Bitcoin

hash – How to calculate Merkle root? Need a twist?

hash – How to calculate Merkle root? Need a twist? – Bitcoin Stack Exchange







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)
  1. All transaction data has been reversed (including Coinbase).
  2. Calculated hash (bytes).
  3. Calculated the merkle root (bytes).
  4. I reversed the Merkroot.
  5. 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.

Jack Green is a new contributor to this site. Be careful when asking for clarification, making comments, and responding. Check out our Code of Conduct.

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

Related Articles

Back to top button