A merkle tree hashes a block's transactions in pairs until one hash remains: the merkle root. Learn how it works and how merkle proofs save space.
Pair, hash, repeat
- Take the txid of every transaction in the block.
- Pair them up and hash each pair together.
- Pair up those hashes and hash again.
- Repeat until a single hash is left: the merkle root.
If there's an odd number at any level, the last hash is paired with a copy of itself.
Why bother?
- Tamper evidence: change any transaction and the root changes, which changes the header hash, which breaks the Proof of work.
- Small proofs: to prove a transaction is in a block you only need the hashes along its path to the root: about 12 hashes for a block of 4,000 transactions. This is how light clients work.
Why proofs stay tiny
A merkle proof needs one hash per level of the tree:
| Transactions in block | Hashes in proof |
|---|---|
| 8 | 3 |
| 1,000 | 10 |
| 4,000 | 12 |
| 1,000,000 | 20 |
That's why a phone wallet can check that a payment is in a block without downloading the whole block. See SPV and light clients.
A known weakness, already handled
Duplicating the last hash at odd levels once allowed two different transaction lists to share a merkle root (CVE-2012-2459). Bitcoin Core detects and rejects such blocks.
Key takeaways
- The merkle root is a single hash built by hashing transactions in pairs.
- It lets an 80-byte header commit to every transaction.
- Merkle proofs show inclusion with only a handful of hashes.
Common questions
What if a block has one transaction?
The merkle root is simply that transaction's txid, as in the genesis block.
Why is the merkle tree needed if every node downloads full blocks?
It makes the header commit to the transactions and enables compact proofs for light clients.
What is a merkle proof?
The list of sibling hashes needed to rebuild the path from one transaction up to the merkle root.
Who invented merkle trees?
Ralph Merkle, in 1979, long before Bitcoin.