From 8e1200c728d43722bb8a17e532ec470828cc6f69 Mon Sep 17 00:00:00 2001 From: Jeff Garzik Date: Fri, 2 Aug 2013 14:33:50 -0400 Subject: [PATCH] Block, Transaction: de-serialize via BinaryParser --- Block.js | 36 +++++++++++++++++++----------------- Transaction.js | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+), 17 deletions(-) diff --git a/Block.js b/Block.js index 9feaa0633..5cae78be9 100644 --- a/Block.js +++ b/Block.js @@ -48,25 +48,27 @@ function spec(b) { return buf; }; - Block.prototype.parseHeader = function parseHeader(buf) { - if (buf.length != 80) - throw new VerificationError('Block header length invalid'); + Block.prototype.parse = function parse(parser, headerOnly) { + this.version = parser.word32le(); + this.prev_hash = parser.buffer(32); + this.merkle_root = parser.buffer(32); + this.timestamp = parser.word32le(); + this.bits = parser.word32le(); + this.nonce = parser.word32le(); - var vars = Binary.parse(buf) - .word32lu('version') - .buffer('prev_hash', 32) - .buffer('merkle_root', 32) - .word32lu('timestamp') - .word32lu('bits') - .word32lu('nonce') - .vars; + this.txs = []; + this.size = 0; - this.version = vars.version; - this.prev_hash = vars.prev_hash; - this.merkle_root = vars.merkle_root; - this.timestamp = vars.timestamp; - this.bits = vars.bits; - this.nonce = vars.nonce; + if (headerOnly) + return; + + var txCount = parser.varInt(); + + for (i = 0; i < txCount; i++) { + var tx = new Transaction(); + tx.parse(parser); + this.txs.push(tx); + } }; Block.prototype.calcHash = function calcHash() { diff --git a/Transaction.js b/Transaction.js index fd758b1e1..28fbd98a8 100644 --- a/Transaction.js +++ b/Transaction.js @@ -575,6 +575,40 @@ function spec(b) { return this; }; + Transaction.prototype.parse = function (parser) { + if (Buffer.isBuffer(parser)) { + parser = new Parser(parser); + } + + var i, sLen, startPos = parser.pos; + + this.version = parser.word32le(); + + var txinCount = parser.varInt(); + + this.ins = []; + for (j = 0; j < txinCount; j++) { + var txin = new TransactionIn(); + txin.o = parser.buffer(36); // outpoint + sLen = parser.varInt(); // script_len + txin.s = parser.buffer(sLen); // script + txin.q = parser.word32le(); // sequence + this.ins.push(txin); + } + + var txoutCount = parser.varInt(); + + this.outs = []; + for (j = 0; j < txoutCount; j++) { + var txout = new TransactionOut(); + txout.v = parser.buffer(8); // value + sLen = parser.varInt(); // script_len + txout.s = parser.buffer(sLen); // script + this.outs.push(txout); + } + + this.lock_time = parser.word32le(); + }; var TransactionInputsCache = exports.TransactionInputsCache = function TransactionInputsCache(tx)