Blockchain foundations in Go · 5 MIN READ

Merkle proofs: show one transaction is in a block with about log2(n) hashes

Build a domain-separated Merkle tree, generate and verify inclusion proofs, and explain the duplicate-leaf and second-preimage pitfalls.

A block header cannot carry every transaction, but it can carry one 32-byte Merkle root that commits to all of them. A client that trusts the header can then check that a particular transaction is included from a handful of sibling hashes instead of the whole block. The tree shape and hashing rules are consensus rules, and two classic mistakes let different transaction lists produce the same root.

blockchain · A MAP OF THE IDEA

  1. Hash leaves with 0x00
  2. Hash nodes with 0x01
  3. Collect one sibling a level
  4. Recompute root from index

Useful when

  • A proof costs about log2(n) hashes, not the whole block.
  • Verification needs only the leaf, index, size and a trusted root.

Watch out

  • Duplicating odd nodes lets two different lists share a root.
  • A root taken from the same untrusted response proves nothing.

Implementation & operation cost: About 2n hashes to build the tree and log2(n) per proof, plus a tree shape that becomes a frozen consensus rule once roots are published.

01

One root for many transactions

The previous lesson chained blocks. Inside a block the problem is different: thousands of transactions, and a wallet or indexer that wants to check one of them without downloading the rest. A Merkle tree hashes each transaction into a leaf, then hashes pairs of nodes level by level until one root remains, and the header stores only that root. To prove leaf i, the prover sends the sibling at each level on the path from the leaf to the root, and the verifier recomputes the path and compares. For n leaves that is about log2(n) hashes, so 20 hashes cover a million transactions. A proof shows that the leaf is committed by this root; it says nothing about whether the header itself is canonical, which is the job of the chain and fork-choice lessons.

02

Build, prove and verify in Go

The program hashes leaves with a 0x00 prefix and interior nodes with a 0x01 prefix, and promotes a lone last node to the next level unchanged instead of pairing it with a copy of itself. prove collects one sibling per level when one exists; verify walks up from the leaf and uses the claimed index and the tree size to decide, at every level, whether the sibling sits left or right. The second half builds the classic tree, with no prefixes and duplication of the last hash, to show what the two rules prevent.

go
package main

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
)

type Hash = [32]byte

// Domain separation: a leaf hash can never be confused with an interior node.
func leafHash(data []byte) Hash { return sha256.Sum256(append([]byte{0x00}, data...)) }

func nodeHash(l, r Hash) Hash {
	return sha256.Sum256(append(append([]byte{0x01}, l[:]...), r[:]...))
}

// levels builds the tree bottom-up. A lone last node is promoted unchanged,
// never paired with a copy of itself.
func levels(leaves [][]byte) [][]Hash {
	level := make([]Hash, len(leaves))
	for i, d := range leaves {
		level[i] = leafHash(d)
	}
	tree := [][]Hash{level}
	for len(level) > 1 {
		var next []Hash
		for i := 0; i < len(level); i += 2 {
			if i+1 < len(level) {
				next = append(next, nodeHash(level[i], level[i+1]))
			} else {
				next = append(next, level[i])
			}
		}
		tree = append(tree, next)
		level = next
	}
	return tree
}

func root(leaves [][]byte) Hash {
	t := levels(leaves)
	return t[len(t)-1][0]
}

func prove(leaves [][]byte, index int) []Hash {
	var proof []Hash
	for _, level := range levels(leaves) {
		sibling := index ^ 1
		if sibling < len(level) {
			proof = append(proof, level[sibling])
		}
		index /= 2
	}
	return proof
}

// verify recomputes the root from the leaf, its index and the tree size, so
// left/right order comes from the claimed position, not from the proof.
func verify(leaf []byte, index, size int, proof []Hash, want Hash) bool {
	if index < 0 || index >= size {
		return false
	}
	h := leafHash(leaf)
	for n := size; n > 1; n = (n + 1) / 2 {
		if index%2 == 1 || index+1 < n {
			if len(proof) == 0 {
				return false
			}
			if index%2 == 1 {
				h = nodeHash(proof[0], h)
			} else {
				h = nodeHash(h, proof[0])
			}
			proof = proof[1:]
		}
		index /= 2
	}
	return len(proof) == 0 && h == want
}

// naiveRoot is the classic shape: no prefixes, odd levels duplicate the last hash.
func naiveRoot(leaves [][]byte) Hash {
	level := make([]Hash, len(leaves))
	for i, d := range leaves {
		level[i] = sha256.Sum256(d)
	}
	for len(level) > 1 {
		if len(level)%2 == 1 {
			level = append(level, level[len(level)-1])
		}
		var next []Hash
		for i := 0; i < len(level); i += 2 {
			next = append(next, sha256.Sum256(append(level[i][:], level[i+1][:]...)))
		}
		level = next
	}
	return level[0]
}

