Merkle Trees, Inclusion & Non-Inclusion Proofs
Move from O(N) hash chains to O(log N) Merkle proofs, block second-preimage attacks with 0x00/0x01 prefixes, and weigh Sparse Merkle vs Verkle trees.
In this lesson (3 bite-sized sections)
From O(N) hash chains to O(log N) Merkle proofs
A linear hash chain (H_n = Hash(H_{n-1} || entry_n)) makes an audit log tamper-evident, because rewriting entry 5 invalidates every hash from 5 to N. The problem is verification cost: to prove to a light client that entry 5 really leads to today's signed head H_1,000,000, the client must download and re-hash all 999,995 entries in between. At billions of records, linear chains are unverifiable for mobile or browser clients.
A binary Merkle tree arranges N records as leaves and hashes pairs bottom-up until a single 32-byte Merkle Root commits to the entire dataset. To prove that leaf L exists in a tree of 1 billion records, the server sends only the log2(1,000,000,000) = 30 sibling hashes along L's path to the root (just 960 bytes total!). The client hashes L upward with those 30 siblings and checks whether the result matches the trusted signed root.

Second-preimage attacks and 0x00 vs 0x01 domain separation
Naive Merkle implementations hash leaves and internal nodes with the exact same function: H(leaf) and H(left || right). That invites a classic second-preimage attack. If an attacker takes the 64-byte concatenation left || right of any existing internal node and presents those 64 bytes as a fake leaf record, its hash equals the internal node's hash, and the truncated sibling path still climbs to the identical signed Merkle root!
The fix from RFC 6962 is one byte of domain separation:
- Leaf hash:
SHA256(0x00 || leaf_bytes) - Interior node hash:
SHA256(0x01 || left_hash || right_hash)
Because every leaf preimage starts with 0x00 and every internal preimage starts with 0x01, no internal node can ever masquerade as a leaf (or vice versa).
Proving absence: Sparse Merkle, Merkle Patricia, and Verkle trees
Standard append-only binary Merkle trees prove inclusion cleanly, but cannot easily prove non-inclusion ("key X does NOT exist in this map"). To prove absence, key-value state commitments map keys to deterministic positions:
- Sparse Merkle Trees (SMTs) define a fixed-depth binary tree of depth 256 where every possible 256-bit key hash occupies a fixed leaf slot. Empty subtrees collapse to precomputed default hashes, so proving key
Kis absent simply provides the inclusion proof showing slotHash(K)holds the empty sentinel. - Merkle Patricia Tries (MPTs) compress long single-child paths into radix-16 extension nodes (used by Ethereum's execution state) to shrink storage depth, though proofs carry all 15 sibling hashes per level (~3-4 KB per proof).
- Verkle Trees replace hash-based siblings with vector commitments (such as KZG or IPA polynomial commitments) over wide 256-way branching nodes, collapsing proof sizes from kilobytes down to ~150-200 bytes for stateless verification.
| Structure | Inclusion proof | Non-inclusion proof | Proof size (10M keys) | Primary use case |
|---|---|---|---|---|
| Linear hash chain | O(N) | O(N) | Hundreds of MB | Small local audit logs |
| Append-only Binary Merkle | O(log N) | Not supported directly | ~768 bytes (24 hashes) | Certificate Transparency, Rekor |
| Sparse Merkle Tree (SMT) | O(log N) / 256 max | Yes (empty leaf proof) | ~1-2 KB (compressed) | Key Transparency directories, revocations |
| Merkle Patricia Trie (MPT) | O(log16 N) | Yes (missing branch) | ~3-4 KB (15 siblings/level) | Ethereum historical state trie |
| Verkle Tree | O(log256 N) | Yes (vector commitment) | ~150-200 bytes | Stateless light clients, rollups |
Match each verifiable-data requirement to the right tree structure.
Sort 4 more items to check
Recap: binary Merkle trees shrink inclusion proofs from O(N) to O(log N), 0x00/0x01 prefixes eliminate second-preimage leaf forgery, Sparse Merkle Trees add non-inclusion proofs for verifiable key directories, and Verkle trees trade hash simplicity for tiny vector-commitment proofs.
Sources: RFC 6962, Certificate Transparency Merkle Trees · Revocation Transparency, Laurie and Kasper · Verkle Trees, Kuszmaul
import hashlib
import math
def h_leaf(data: bytes) -> bytes:
return hashlib.sha256(b"\x00" + data).digest()
def h_node(left: bytes, right: bytes) -> bytes:
return hashlib.sha256(b"\x01" + left + right).digest()
records = [f"tx-{i}:amount={100 + i * 25}".encode() for i in range(8)]
levels = [[h_leaf(r) for r in records]]
while len(levels[-1]) > 1:
cur = levels[-1]
levels.append([h_node(cur[i], cur[i + 1]) for i in range(0, len(cur), 2)])
def make_proof(idx: int) -> list[tuple[bytes, bool]]:
return [(layer[(idx >> d) ^ 1], ((idx >> d) & 1) == 0) for d, layer in enumerate(levels[:-1])]
def verify(record: bytes, proof: list[tuple[bytes, bool]], root: bytes) -> bool:
cur = h_leaf(record)
for sib, on_right in proof:
cur = h_node(cur, sib) if on_right else h_node(sib, cur)
return cur == root
root, proof = levels[-1][0], make_proof(5)
print(f"Root: {root.hex()[:20]}... | proof: {len(proof)} siblings ({len(proof) * 32} B)")
print(f"Valid tx-5: {verify(records[5], proof, root)} | Tampered: {verify(b'tx-5:fake', proof, root)}")
for n in (8, 1_000_000, 1_000_000_000):
k = math.ceil(math.log2(n))
print(f"N={n:>13,d} -> {k:>2} siblings ({k * 32:>3} bytes)")Apply
Your turn
The task this lesson builds to.
Specify the verifiable proof-of-reserves and user-balance audit tree for a financial custodian holding 50 million user accounts so any user can verify their exact balance is included (or confirm an account is absent) in under 2 KB of proof data.
Think about
- Why does a linear hash chain fail for 50 million users verifying independently?
- How do you prevent second-preimage forgery and hidden negative-balance manipulation?
- Should you use a plain binary Merkle tree, a Sparse Merkle Tree, or a Merkle Sum Tree?
Draft your design answer here Save your draft, compare against the model answer, and track progress.
Practice
Make it stick
A second problem on the same idea, so it survives past today.
Compare migrating a 100-million-key verifiable state directory from a Merkle Patricia Trie (MPT) to either a Sparse Merkle Tree (SMT) or a Verkle Tree for a stateless network where every block must carry 500 state proofs within a 256 KB network budget.
Think about
- How big are 500 proofs under an MPT versus a compressed SMT versus a Verkle Tree?
- What cryptographic assumptions and update-time trade-offs does a Verkle Tree introduce compared to hash-only trees?
- How does proof deduplication (multiproofs) narrow the gap?
Draft your design answer here Save your draft, compare against the model answer, and track progress.