From dd4596a44ade32daabf72966d78977c37a49232a Mon Sep 17 00:00:00 2001 From: Daniel Cousens Date: Fri, 7 Oct 2016 17:03:12 +1100 Subject: [PATCH] block: use merkle-lib instead of inline calculation --- package.json | 1 + src/block.js | 24 ++++++------------------ 2 files changed, 7 insertions(+), 18 deletions(-) diff --git a/package.json b/package.json index 85698d1..95520df 100644 --- a/package.json +++ b/package.json @@ -57,6 +57,7 @@ "create-hash": "^1.1.0", "create-hmac": "^1.1.3", "ecurve": "^1.0.0", + "merkle-lib": "^1.0.0", "randombytes": "^2.0.1", "typeforce": "^1.8.7", "varuint-bitcoin": "^1.0.4", diff --git a/src/block.js b/src/block.js index d65609b..23ae976 100644 --- a/src/block.js +++ b/src/block.js @@ -1,7 +1,7 @@ -var createHash = require('create-hash') var bufferutils = require('./bufferutils') var bcrypto = require('./crypto') var bufferReverse = require('buffer-reverse') +var fastMerkleRoot = require('merkle-lib/fastRoot') var Transaction = require('./transaction') @@ -134,25 +134,13 @@ Block.calculateTarget = function (bits) { } Block.calculateMerkleRoot = function (transactions) { - var length = transactions.length - if (length === 0) throw TypeError('Cannot compute merkle root for zero transactions') + if (transactions.length === 0) throw TypeError('Cannot compute merkle root for zero transactions') - var hashes = transactions.map(function (transaction) { return transaction.getHash() }) + var hashes = transactions.map(function (transaction) { + return transaction.getHash() + }) - while (length > 1) { - var j = 0 - - for (var i = 0; i < length; i += 2, ++j) { - var hasher = createHash('sha256') - hasher.update(hashes[i]) - hasher.update(i + 1 !== length ? hashes[i + 1] : hashes[i]) - hashes[j] = bcrypto.sha256(hasher.digest()) - } - - length = j - } - - return hashes[0] + return fastMerkleRoot(hashes, bcrypto.hash256) } Block.prototype.checkMerkleRoot = function () {