diff --git a/lib/bcoin/block.js b/lib/bcoin/block.js index 795f79aa..c65ee44c 100644 --- a/lib/bcoin/block.js +++ b/lib/bcoin/block.js @@ -22,8 +22,6 @@ function Block(data, subtype) { if (!(this instanceof Block)) return new Block(data, subtype); - assert(typeof data.hash !== 'string'); - this.type = 'block'; this.subtype = subtype || data.subtype; this.version = data.version; @@ -235,6 +233,18 @@ Block.prototype.getMerkleRoot = function getMerkleRoot() { return utils.toHex(tree[tree.length - 1]); }; +Block.prototype.getMerkleRoot = function getMerkleRoot() { + var hashes = []; + var i; + + assert(this.subtype === 'block'); + + for (i = 0; i < this.txs.length; i++) + hashes.push(this.txs[i].hash()); + + return utils.getMerkleRoot(hashes); +}; + Block.prototype._verify = function _verify() { var uniq = {}; var i, tx, hash; diff --git a/lib/bcoin/ec.js b/lib/bcoin/ec.js index c09b786b..e218f5b3 100644 --- a/lib/bcoin/ec.js +++ b/lib/bcoin/ec.js @@ -38,6 +38,10 @@ ec.random = function random(size) { return new Buffer(elliptic.rand(size)); }; +bn.prototype.toBuffer = function toBuffer(order, size) { + return new Buffer(this.toArray(order, size)); +}; + ec.verify = function verify(msg, sig, key, historical) { if (key.getPublicKey) key = key.getPublicKey(); diff --git a/lib/bcoin/protocol/framer.js b/lib/bcoin/protocol/framer.js index 32ff134a..d95bfea7 100644 --- a/lib/bcoin/protocol/framer.js +++ b/lib/bcoin/protocol/framer.js @@ -403,7 +403,9 @@ Framer.block = function _block(block, type) { p = new Buffer(80 + utils.sizeIntv(block.txs.length)); } else { for (i = 0; i < block.txs.length; i++) { - tx = block.txs[i].render(); + tx = block.txs[i].render + ? block.txs[i].render() + : Framer.tx(block.txs[i]); txs.push(tx); txSize += tx.length; } diff --git a/lib/bcoin/tx.js b/lib/bcoin/tx.js index 720a8a6d..5ac1f6cb 100644 --- a/lib/bcoin/tx.js +++ b/lib/bcoin/tx.js @@ -22,8 +22,6 @@ function TX(data, block) { if (!data) data = {}; - assert(typeof data.hash !== 'string'); - this.type = 'tx'; this.version = data.version || 1; this.inputs = []; diff --git a/lib/bcoin/utils.js b/lib/bcoin/utils.js index ed669904..a6352dfb 100644 --- a/lib/bcoin/utils.js +++ b/lib/bcoin/utils.js @@ -1587,3 +1587,38 @@ utils.once = function once(callback) { return onceFn; }; + +utils.buildMerkleTree = function buildMerkleTree(items) { + var tree = items.slice(); + var i, j, size, i2, hash; + + j = 0; + size = items.length; + + for (; size > 1; size = ((size + 1) / 2) | 0) { + for (i = 0; i < size; i += 2) { + i2 = Math.min(i + 1, size - 1); + if (i2 === i + 1 && i2 + 1 === size + && tree[j + i] === tree[j + i2]) { + return; + } + hash = Buffer.concat([tree[j + i], tree[j + i2]]); + hash = utils.dsha256(hash); + tree.push(hash); + } + j += size; + } + + if (!tree.length) + return; + + return tree; +}; + +utils.getMerkleRoot = function getMerkleRoot(items) { + var tree = utils.buildMerkleTree(items); + if (!tree) + return; + + return utils.toHex(tree[tree.length - 1]); +};