func split(s ...string) [][]byte {
	out := make([][]byte, len(s))
	for i, v := range s {
		out[i] = []byte(v)
	}
	return out
}

func main() {
	txs := split("tx-a", "tx-b", "tx-c", "tx-d", "tx-e")
	r := root(txs)
	fmt.Println("root:", hex.EncodeToString(r[:4]), "leaves:", len(txs))

	proof := prove(txs, 2)
	fmt.Println("proof for leaf 2:", len(proof), "hashes, valid:", verify(txs[2], 2, len(txs), proof, r))
	fmt.Println("tampered leaf valid:", verify([]byte("tx-x"), 2, len(txs), proof, r))
	fmt.Println("wrong index valid:", verify(txs[2], 3, len(txs), proof, r))

	three, four := split("a", "b", "c"), split("a", "b", "c", "c")
	ha, hb := sha256.Sum256([]byte("a")), sha256.Sum256([]byte("b"))
	hc, hd := sha256.Sum256([]byte("c")), sha256.Sum256([]byte("d"))
	honest := split("a", "b", "c", "d")
	forged := [][]byte{append(ha[:], hb[:]...), append(hc[:], hd[:]...)}

	fmt.Println("naive [a b c] == [a b c c]:", naiveRoot(three) == naiveRoot(four))
	fmt.Println("naive 4 leaves == 2 forged leaves:", naiveRoot(honest) == naiveRoot(forged))
	fmt.Println("separated [a b c] == [a b c c]:", root(three) == root(four))
	fmt.Println("separated 4 leaves == 2 forged leaves:", root(honest) == root(forged))
}
Read the code

With five leaves, leaf 2 needs three siblings: leaf 3, the hash of leaves 0 and 1, and leaf 4, which was promoted from below. A changed leaf or a claimed index of 3 recomputes a different path and fails. verify derives each direction from index and size instead of trusting flags inside the proof, and it rejects proofs with too few or too many hashes. naiveRoot gives [a b c] and [a b c c] one root and accepts two 64-byte forged leaves built from interior hashes; the separated tree rejects both. Promotion yields the same tree shape as RFC 6962, which splits at the largest power of two below n.

03

The duplicate-last-leaf trap

Bitcoin's tree pairs an odd last hash with a copy of itself, so the transaction lists [a, b, c] and [a, b, c, c] produce the same root, exactly as naiveRoot shows. This became CVE-2012-2459. The list with the repeated transaction is an invalid block, but its header hash equals the honest block's. A node that received the mutated version first, rejected it and remembered the header hash as invalid would then refuse the honest block too. Bitcoin Core now detects the mutation while computing the root and treats the block as malformed rather than marking the header invalid, and the comment above its Merkle code warns new designs not to copy the algorithm. In your own trees, promote the lone node or use the RFC 6962 split, and include the leaf count in whatever you sign or publish next to the root.

04

Separate leaves from interior nodes

Without domain separation an interior node is SHA-256 of 64 bytes and a leaf is SHA-256 of arbitrary bytes. Anyone who knows two sibling hashes can present their 64-byte concatenation as a leaf, and the shorter, forged list reaches the same root: that is the second-preimage result in the program. Prefixing leaves with 0x00 and nodes with 0x01, as Certificate Transparency does in RFC 6962, makes the two kinds of input disjoint, so no interior node can satisfy a leaf proof. Bitcoin's tree has no such separation, and its known ambiguity around 64-byte transactions follows from that. Ethereum headers use Merkle-Patricia tries for transactions, receipts and state rather than this binary tree, and eth_getProof (EIP-1186) returns account and storage proofs. The principle is the same: verify the proof against a root you already trust, never against a root delivered in the same response.

05

Review checklist for proof code

Take the root from a header you have already validated. Bind the index and tree size into verification so a proof for one position cannot be replayed for another. Reject proofs that are too long or too short instead of ignoring extra hashes. Hash leaves from their canonical bytes, as in the hash-chain lesson. Test every index for many sizes, including 1 and powers of two plus and minus one; a wrong index; swapped sibling order; truncated and extended proofs; and a leaf whose bytes equal an interior node. Fuzz verify with random proofs and require that it never panics. These tests are cheap: checking every index and every wrong index for all sizes from 1 to 40 runs in well under a second.

TAKE THIS WITH YOU

Prefix leaves and interior nodes differently, never duplicate an odd node, and verify a proof from the leaf, its index and the tree size against a root you already trust.

Check your understanding

A Merkle tree hashes leaves as H(data) and interior nodes as H(left || right). Which attack do distinct leaf and node prefixes stop?

Go to the source

Progress stays in this browser. No account needed.