Merkle trees
A Merkle tree pairs up transaction hashes repeatedly until one root remains — 32 bytes that commit to every transaction in the block.
In this lesson
- Construct a Merkle root from four transactions
- Verify a Merkle proof step by step
- Explain how light clients use proofs
Prerequisites
- recommended Transactions
Pairs all the way up
Transactions are hashed (leaves), then hashes are hashed in pairs, layer after layer, until a single Merkle root remains. The root goes in the block header; the full list stays in the block body.
A Merkle proof is the set of sibling hashes needed to recompute the root from one leaf — logarithmic in the number of transactions: ~10 hashes instead of 4,000.
import hashlib\n\ndef h(x): return hashlib.sha256(x).digest()\n\ndef root(leaves):\n level = [h(l) for l in leaves]\n while len(level) > 1:\n if len(level) % 2: level.append(level[-1]) # odd node promoted\n level = [h(level[i] + level[i+1]) for i in range(0, len(level), 2)]\n return level[0].hex()
Example · SPV wallets on your phone
A phone wallet cannot store 600 GB of blocks. It downloads only headers, then asks a peer for the Merkle proof of its transaction. Recomputing the root against the header proves inclusion — with no full node required.
| Layer | Nodes | Contents |
|---|---|---|
| Leaves | N | One hash per transaction |
| Middle | N/2, N/4, … | Hashes of pairs below |
| Root | 1 | Commits to everything |
One changed leaf, one changed root
That is the tamper-evidence property in a nutshell: altering any transaction — even flipping one bit — forces a different root, which forces a different block hash, which breaks the chain above it.
Build and break a tree
Hash four transactions into a root, edit one leaf, and watch the proof for that leaf fail.
Order the steps
Practice · server-gradedMatch the parts
Practice · server-gradedPractice exercise
Practice: blockchain basics
Why duplicate the last hash on odd levels?
So every pair is defined. It is a convention, not a security hole — attackers still cannot forge a path.
Can a proof lie?
No — recomputing the root must byte-for-byte match the header hash, which is itself chained to the tip.
Practice
- Blockchain basics Start