hash – How to calculate Merkle root? Need a twist?
Bitcoin Stack Exchange is a question and answer site for Bitcoin users, developers, and enthusiasts. It only takes 1 minute to sign up.
Sign up to join this community
Anyone can ask questions
Anyone can answer
The best answers are voted on and promoted to the top.
Asked
copy
Episode 27
I downloaded the necessary information and created Coinbase. Then I calculated the merkle root… but when I submit the block I always get the error message “bad-txnmerkleroot”. Here is my code:
def dblsha(d)->bytes:
return hashlib.sha256(hashlib.sha256(d).digest()).digest()
def makeMerkleRoot()->None:
global merkleroot,txnlist
txnlist=(coinbase)+(unhexlify(a('data')) for a in tmpl('transactions'))
merklehashes=(dblsha
while len(merklehashes)>1:
if len(merklehashes)%2:
merklehashes.append(merklehashes(-1))
merklehashes=(dblsha(merklehashes(i)+merklehashes(i+1)) for i in range(0,len(merklehashes),2))
merkleroot=merklehashes(0)(::-1)
- All transaction data has been reversed (including Coinbase).
- Calculated hash (bytes).
- Calculated the merkle root (bytes).
- I reversed the Merkroot.
- Converted merkleroot (bytes) to hexadecimal. However, no matter how many times I invert it or not, I always get the error ‘bad-txnmerkleroot’. Do I actually need to flip the data during calculations? By the way, I tested your code in regtest. Need to test your code on the main network? Are there other reasons why the ‘bad-txnmerkle’ error occurs? Like Coinbase gone wrong. I really don’t know what to do.
0
There is no need to revert anything. Hashes are never reversed in Bitcoin except for human marking purposes. So if you’re starting from txids obtained from Explorer or RPC output, you’ll need to invert them (to undo the inversion), but other than that, it’s of no use.
About stealing comments and posting them as replies
2