Bitcoinjs-lib: Block.calculateMerkleRoot

Created on 10 Mar 2018  路  4Comments  路  Source: bitcoinjs/bitcoinjs-lib

Error encountered when passing transactions array from bitcoind JSON-RPC "getBlockTemplate" (without modification) to Block.calculateMerkleRoot. Likely I am using it incorrectly?

CODE:

    client.getBlockTemplate( function(error, template) {
        if (error) return console.log(error);
        merkleRoot=bitcoinjs.Block.calculateMerkleRoot(template.transactions);      
    }); 

ERROR:

C:\Users\corbi\OneDrive\Documents\NodeJS\node_modules\typeforce\index.js:23
          throw tfSubError(e, i)
          ^
Error: Expected property "0.getHash" of type Function, got undefined
    at tfSubError (C:\Users\corbi\OneDrive\Documents\NodeJS\node_modules\typeforce\errors.js:93:9)
    at C:\Users\corbi\OneDrive\Documents\NodeJS\node_modules\typeforce\index.js:23:17
    at Array.every (<anonymous>)
    at _arrayOf (C:\Users\corbi\OneDrive\Documents\NodeJS\node_modules\typeforce\index.js:19:20)
    at typeforce (C:\Users\corbi\OneDrive\Documents\NodeJS\node_modules\typeforce\index.js:196:9)
    at typeforce (C:\Users\corbi\OneDrive\Documents\NodeJS\node_modules\typeforce\index.js:202:10)
    at Function.Block.calculateMerkleRoot (C:\Users\corbi\OneDrive\Documents\NodeJS\node_modules\bitcoinjs-lib\src\block.js:153:3)
    at C:\Users\corbi\OneDrive\Documents\NodeJS\Miner\miner.js:11:31
    at C:\Users\corbi\OneDrive\Documents\NodeJS\node_modules\bitcoin\lib\index.js:37:8
    at C:\Users\corbi\OneDrive\Documents\NodeJS\node_modules\bitcoin\lib\jsonrpc.js:138:13
how to / question / docs

Most helpful comment

Using the code recommended by dabura667.

All 4 comments

You need to turn each transaction into a Transaction object using bitcoinjs.Transaction.fromHex(rawtx) etc.

What I would recommend:

Look at what Block.calculateMerkleRoot does.

https://github.com/bitcoinjs/bitcoinjs-lib/blob/5b0ccb6f68ed9189dc3e382d78e108046974910f/src/block.js#L152-L161

It basically does transaction.getHash() on each transaction and runs it through fastmerkle

So maybe try: (safe-buffer is not related, but you should use if you plan to deploy on old versions of NodeJS or open source it, there was a bug in Buffer for old NodeJS versions)

// npm install merkle-lib safe-buffer
var fastMerkleRoot = require('merkle-lib/fastRoot')
Buffer = require('safe-buffer')

client.getBlockTemplate( function(error, template) {
    if (error) return console.log(error);
    txhashes = template.transactions.map(function(tx){ return Buffer.from(tx.txid, 'hex').reverse() })
    merkleRoot = fastMerkleRoot(txhashes, bitcoinjs.crypto.hash256)
})

How did you go @DawBin ?

Using the code recommended by dabura667.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

tuyennvtb picture tuyennvtb  路  3Comments

dakk picture dakk  路  3Comments

hoshsadiq picture hoshsadiq  路  3Comments

LeonYanghaha picture LeonYanghaha  路  3Comments

zhaozhiming picture zhaozhiming  路  3Comments