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
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.
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.
Most helpful comment
Using the code recommended by dabura667.