Skip to content
KALANBLON
Show contents

Chapter 4 of 6 · 20 min

Merkle trees

By the end of this chapter, you'll be able to

  • Build a Merkle tree and compute its root
  • Produce an inclusion proof for a transaction
  • Verify an inclusion proof with only the block's root
  • Recognise the flaw of odd-length lists and protect against it

A tree of fingerprints

We compute the fingerprint of each transaction: these are the leaves. We group them two by two and hash each pair: that gives the level above. We repeat until only one fingerprint is left: the Merkle root. Only the root is placed in the block header; it summarises all the transactions: changing a single transaction changes the root.

When a level has an odd number of elements, Bitcoin duplicates the last one to form a pair. Remember this detail: it hides a trap.

It recomputes the path from C. For 3,000 transactions, 12 fingerprints are enough.

Step 5 of 5
Text description of the animation
  1. We hash each transaction.
  2. We hash neighbouring pairs.
  3. The root goes into the block header, protected by proof of work.
  4. For C, the phone only receives the "sibling" fingerprints on the path to the root.
  5. It recomputes the path from C. For 3,000 transactions, 12 fingerprints are enough.
import hashlib

def h(data):
    return hashlib.sha256(data).digest()

def merkle_root(transactions):
    level = [h(tx.encode()) for tx in transactions]
    while len(level) > 1:
        if len(level) % 2:                        # odd number: duplicate the last one
            level.append(level[-1])
        level = [h(level[i] + level[i + 1]) for i in range(0, len(level), 2)]
    return level[0]

block = ["Awa -> Mei 15000", "Kofi -> Yao 3000", "Fatou -> Awa 8000", "Mei -> Kofi 1200"]
print("root:", merkle_root(block).hex()[:16])

modified_block = block.copy()
modified_block[2] = "Fatou -> Awa 9000"
print("root after change:", merkle_root(modified_block).hex()[:16])
root: 1307aece20e65cdb
root after change: bffaa863c77065a1

The inclusion proof

A transaction's inclusion proof is the list of sibling fingerprints met while going up from its leaf to the root, with their side (left or right). The verifier starts from the transaction, combines with each sibling in the right order, and compares the result with the root it knows (the one in the block header).

import hashlib

def h(data):
    return hashlib.sha256(data).digest()

def levels(transactions):
    level = [h(tx.encode()) for tx in transactions]
    all_levels = [level]
    while len(level) > 1:
        if len(level) % 2:
            level = level + [level[-1]]
        level = [h(level[i] + level[i + 1]) for i in range(0, len(level), 2)]
        all_levels.append(level)
    return all_levels

def proof(transactions, index):
    path = []
    for level in levels(transactions)[:-1]:
        if len(level) % 2:
            level = level + [level[-1]]
        sibling = index ^ 1                        # the neighbour: even index → +1, odd → −1
        path.append((level[sibling], "right" if sibling > index else "left"))
        index //= 2
    return path

def verify_proof(transaction, path, root):
    current = h(transaction.encode())
    for sibling, side in path:
        current = h(current + sibling) if side == "right" else h(sibling + current)
    return current == root

block = [f"payment {i}" for i in range(3000)]
root = levels(block)[-1][0]
p = proof(block, 1789)
print("proof size:", len(p), "fingerprints for", len(block), "transactions")
print("payment 1789 included :", verify_proof("payment 1789", p, root))
print("fake payment included :", verify_proof("payment 99999", p, root))
proof size: 12 fingerprints for 3000 transactions
payment 1789 included : True
fake payment included : False

The proof has the size of the logarithm of the number of transactions: 12 fingerprints of 32 bytes for 3,000 transactions, under 400 bytes. That is what lets light wallets (SPV, Simplified Payment Verification) check a payment with only the block headers, a few dozen megabytes for Bitcoin's entire history.

Mini-lab: the size of proofsPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Your turn

Worked exercise

Worked exercise: the light wallet

A light wallet only knows the blocks' roots. A server sends it, for each expected payment, the block number, the transaction and the proof. Write check_payments(roots, answers) that displays confirmed or REJECTED for each answer. Build two blocks, an honest answer for each, an answer where the server changed the amount, and an answer presenting a proof from another block.

Hint 1
roots is a dictionary block number → root. For each answer, get the root with roots.get(answer["block"]).
Hint 2
Reuse levels, proof and verify_proof from the chapter: the wallet only calls verify_proof.
Show the solution and common mistakes
import hashlib

def h(d):
    return hashlib.sha256(d).digest()

def levels(transactions):
    level = [h(tx.encode()) for tx in transactions]
    all_levels = [level]
    while len(level) > 1:
        if len(level) % 2:
            level = level + [level[-1]]
        level = [h(level[i] + level[i + 1]) for i in range(0, len(level), 2)]
        all_levels.append(level)
    return all_levels

def proof(transactions, index):
    path = []
    for level in levels(transactions)[:-1]:
        if len(level) % 2:
            level = level + [level[-1]]
        sibling = index ^ 1
        path.append((level[sibling], "right" if sibling > index else "left"))
        index //= 2
    return path

def verify_proof(tx, path, root):
    current = h(tx.encode())
    for sibling, side in path:
        current = h(current + sibling) if side == "right" else h(sibling + current)
    return current == root

blocks = {101: ["Awa -> Mei 15000", "Kofi -> Yao 3000", "Fatou -> Mei 2500"],
          102: ["Yao -> Awa 700", "Mei -> Kofi 1200", "Awa -> Fatou 400", "Kofi -> Mei 9000", "Yao -> Fatou 50"]}
roots = {n: levels(txs)[-1][0] for n, txs in blocks.items()}        # all the wallet knows

answers = [
    {"block": 101, "tx": "Awa -> Mei 15000", "proof": proof(blocks[101], 0)},
    {"block": 102, "tx": "Kofi -> Mei 9000", "proof": proof(blocks[102], 3)},
    {"block": 101, "tx": "Awa -> Mei 150000", "proof": proof(blocks[101], 0)},
    {"block": 101, "tx": "Kofi -> Mei 9000", "proof": proof(blocks[102], 3)},
]

def check_payments(roots, answers):
    for a in answers:
        root = roots.get(a["block"])
        ok = root is not None and verify_proof(a["tx"], a["proof"], root)
        print(f"block {a['block']} | {a['tx']:<18} | {'confirmed' if ok else 'REJECTED'}")

check_payments(roots, answers)
block 101 | Awa -> Mei 15000   | confirmed
block 102 | Kofi -> Mei 9000   | confirmed
block 101 | Awa -> Mei 150000  | REJECTED
block 101 | Kofi -> Mei 9000   | REJECTED

The wallet never saw the other transactions, and yet it detects the changed amount and the proof that came from another block. It only trusts the roots, themselves protected by the headers' proof of work.

Common mistakes:

  • Always combining fingerprints in the same order (h(current + sibling)): the proof fails as soon as the sibling is on the left.
  • Not duplicating the last element of an odd level, or doing it differently in the builder and the verifier: the roots no longer match.
  • Trusting a root sent by the same server as the proof: the root must come from the header, checked separately.

Summary

  1. 1A Merkle tree hashes the transactions two by two up to a single root, placed in the block header.
  2. 2Changing a single transaction changes the root.
  3. 3An inclusion proof only contains the sibling fingerprints along the path: its size is logarithmic.
  4. 4Duplicating the odd element creates different lists with the same root: duplicate transactions must be rejected.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.