A Merkle tree is a way to commit to a whole list of data with one hash. You hash every item to make the leaves, then repeatedly hash pairs of hashes together until a single Merkle root remains. Change any item and the root changes. A Merkle proof shows that one item is in the list by supplying only the sibling hashes on the path from that leaf to the root, about log₂(n) hashes, so proving one transaction among a million takes around 20 hashes instead of the full million. Blockchains put Merkle roots in block headers so light clients, bridges and contracts can verify individual transactions, balances or claims without downloading everything.
How a Merkle tree is built
Take four transactions, A to D. Hash each one, then hash the hashes in pairs:
root = H(H_AB || H_CD)
/ \
H_AB = H(H_A || H_B) H_CD = H(H_C || H_D)
/ \ / \
H_A = H(A) H_B = H(B) H_C = H(C) H_D = H(D)
H is a cryptographic hash such as SHA-256 or Keccak-256, and || means concatenation. The root is 32 bytes no matter how many items the tree holds. Because hash functions are collision-resistant, nobody can find a different list of items that produces the same root. That makes the root a commitment: publish it, and you have fixed the entire list without revealing or storing it.
This is what a block header's merkle_root does in Bitcoin. As explained in how Bitcoin mining works, the 80-byte header contains the root of the block's transactions, so the proof of work over the header also secures every transaction inside it.
How does a Merkle proof work?
To prove that C is in the tree, you don't need A, B or D. You need:
- C itself (the verifier hashes it to get
H_C). H_D, its sibling, to computeH_CD.H_AB, the sibling one level up, to compute the root.
The verifier recomputes the root from those pieces and compares it with the trusted root, for example one taken from a block header. If they match, C is in the tree at that position. Forging a proof would require finding a hash collision.
Proof size grows with the tree's depth, not its size:
| Items in the tree | Hashes in a proof | Proof size at 32 bytes each |
|---|---|---|
| 1,000 | 10 | 320 bytes |
| 1,000,000 | 20 | 640 bytes |
| 1,000,000,000 | 30 | 960 bytes |
That logarithmic scaling is the whole point. It is why a phone wallet can check that a payment was included in a block, and why a smart contract can verify one claim out of millions while storing only 32 bytes.
A working example in Python
This builds a tree, produces a proof and verifies it. It uses a one-byte prefix to separate leaves from internal nodes, a detail explained in the pitfalls section below.
import hashlib
def h(b: bytes) -> bytes:
return hashlib.sha256(b).digest()
def leaf_hash(data: bytes) -> bytes:
return h(b"\x00" + data) # leaves get a 0x00 prefix...
def node_hash(left: bytes, right: bytes) -> bytes:
return h(b"\x01" + left + right) # ...internal nodes get 0x01
def build_levels(items):
level = [leaf_hash(x) for x in items]
levels = [level]
while len(level) > 1:
nxt = []
for i in range(0, len(level), 2):
if i + 1 < len(level):
nxt.append(node_hash(level[i], level[i + 1]))
else:
nxt.append(level[i]) # odd node is carried up unchanged
level = nxt
levels.append(level)
return levels
def get_proof(levels, index):
proof = []
for level in levels[:-1]:
sibling = index ^ 1
if sibling < len(level):
proof.append((level[sibling], sibling < index)) # (hash, sibling_is_left)
index //= 2
return proof
def verify(root, item, proof):
acc = leaf_hash(item)
for sibling, is_left in proof:
acc = node_hash(sibling, acc) if is_left else node_hash(acc, sibling)
return acc == root
txs = [b"alice->bob 5", b"bob->carol 2", b"carol->dave 1", b"dave->erin 7", b"erin->frank 3"]
levels = build_levels(txs)
root = levels[-1][0]
proof = get_proof(levels, 2)
print(root.hex())
print(len(proof), verify(root, txs[2], proof)) # 3 True
print(verify(root, b"carol->dave 1000", proof)) # False
Every tree design must answer the same questions this code answers: which hash, how leaves are encoded, how an odd node is handled, and how the verifier knows whether a sibling goes on the left or the right. Two implementations that answer any of them differently produce different roots for the same data.
Where blockchains use Merkle trees
Bitcoin transactions. Each block's header commits to its transaction IDs with a binary tree of double SHA-256 hashes. When a level has an odd number of nodes, Bitcoin duplicates the last one. Section 8 of the Bitcoin whitepaper describes simplified payment verification (SPV): a light client keeps only headers and asks for a Merkle branch proving its transaction is in a block. Sidechains and layers that read Bitcoin use the same trick; Stacks contracts, for example, verify Bitcoin transactions with Merkle proofs against headers they already know, and Dogecoin's merged mining with Litecoin relies on two Merkle branches per block.
Ethereum state. Ethereum headers carry three roots: stateRoot, transactionsRoot and receiptsRoot. They are Merkle-Patricia tries, a 16-way radix tree keyed by path and hashed with Keccak-256, so a proof shows both that a key exists and what its value is. Any account balance or storage slot can be proven against a block's stateRoot with eth_getProof (EIP-1186):
# Prove storage slot 0 of a contract at the latest block
cast proof 0xContractAddress 0 --rpc-url "$RPC_URL"
These proofs are larger than binary ones, typically several hundred bytes to a few kilobytes, because each step includes up to 16 child hashes. That cost is one reason proving Ethereum in zero knowledge is hard, as covered in what zkEVM types 1 through 4 mean, and Ethereum researchers have proposed moving state to a different tree design to make proofs smaller.
Rollup withdrawals and bridges. A rollup posts a state root to L1, and a user withdrawing funds submits a Merkle proof that their withdrawal message is included under it. That is the final "claim" step when you move assets out of a ZK rollup like Linea.
Data availability. Celestia uses namespaced Merkle trees, where every node also records the range of namespaces beneath it, so a rollup can prove it received all of its own data and nothing was omitted. See how Celestia's data availability sampling works.
Privacy coins. Zcash appends every shielded note commitment to a Merkle tree, and spending proves in zero knowledge that you know a path to some leaf without revealing which one, as described in how Zcash shielded transactions work.
Allowlists and airdrops. A contract stores one root and lets each eligible address claim with a proof, instead of storing thousands of addresses.
Verifying a proof in a smart contract
For the allowlist case, OpenZeppelin provides a matching pair: @openzeppelin/merkle-tree builds the tree off-chain and MerkleProof verifies on-chain. Both hash leaves twice, which keeps a leaf from ever being mistaken for an internal node.
import { StandardMerkleTree } from "@openzeppelin/merkle-tree";
const values = [
["0x1111111111111111111111111111111111111111", "5000000000000000000"],
["0x2222222222222222222222222222222222222222", "2500000000000000000"],
];
const tree = StandardMerkleTree.of(values, ["address", "uint256"]);
console.log("root:", tree.root);
const proof = tree.getProof(1); // proof for the second entry
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
contract Allowlist {
bytes32 public immutable root;
mapping(address => bool) public claimed;
constructor(bytes32 root_) {
root = root_;
}
function claim(uint256 amount, bytes32[] calldata proof) external {
require(!claimed[msg.sender], "already claimed");
bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(msg.sender, amount))));
require(MerkleProof.verify(proof, root, leaf), "invalid proof");
claimed[msg.sender] = true;
// pay out `amount` here
}
}
OpenZeppelin sorts each pair before hashing, so proofs don't need left or right flags. The leaf encoding in Solidity must match the library exactly: abi.encode of the same types, hashed twice.
Common pitfalls
Leaves that look like nodes. If leaves and internal nodes are hashed the same way, an attacker can present an internal node, which is just 64 bytes of two child hashes, as if it were a leaf. This second preimage trick lets them "prove" data that was never in the list. Prefix leaves and nodes differently, as in the Python example, or double-hash leaves like OpenZeppelin. Bitcoin's tree has no such separation, which is why a 64-byte transaction can be confused with an internal node; the proposed Consensus Cleanup soft fork (BIP-54), not activated on mainnet at the time of writing, would make 64-byte transactions invalid.
Duplicated odd nodes. Bitcoin's rule of duplicating the last node means a list ending [..., X] and one ending [..., X, X] can share a root. This caused a real vulnerability (CVE-2012-2459), where a block could be mutated into an invalid one with the same header hash. Prefer carrying the odd node up or padding with a fixed empty value.
Encoding mismatches. The most common bug in production is an off-chain tree built with abi.encodePacked or a different field order from the contract's leaf. The proof then fails for everyone. Generate test vectors from the same library you deploy with.
Membership is not non-membership. A plain Merkle proof shows an item is in the tree. Proving something is absent requires a sorted tree (show the two neighbours) or a sparse Merkle tree keyed by the item.
Trusting the root. A proof is only as good as the root you check it against. A root from an untrusted RPC, an unfinalised block or an unauthenticated admin call proves nothing.
Summary
| Concept | What to remember |
|---|---|
| Merkle root | One hash committing to an entire list; any change alters it |
| Merkle proof | Sibling hashes from leaf to root, about log₂(n) of them |
| Bitcoin | Binary double SHA-256 tree of txids in each header; SPV wallets use branches |
| Ethereum | Merkle-Patricia tries for state, transactions and receipts; eth_getProof |
| Contracts | Store a root, verify claims with MerkleProof.verify |
| Safety | Separate leaf and node hashing, match encodings, handle odd nodes, trust only finalised roots |
Get the weekly commit
New blockchain deep dives every week.