Verify Merkle Root of 2 Transactions

This section describes how to verify the Merkle Root of 2 transactions in a Bitcoin block.

Once we learned how to calculating SHA256 hash in Python, we can try to verify the Merkle Root now.

Get the block # 492 (it has only 2 transactions) from Bitcoin Test Network:

```C:\>\local\bitcoin-0.15.1\bin\bitcoin-cli -testnet getblockhash 492
000000001b6611060bea0c68a9e9a67cc7addf16eded69f45cd3c246ec08f0ff

C:\>\local\bitcoin-0.15.1\bin\bitcoin-cli -testnet getblock
000000001b6611060bea0c68a9e9a67cc7addf16eded69f45cd3c246ec08f0ff

...
"height": 492,
"version": 1,
"versionHex": "00000001",
"merkleroot":
"8a1488b7ee767f0e03840ad0eac6277762e4bba8481d38a38ed1df1d564db361",
"tx": [
"e788ae269c53d6968fbff98791dc33a21c5758f65c91094f81c907769bdf0a99",
"3c5b5e142132493520fafd10989a64d42a43d94bae44dd618936667e7fd947dc"
],
...
```

Enter following Python script:

```#- Merkle-Root-Hash-of-testnet-492.py
#- Copyright (c) 2018, HerongYang.com, All Rights Reserved.

import hashlib
import binascii

def doubleSha256(hex):
bin = binascii.unhexlify(hex)
hash = hashlib.sha256(bin).digest()
hash2 = hashlib.sha256(hash).digest()
return binascii.hexlify(hash2)

# Getting transaction hashes from Bitcoin Core
h1 = "e788ae269c53d6968fbff98791dc33a21c5758f65c91094f81c907769bdf0a99"
h2 = "3c5b5e142132493520fafd10989a64d42a43d94bae44dd618936667e7fd947dc"

# Converting them in little-endian hex notation
h1 = binascii.hexlify(binascii.unhexlify(h1)[::-1])
h2 = binascii.hexlify(binascii.unhexlify(h2)[::-1])

# Concatenating the pair
hex = h1+h2

# Taking double-SHA256 hash
hash = doubleSha256(hex)

# Converting result to big-endian hex notation
root = binascii.hexlify(binascii.unhexlify(hash)[::-1])
root = str(root,"ascii")

# Comparing with Merkle Root on Bitcoin Core
exp = "8a1488b7ee767f0e03840ad0eac6277762e4bba8481d38a38ed1df1d564db361";
print("Match the Bitcoin network: "+str(root==exp))
print("Merkle Root:\n   "+root)
```

Enter following Python script:

```C:\>Python Merkle-Root-Hash-of-testnet-492.py

Match the Bitcoin network: True
Merkle Root:
8a1488b7ee767f0e03840ad0eac6277762e4bba8481d38a38ed1df1d564db361
```

This confirms our Merkle Root hash algorithm is correct.

Table of Contents