Data structures / Merkle trees

Merkle trees

Hash the hashes until one value is left. Then prove any single leaf belongs, using only a handful of its neighbours.

Intermediate7 steps~6 min
Leaves — transactions and their hashes
Branches — hashes of two children
Root — one hash for the whole tree
// THE SHORT VERSION

In 30 seconds

A Merkle tree sums up a whole set of data in one hash. Every item is hashed, the hashes are paired and hashed again, and so on up to a single root.

Change any item and the root changes.

To prove one item belongs you need only the sibling hashes along its path to the root, about log₂ n of them, instead of the whole data set.

Merkle trees, step by step

STEPS01 / 07

Hashes are real SHA-256, shown as their first 8 hex characters. Parents hash the two full 32-byte child digests joined together.

STEP 01 / 07 A list of transactions
THE MATH
block = [A, B, C, D]
  1. Step 1: A list of transactions. We want one short value that commits to the whole list — and lets anyone prove a single item is in it.
  2. Step 2: Hash every leaf. Each transaction is hashed on its own. These leaf hashes are the bottom row of the tree.
  3. Step 3: Hash the pairs. Neighbouring hashes are glued together and hashed again. Each level has half as many nodes as the one below.
  4. Step 4: Reach the root. The last hash standing is the Merkle root. A block header stores only this, yet it depends on every transaction.
  5. Step 5: Prove one leaf. To show C is included you send its siblings along the path. The verifier rebuilds the root and compares it with the header.
  6. Step 6: Tampering shows. Change any leaf and every hash above it changes. Forging a matching root would mean breaking SHA-256.
  7. Step 7: Why it scales. A million transactions need a 20-hash proof — about 640 bytes. That is how light wallets verify payments.
VALUES SO FAR
leavesA B C Ddata
H(C)····leaf
H(AB)····branch
H(CD)····branch
root····public
proof····proof
root′····tampered
1M····proof
// AFTER

Learn next

Nothing builds on this one yet. See every data structures concept.

Spotted a mistake on this page?