Proposes header commitments designed to simplify verification for clients without full chain history.
Specification
CHIP-2026-02: Simplified Header Verification for Bitcoin Cash
Title: CHIP-2026-02 Simplified Header Verification for Bitcoin Cash
First Submission Date: 2026-02-25
Owners: bitcoincashautist (ac-A60AB5450353F40E)
Type: Technical
Layers: SPV
Status: Proposed
Last Edit Date: 2026-04-01
Table of Contents
- Summary
- Introduction
- Deployment
- Motivation
- Benefits
- Technical Description
- Security Analysis
- Specification
- Implementations
- Test Cases
- Evaluation of Alternatives
- Acknowledgements
- Copyright
Summary
This CHIP proposes a header commitment scheme for Bitcoin Cash that enables light clients to verify blockchain state without storing the full header chain. By maintaining a compact cryptographic "Merkle Mountain Range" (MMR) accumulator over block headers, clients can reduce storage requirements from linear to logarithmic in chain height. The MMR can be reduced to a fixed-size root (a single hash) for checkpointing. We show that every Bitcoin Merkle tree contains an MMR: we exploit this to maintain compatibility with Bitcoin's existing Merkle tree construction. The scheme allows clients to verify any historical header against a trusted root or accumulator using inclusion proofs, enabling flexible trust models ranging from fully trustless self-verification to checkpoint-based bootstrapping. Servers benefit from efficient state caching, allowing them to serve header proofs for any block against any past accumulator state or root. This proposal complements existing Simplified Payment Verification (SPV) by addressing its storage overhead, making light wallet implementations more practical for resource-constrained devices.
Introduction
Simplified Payment Verification (SPV), as described in Section 8 of the Bitcoin whitepaper, allows lightweight clients to verify transactions without downloading full blocks. The client downloads block headers, verifies the proof-of-work chain, and checks transaction inclusion via Merkle proofs. This design assumes header storage is negligible, a reasonable assumption in 2008 when headers consumed ~4.2 MB per year.
However, as blockchains mature, header chains grow indefinitely. Bitcoin Cash, sharing Bitcoin's early history and adding nearly a decade of its own, now requires clients to download and store ~75 MB of headers. For mobile wallets and embedded devices, this overhead is non-trivial. Synchronizing a fresh client requires downloading the entire header chain, verifying each header's proof-of-work, and only then can the client begin verifying transactions.
A classical checkpoint commits to a single header; verifying any other header requires the full header segment between them, yielding O(d) proof size where d is the distance. A data structure that commits to the full header history with logarithmic storage and proof size, while remaining efficiently extensible, would solve this problem.
Crosby and Wallach introduced an efficient authenticated data structure for tamper-evident logging in 2009, which they called a "History Tree." Peter Todd later adapted this concept for blockchain applications under the name "Merkle Mountain Range" (MMR). Grin and other cryptocurrencies have since adopted MMR-based commitments for various purposes. Bonneau et al. proved this structure is optimal for authenticated append-only logs, achieving O(log n) accumulator size, proof size, and worst case update cost. Amortized update cost is O(1) per leaf, i.e. m leaves costs O(m) hash operations on average.
We observe that the MMR accumulator state (the ordered sequence of peaks) can be reduced to a root using Bitcoin's Merkle tree construction. This combines the efficiency of MMR with compatibility with Bitcoin's existing commitment and proof formats: the root produced is identical to Bitcoin's Merkle root for the same leaves.
This CHIP proposes applying this insight to Bitcoin Cash block headers, enabling what we call Simplified Header Verification (SHV). The name parallels SPV: just as SPV simplifies transaction verification, SHV simplifies block header verification. A client using SHV maintains only a small accumulator (tens of hashes) and can verify any header's inclusion in the chain without storing the full header sequence.
Deployment
This proposal requires no consensus changes. Clients using SHV still perform full verification of each header's proof-of-work and chain linkage; the accumulator simply provides a compact commitment to headers the client has already verified or chooses to trust.
Implementation requires only infrastructure support for serving accumulators and inclusion proofs:
- Electrum SPV: client upgrades only (server infrastructure already supports SHV)
- P2P SPV: client and server upgrades (no current infrastructure)
Electrum Protocol
Electrum servers already maintain a Bitcoin-style Merkle tree over headers and serve inclusion proofs via blockchain.block.header with the cp_height parameter.
Since computing the root over MMR peaks with Bitcoin's Merkle construction produces identical roots and proofs to what servers already generate, clients can use these proofs to maintain an MMR accumulator with no server changes required.
To bootstrap, a client queries the proof for the header at height = cp_height.
Since this is the last leaf, the proof contains all the MMR peaks needed to initialize the accumulator.
The protocol could be extended to serve peaks directly and support proof-to-peak queries, but this is not required to achieve the goals of this CHIP. Electrum clients are typically not bandwidth-constrained, and the existing protocol is sufficient to achieve the goals of this CHIP.
The main requirement is client-side accumulator maintenance and header pruning, which will remove the header storage burden.
P2P Protocol Extension
This CHIP proposes a P2P protocol extension for full nodes to serve roots, accumulator states, and inclusion proofs directly to SPV clients. This allows P2P light clients (e.g. BIP-37, Neutrino) to utilize SHV without reliance on Electrum infrastructure. The extension supports both proof-to-root and proof-to-peak modes, and can serve peaks directly for efficient bootstrapping.
Clients will need to be upgraded to make use of this infrastructure.
Standalone Proof Servers
Dedicated services could serve roots, accumulators, and proofs via a simple API. Block explorers could display the accumulator root alongside each block, giving users additional sources for trust-on-first-use verification or trusted operation. Clients can query reputable explorers for the root, without running any specialized infrastructure.
Cross-Verification
Because the accumulator is deterministically derived from the header chain, all compliant servers produce identical accumulators, roots, and proofs for the same height. Clients can detect misbehavior by cross-checking responses from multiple independent sources.
Motivation
An SPV client must store headers from the block containing the oldest transaction he wants to verify, up to the chain tip. In the worst case (verifying very old transactions), this approaches the entire header chain. Each header is 80 bytes, and the chain grows by one header per block. With the current 10-minute target, this adds ~4.2 MB per year; with a proposed 1-minute target (CHIP-2025-03 Faster Blocks for Bitcoin Cash), it would add ~42 MB per year. Over a decade, even the slower rate accumulates to significant storage, problematic for mobile devices and browser-based wallets.
Downloading headers also introduces synchronization delays. A new client or one verifying old transactions must fetch and verify all headers back to the oldest relevant transaction before he can validate it. This creates friction for first-time users and for clients that have been offline for extended periods.
This overhead becomes a technical obstacle to faster block times. SHV removes this obstacle by decoupling client storage requirements from block production rate.
Benefits
Reduced Client Storage
Clients using SHV store only a logarithmic-sized accumulator rather than headers back to their oldest transaction. For a chain of 1 million blocks, this reduces worst-case storage from ~80 MB of headers to ~640 bytes of accumulator state (20 hashes at 32 bytes each, plus the leaf count).
Main beneficiaries:
- Mobile Wallets: Reduced storage footprint makes BCH more practical on resource-constrained devices.
- Browser Wallets: Web-based clients can operate without downloading tens of megabytes of headers.
- Embedded Devices: IoT and point-of-sale systems with limited storage can run light clients.
- Temporary Clients: One-time-use wallets for specific transactions need not sync any headers beyond what they're verifying.
Faster Client Bootstrapping
New clients can begin verifying transactions immediately after obtaining a trusted accumulator, rather than downloading and verifying headers back to their oldest transaction. Trust can be established via multiple independent servers or a shipped checkpoint.
Main beneficiaries:
- New Users: First-time BCH users experience faster onboarding when installing a wallet.
- Restored Wallets: Users recovering wallets on new devices sync more quickly.
- Offline Clients: Wallets that have been offline for months catch up faster.
Flexible Trust Models
Current SPV clients have limited options for bootstrapping. A client can verify everything from genesis, but this is slow and storage-intensive. Alternatively, a client can ship with a hardcoded checkpoint header at some height and store all headers from that point forward. BIP37 and Neutrino wallets use this approach, and cannot verify transactions before their checkpoint without downloading the header segment back to the transaction's block.
Electrum wallets go further: they ship with a checkpoint that includes a Merkle root over all headers up to that height. This allows them to verify any historical transaction against the checkpoint. However, they still store all headers from the checkpoint forward, because they don't implement accumulator extension.
An accumulator-based approach completes what Electrum started, enabling a full spectrum of trust models:
- Fully Trustless: The client downloads and verifies all headers, extending the accumulator incrementally, then prunes the headers while retaining the accumulator.
- Trust-on-First-Use: The client queries multiple independent servers for the current accumulator, accepts it if they agree, and verifies headers going forward.
- Checkpoint-Based: The client ships with a developer-attested accumulator and can verify any historical transaction immediately, with no header storage required.
Both trust-on-first-use and checkpoint-based clients can accept their initial trust level or opportunistically upgrade to fully trustless by verifying historical headers in the background.
These options let users and developers choose the trade-off between security assumptions and resource usage appropriate for their context.
Main beneficiaries:
- Security-Conscious Users: Can verify the full chain without ongoing storage burden.
- Convenience-Oriented Users: Can start transacting immediately with reasonable security assumptions.
- Wallet Developers: Can offer configurable trust models to suit different user needs.
Efficient Server Infrastructure
Electrum servers already maintain a Bitcoin-style Merkle tree over headers and serve inclusion proofs. Since MMR with Bitcoin-style commitment produces identical roots and proofs, existing infrastructure already supports this scheme with no server changes required.
Fulcrum, the most widely deployed Electrum server implementation, uses an efficient caching strategy: it stores O(sqrt(n)) subtree roots at a middle level and fetches at most O(sqrt(n)) leaves when generating proofs for any historical root.
With the insight that a Bitcoin-style Merkle tree contains an MMR, other optimizations become available. For serving proofs against historical roots, servers can cache accumulator states at various heights. Because the state is small (on the order of log2(n) hashes for n blocks), servers can maintain historical states without excessive storage overhead. Caching at every height requires O(n log n) storage in total; approximately 320 MB for 1 million headers. Alternatively, the server can cache sparsely (e.g., every 1024 blocks) and extend the cached accumulator on-demand for intermediate heights, requiring at most 1023 leaf appends per served proof, while maintaining only a 313 kB cache.
Main beneficiaries:
- Electrum Server Operators: Existing infrastructure already supports this scheme with no changes required.
- BIP37/Neutrino Node Operators: Can announce roots and add header proofs with minimal overhead.
- Other Wallet Backend Providers: Can implement the scheme with minimal effort.
- Block Explorers: Can display the accumulator root alongside each block, giving users additional sources for trust-on-first-use verification.
Enabling Faster Blocks
Header chain growth is currently a technical obstacle to faster block times. If Bitcoin Cash adopts a 1-minute target block time, the header chain will grow 10x faster—from ~4.2 MB to ~42 MB per year. SHV removes this obstacle by decoupling client storage requirements from block production rate. A client appends one leaf per block, but the accumulator state size remains logarithmic. This makes SHV increasingly advantageous as the chain lengthens.
Main beneficiaries:
- Long-Term Users: Storage requirements remain manageable as the chain ages.
- Ecosystem Scalability: More users can run light clients without proportional infrastructure growth.
- Future Upgrades: Faster block times become feasible without penalizing light client users.
Technical Description
This section describes the Merkle Mountain Range (MMR) data structure and its application to Simplified Header Verification (SHV).
Merkle Mountain Range
An MMR is a collection of perfect binary Merkle trees, called "mountains." The root of each mountain is called a "peak." The number of mountains and their sizes are determined by the binary representation of the total leaf count: each set bit corresponds to one mountain, and the bit's position determines the mountain's height.
For example, with 11 leaves (binary 1011), the MMR has three mountains of heights 3, 1, and 0, corresponding to the set bits:
Leaf count: 11 = 8 + 0 + 2 + 1 = 2^3 + 0 + 2^1 + 2^0
Binary: 1 0 1 1
Bit index: 3 2 1 0
Mountains: 8-leaf 2-leaf 1-leaf
tree tree tree
(14) Height 3
_ / \ _
/ \
6 13 Height 2
/ \ / \
2 5 9 12 (17) Height 1
/ \ / \ / \ / \ / \
0 1 3 4 7 8 10 11 15 16 (18) Height 0 (leaf nodes)
------------------------------------------------------------------
0 1 2 3 4 5 6 7 8 9 10 Leaf index
Note: MMR peaks are highlighted in (), nodes are numbered in the order of appending.
The number of peaks equals the number of set bits in the leaf count, which is at most floor(log2(n)) + 1 for n leaves.
Extending the MMR
If leaves are only appended, then the whole MMR becomes an append-only data structure. Appending a leaf will produce a number of new nodes, but will not remove or change old ones. As leaves are appended, mountains merge whenever two mountains of equal height exist. Merges cascade upward, producing new peaks and burying old ones. This works exactly like binary addition. Building on the above example, we can observe how the MMR changes when appending leaf 11.
Before:
Leaf count: 11 = 8 + 0 + 2 + 1 = 2^3 + 0 + 2^1 + 2^0
Binary: 1 0 1 1
Bit index: 3 2 1 0
After:
Leaf count: 12 = 8 + 4 + 0 + 0 = 2^3 + 2^2 + 0 + 0
Binary: 1 1 0 0
Bit index: 3 2 1 0
Mountains: 8-leaf 4-leaf
tree tree
[(14)] Height 3
_ / \ _
/ \
6 13 [21] Height 2
/ \ / \ / \
2 5 9 12 (17) 20 Height 1
/ \ / \ / \ / \ / \ / \
0 1 3 4 7 8 10 11 15 16 (18) 19 Height 0 (leaf nodes)
---------------------------------------------------------------------
0 1 2 3 4 5 6 7 8 9 10 11 Leaf index
Note: previous peaks are highlighted in (), new peaks in [].
Notice that old peaks are not discarded or recomputed; they persist as intermediate or leaf nodes in the new structure. Only three hashes are computed for the new nodes:
19 = hash(leaf at index 11)
20 = hash(18 || 19)
21 = hash(17 || 20)
The old set of peaks was (n = 11, peaks = [14, 17, 18]). The new set of peaks is (n = 12, peaks = [14, 21]).
When appending a leaf, the number of merges equals the number of trailing 1-bits in the binary representation of n. This requires O(log n) hash operations in the worst case (when n + 1 is a power of two). On average, appending a leaf requires fewer than 2 hash operations.
Rewinding the MMR
Since the whole data structure is append-only, it is trivial to rewind it: pop off the correct number of nodes. Similarly, it is trivial to produce a snapshot of a past state: slice the nodes to desired leaf count.
MMR Accumulator
The MMR accumulator is the leaf count and MMR peaks. It is the minimal data needed to be able to extend the MMR with new nodes. For n leaves, the peaks correspond to set bits in the binary representation of n:
n binary peak heights peak count peak nodes
----- ------ ------------ ---------- ----------------
0 0000 [] 0 []
1 0001 [0] 1 [0]
2 0010 [1] 1 [2]
3 0011 [1, 0] 2 [2, 3]
4 0100 [2] 1 [6]
5 0101 [2, 0] 2 [6, 7]
6 0110 [2, 1] 2 [6, 9]
7 0111 [2, 1, 0] 3 [6, 9, 10]
8 1000 [3] 1 [14]
9 1001 [3, 0] 2 [14, 15]
10 1010 [3, 1] 2 [14, 17]
11 1011 [3, 1, 0] 3 [14, 17, 18]
12 1100 [3, 2] 2 [14, 21]
13 1101 [3, 2, 0] 3 [14, 21, 22]
14 1110 [3, 2, 1] 3 [14, 21, 24]
15 1111 [3, 2, 1, 0] 4 [14, 21, 24, 25]
16 10000 [4] 1 [30]
The maximum number of peaks for n > 0 leaves is floor(log2(n)) + 1. On average, half the bits are set, so the expected number of peaks is approximately log2(n) / 2.
Extending the MMR Accumulator
Extension works exactly as for the full MMR structure, but old nodes are pruned after merging to obtain the new accumulator state.
Rewinding the MMR Accumulator
Since old peaks are pruned, rewinding is not possible. However, an old state can be proven by supplying the old accumulator and the intervening leaves. The verifier extends the old state and checks that the result matches his trusted accumulator.
Merkle Tree
The complete Merkle tree over leaves can be produced from just the accumulator, a procedure known as "bagging the peaks". We use the familiar Bitcoin Merkle tree construction. Starting from MMR peaks, we build an auxiliary subtree (unstable, rebuilt on every append) on top of the smaller peaks, duplicating unpaired nodes where necessary to match heights before combining.
**root**
__________/ \_________
/ \
(14) c Height 3
_ / \ _ / \
/ \ / \
6 13 b b' Height 2
/ \ / \ / \
2 5 9 12 (17) a Height 1
/ \ / \ / \ / \ / \ / \
0 1 3 4 7 8 10 11 15 16 (18) 18' Height 0 (leaf nodes)
----------------------------------------------------------------------
0 1 2 3 4 5 6 7 8 9 10 Leaf index
Note: nodes marked with ' are duplicates; lowercase letters mark the auxiliary subtree; () mark the MMR peaks.
The root is an O(1) commitment but cannot be extended without knowledge of MMR peaks and leaf count. The full accumulator (leaf count + peaks) is an O(log n) commitment that supports extension. The root uniquely identifies both the contents and the structure, and matches the root that the classical layer-by-layer method would produce.
The bagging procedure requires O(log n) hash operations in the worst case. The proof path from any leaf to the root passes through all peaks smaller than the leaf's mountain, so a proof for the last leaf provides all peaks.
SHV Proofs
SHV supports two proof modes, proof-to-peak and proof-to-root, offering different trade-offs between client state size and proof size. Inclusion proofs use the standard Merkle proof format: a list of sibling hashes along the path from the leaf to the target (either a peak or the root). The leaf index bits determine left/right ordering at each level. The leaf count bits determine the target peak (for proof-to-peak verification).
SHV Proof-to-Peak
The client maintains the full accumulator: leaf count plus all peaks. Inclusion proofs terminate at the relevant mountain's peak rather than extending to a single root.
Proof size depends on which mountain contains the leaf. For a leaf in a mountain of 2k leaves, the proof contains k sibling hashes. Recent leaves fall under smaller mountains, yielding shorter proofs. Only leaves in the tallest mountain require the maximum proof size.
| Mountain size | Proof size |
|---|---|
| 1 leaf | 0 hashes |
| 2 leaves | 1 hash |
| 4 leaves | 2 hashes |
| 2k leaves | k hashes |
This mode is ideal for ongoing verification after the client has bootstrapped. The client stores O(log n) peaks and receives O(log m) proofs, where m is the size of the mountain containing the proven leaf.
SHV Proof-to-Root
The client maintains only a single root hash. Inclusion proofs extend from the leaf through the MMR structure to this root. All proofs are O(log n) in size, regardless of which mountain contains the leaf.
This mode is used for:
- Electrum compatibility: The current Electrum protocol supports only proof-to-root. Clients maintaining a full accumulator must still fetch proofs against the root, even though shorter proofs to peaks would suffice.
- Bootstrapping: A client with only a trusted root can obtain the full accumulator by requesting a proof for the last leaf.
The proof contains all MMR peaks as sibling hashes, allowing the client to initialize his accumulator.
Electrum's
blockchain.block.headerendpoint withheight = cp_heightprovides this proof. - Checkpointing: A shipped checkpoint can be a single 32-byte root rather than the full accumulator. The client upgrades to the full accumulator on first sync.
- Cross-verification: Clients can verify that multiple servers agree on the same root without comparing full accumulators.
Range Proofs
To verify a range of consecutive headers, only the final header in the range requires an inclusion proof.
Earlier headers in the range are verified by checking that each header's hash matches the prevBlockHash field of its successor.
For example, to verify headers at heights 1000 through 1009:
- Obtain an inclusion proof for header 1009 against the trusted accumulator or root.
- Verify the proof, confirming header 1009 is at position 1009 in the commitment.
- Verify that header 1008's hash equals header 1009's
prevBlockHash. - Repeat backward through header 1000.
This reduces proof size for range queries from O(k log n) to O(log n) + O(k), where k is the range length. For a 100-header range, this saves 99 inclusion proofs, requiring only the raw headers (~8 KB total) plus one inclusion proof.
With the current Electrum protocol (blockchain.block.headers endpoint), the server returns count, headers, max, branch (sibling hashes for the last provided header), and root.
The leaf index and commitment leaf count are implicit in the client's request (start_height, count, and cp_height parameters).
Handling Blockchain Reorganizations
A client must handle blockchain reorganizations gracefully. If he maintains an accumulator only for the current tip, and that tip becomes orphaned, he loses his verification state.
Since Bitcoin Cash has automatic finalization for blocks with 10 or more confirmations, the client should maintain:
- An accumulator up to the most recent finalized block (11 confirmations; or 101 with 1-minute blocks).
- The tip headers beyond finalization (10 headers; or 100 with 1-minute blocks).
At 80 bytes per header, this costs under 2 kB of storage (or ~9 kB with 1-minute blocks). When the chain extends, the client appends the newly finalized header to his accumulator and adds the new tip header to his buffer. If a reorganization occurs, he discards the affected tip headers and re-syncs from his finalized accumulator.
Security Analysis
Established Construction. The scheme uses Bitcoin's Merkle tree construction, which has been deployed and studied since 2009. The MMR accumulator is contained within this structure, inheriting its security properties.
Collision Resistance. Security relies on double-SHA256, as used throughout Bitcoin. Finding two different sequences of headers that produce the same root requires finding a hash collision.
Duplicate Subtree Ambiguity (CVE-2012-2459). Bitcoin's Merkle tree duplicates nodes to balance the tree when count is not a power of 2 (perfect binary tree). This creates an ambiguity: multiple MMR states with different leaf counts can produce the same bagged root. A subtree that was duplicated during bagging can be reinterpreted as containing real leaves, allowing forged proofs for phantom positions.
For example, with 11 real leaves, the bagging process duplicates smaller peaks to match heights before merging. An attacker can construct a forged 16-leaf interpretation where the duplicated subtree appears as 5 additional phantom leaves (indices 11-15). The forged tree has the same root as the real tree, and proofs for phantom leaves are byte-for-byte identical to proofs for real leaves in the original tree.
The attack works because duplicates from bagging appear as right siblings in the proof path. In a forged proof, the same duplicated node appears as a left sibling: the subtree that was originally on the right (and duplicated) is now claimed to be on the left (with a phantom copy on the right).
This ambiguity affects only proof-to-root verification and bootstrapping, where the root alone does not uniquely identify the MMR structure. Proof-to-peak verification is not vulnerable because the accumulator state (leaf count and peaks) has a 1-to-1 mapping with the leaf sequence: there is no ambiguity to exploit when verifying against trusted peaks.
For proof-to-root and bootstrapping, a client detects forgery by checking at each level of the proof path: if a sibling equals the current hash and the sibling is on the left (index bit is 1), the proof is rejected. Legitimate duplicates from bagging only appear as right siblings, so this check has no false positives.
For header verification, this attack has two practical implications:
- Proving headers at wrong heights: A server could prove a real historical header but claim it exists at a phantom position, misleading the client about when a transaction confirmed or which fork a block belongs to.
- Bootstrapping with wrong height: A malicious server could provide a valid proof for the tip header but claim a higher leaf count than reality. The client would initialize with an incorrect chain height and subsequently fail to extend the accumulator correctly when real blocks arrive.
The left-sibling duplicate check in proof-to-root verification and bootstrapping defends against both attacks independent of header chain linkage constraints.
Domain Separation (CVE-2017-12842). Bitcoin's Merkle tree construction lacks domain separation between leaf and internal nodes, which can allow second preimage attacks in some contexts. This does not apply to header commitments because all leaves are exactly 80 bytes (the fixed header size), while internal nodes are 64 bytes (two concatenated 32-byte hashes). The length difference provides implicit domain separation.
Append-Only Integrity. Given a valid root, it is computationally infeasible to produce a proof for a header that was not appended at the claimed position. This follows from collision resistance of the hash function.
Deterministic Construction. All parties computing the same kind of commitment over the same sequence of headers arrive at the same accumulator and root. There is no ambiguity in the structure.
Efficient Verification. Verifying an inclusion proof requires O(log n) hash operations. No party can construct a valid proof without knowing the actual header data and its position.
Specification
SHV Client Specification
This section provides precise definitions and algorithms sufficient to implement the scheme client-side.
Definitions
| Term | Definition |
|---|---|
| Hash | 32-byte SHA256d output |
| sha256d(x) | SHA256(SHA256(x)), returns 32-byte Hash |
| header | 80-byte Bitcoin Cash block header |
| popcount(n) | Number of 1-bits in n |
| ` | |
| countr_zero(n) | Number of trailing 0-bits in n |
| countr_one(n) | Number of trailing 1-bits in n |
| bit_width(n) | Number of bits needed to represent n |
Leaf Node
The leaf node value for the MMR is the hash of the 80-byte raw block header:
Hash leaf(byte[80] header) {
return sha256d(header);
}
This is the standard Bitcoin block hash, computed over the raw header bytes.
Merged Node
Merged nodes are computed by concatenating the left and right child hashes and hashing the result:
Hash merge(Hash left, Hash right) {
return sha256d(left || right);
}
This matches Bitcoin's Merkle tree node computation.
Accumulator State
The accumulator consists of:
struct State {
uint64 leaf_count; // number of leaves
Hash peaks[]; // length = popcount(leaf_count), ordered by decreasing subtree size
};
The initial state is State { leaf_count: 0, peaks: [] }.
The number of peaks equals the number of set bits in leaf_count.
Peak heights correspond to the bit positions of set bits in leaf_count.
For example, with leaf_count = 11 (binary 1011):
peaks[0] = height-3 peak (covers leaves 0-7)
peaks[1] = height-1 peak (covers leaves 8-9)
peaks[2] = height-0 peak (covers leaf 10)
Accumulator Extension
Extends the accumulator by appending a new leaf node.
State extend(State state, Hash leaf) {
// Number of merges equals trailing 1-bits in current leaf count.
unsigned merge_count = countr_one(state.leaf_count);
Hash current = leaf;
// Merge with smallest peaks (from back) as they combine with new leaf.
for (unsigned i = 0; i < merge_count; i++) {
current = merge(state.peaks.back(), current);
state.peaks.pop_back();
}
state.peaks.push_back(current);
state.leaf_count++;
return state;
}
When appending a leaf node, the number of merges equals the number of trailing 1-bits in the binary representation of leaf_count.
This requires O(log n) hash operations in the worst case (when leaf_count + 1 is a power of two).
On average, each extend requires fewer than 2 merges.
Accumulator Build
Builds an accumulator from a sequence of leaf nodes.
State build(Hash leaves[]) {
State state = State { leaf_count: 0, peaks: [] };
for (uint64 i = 0; i < leaves.length; i++) {
state = extend(state, leaves[i]);
}
return state;
}
Accumulator Rewind
The accumulator cannot be rewound directly since old peaks are pruned. However, a past state can be verified and adopted by extending it forward.
bool rewind(State current, State past, Hash leaves[]) {
// Verify past state is older.
if (past.leaf_count >= current.leaf_count) {
return false;
}
// Verify leaves array spans the gap.
if (leaves.length != current.leaf_count - past.leaf_count) {
return false;
}
// Extend past state with provided leaves.
State extended = past;
for (uint64 i = 0; i < leaves.length; i++) {
extended = extend(extended, leaves[i]);
}
// Verify extended state matches trusted current state.
if (extended.leaf_count != current.leaf_count) {
return false;
}
if (extended.peaks.length != current.peaks.length) {
return false;
}
for (uint64 i = 0; i < extended.peaks.length; i++) {
if (extended.peaks[i] != current.peaks[i]) {
return false;
}
}
return true;
}
If verification succeeds, the client may adopt past as his new trusted state.
The caller is responsible for obtaining the past state and intervening leaves from a server or other source.
Merkle Root Computation
Computes the root by duplicating and merging peaks to form a balanced tree.
Hash bitcoin_root(State state) {
if (state.leaf_count == 0) {
return Hash{}; // All-zero hash for empty state
}
if (state.peaks.length == 1) {
return state.peaks[0]; // Single peak is the root
}
// Bag peaks from smallest to largest, duplicating to match heights.
Hash hash = state.peaks.back();
uint64 remaining = state.leaf_count;
unsigned height = countr_zero(remaining);
for (int i = state.peaks.length - 1; i > 0; i--) {
// Clear lowest set bit to find next peak's height.
remaining = remaining & (remaining - 1);
unsigned next_height = countr_zero(remaining);
// Duplicate until heights match.
while (height < next_height) {
hash = merge(hash, hash);
height++;
}
// Merge with next larger peak.
hash = merge(state.peaks[i - 1], hash);
height++;
}
return hash;
}
Starting from the smallest peak (rightmost in the tree), the algorithm works backwards through progressively larger peaks.
Before merging with each larger peak, the running hash is duplicated until its height matches the next peak's height.
This produces the same root as Bitcoin's Merkle tree construction, where unpaired nodes are duplicated to form a balanced tree.
Peak heights correspond to the positions of set bits in leaf_count; the bit manipulation leaf_count & (leaf_count - 1) clears the lowest set bit, allowing countr_zero to yield each successive peak height.
For an empty accumulator, the function returns the null hash (32 zero bytes).
Proof-to-Peak Verification
Verifies a leaf's inclusion by computing the path to its mountain's peak and comparing against the trusted accumulator state.
bool verify_to_peak(State state, uint64 leaf_index, Hash leaf, Hash siblings[]) {
// Malformed proof check.
if (leaf_index >= state.leaf_count) {
return false;
}
// Find which peak covers this leaf.
// XOR identifies where leaf_index and leaf_count differ; the highest
// differing bit indicates the mountain boundary.
uint64 diff = leaf_index ^ state.leaf_count;
unsigned diff_width = bit_width(diff);
unsigned mountain_height = diff_width - 1;
unsigned peak_index = popcount(state.leaf_count >> diff_width);
// Malformed proof check.
if (siblings.length != mountain_height) {
return false;
}
// Compute path to peak. No CVE-2012-2459 check needed: proof-to-peak
// verifies against trusted accumulator state, which has 1-to-1 mapping
// with leaf sequence, even if there are duplicate leaves.
Hash current = leaf;
uint64 idx = leaf_index;
for (unsigned i = 0; i < siblings.length; i++) {
if (idx & 1) {
current = merge(siblings[i], current);
} else {
current = merge(current, siblings[i]);
}
idx = idx >> 1;
}
return current == state.peaks[peak_index];
}
The bits of leaf_index determine orientation: a 1-bit means the sibling is on the left, a 0-bit means it is on the right.
The proof may be empty when the leaf is a lone peak; this occurs when leaf_index == leaf_count - 1 and leaf_count is odd.
Proof-to-Root Verification
Verifies a leaf's inclusion by computing the path to the bagged root.
bool verify_to_root(State state, uint64 leaf_index, Hash leaf, Hash siblings[]) {
// Malformed proof check.
if (leaf_index >= state.leaf_count) {
return false;
}
// Malformed proof check && trivial verification if well formed.
if (state.leaf_count == 1) {
return siblings.length == 0 && leaf == state.peaks[0];
}
// Malformed proof check.
unsigned expected_length = bit_width(state.leaf_count - 1);
if (siblings.length != expected_length) {
return false;
}
// Compute path to root with CVE-2012-2459 protection.
// The attack exploits bagging ambiguity: multiple MMR states can produce
// the same root, allowing forged proofs for phantom positions. We detect
// this by rejecting left-sibling duplicates, which only occur in forged
// proofs (legitimate duplicates from bagging appear as right siblings).
Hash current = leaf;
uint64 idx = leaf_index;
for (unsigned i = 0; i < siblings.length; i++) {
if ((idx & 1) && siblings[i] == current) {
return false;
}
if (idx & 1) {
current = merge(siblings[i], current);
} else {
current = merge(current, siblings[i]);
}
idx = idx >> 1;
}
return current == bitcoin_root(state);
}
The proof length is always bit_width(leaf_count - 1), which equals the height of the bagged tree.
The proof is empty only when leaf_count == 1.
Bootstrapping from Proof
A client can initialize his accumulator from a proof-to-root for the last leaf. The proof contains all MMR peaks as siblings along the path, interleaved with duplicates from the bagging process.
State bootstrap(uint64 leaf_count, Hash last_leaf, Hash siblings[]) {
// Edge case.
if (leaf_count == 0) {
if (siblings.length != 0) {
return null;
}
return State { leaf_count: 0, peaks: [] };
}
// Trivial verification and initialization.
if (leaf_count == 1) {
if (siblings.length != 0) {
return null;
}
return State { leaf_count: 1, peaks: [last_leaf] };
}
// Malformed proof check.
unsigned expected_length = bit_width(leaf_count - 1);
if (siblings.length != expected_length) {
return null;
}
unsigned peak_count = popcount(leaf_count);
Hash peaks[peak_count];
uint64 remaining = leaf_count;
unsigned proof_idx = 0;
unsigned peak_idx = peak_count;
unsigned current_height = 0;
// Track path computation for extracting root as the only peak
// when leaf count is power of two.
Hash computed = last_leaf;
uint64 idx = leaf_count - 1;
// We must guard against CVE-2012-2459 throughout the whole path
// (path segments inside & outside MMR structure) because MMR
// structure is determined from leaf_count, and it cannot be trusted.
while (remaining > 0) {
unsigned peak_height = countr_zero(remaining);
// Advance through proof to reach peak height.
while (current_height < peak_height) {
Hash sibling = siblings[proof_idx];
// CVE-2012-2459 (proof-to-peak segment).
if ((idx & 1) && sibling == computed) {
return null;
}
if (idx & 1) {
computed = merge(sibling, computed);
} else {
computed = merge(computed, sibling);
}
idx = idx >> 1;
proof_idx++;
current_height++;
}
peak_idx--;
if (peak_height == 0 && peak_idx == peak_count - 1) {
// Smallest peak is the last_leaf itself.
peaks[peak_idx] = last_leaf;
} else if (proof_idx < siblings.length) {
// Next sibling in proof is this peak.
peaks[peak_idx] = siblings[proof_idx];
// CVE-2012-2459 (proof-to-root segment).
if ((idx & 1) && siblings[proof_idx] == computed) {
return null;
}
if (idx & 1) {
computed = merge(siblings[proof_idx], computed);
} else {
computed = merge(computed, siblings[proof_idx]);
}
idx = idx >> 1;
proof_idx++;
current_height++;
} else {
// Exhausted proof; computed value is the final peak (root).
peaks[peak_idx] = computed;
}
remaining = remaining & (remaining - 1);
}
return State { leaf_count: leaf_count, peaks: peaks };
}
Example with leaf_count = 11 (binary 1011):
Peaks: [height-3, height-1, height-0]
Proof: [last_leaf_dup, peaks[1], dup, peaks[0]]
Iteration 1: peak_height=0, extract peaks[2]=last_leaf
Iteration 2: peak_height=1, extract peaks[1]=siblings[1]
Iteration 3: peak_height=3, skip 1 dup, extract peaks[0]=siblings[3]
Example with leaf_count = 8 (binary 1000):
Peaks: [height-3]
Proof: [sibling, intermediate, intermediate] // 3 elements
Iteration 1: peak_height=3, compute path through all 3 siblings,
proof exhausted, extract peaks[0]=computed
The extracted accumulator can be used in several trust modes:
- Verify against root: Compute
bitcoin_root(state)and compare to a trusted root. - Deferred verification: Accept the accumulator and start operating immediately; download and verify the full header chain from genesis in the background, rebuilding the accumulator from scratch to confirm it matches.
- Trust servers: Operate without verification, relying on server honesty or cross-checking multiple independent servers.
SHV Server Specification
Server proof generation follows straightforwardly from the verification algorithms by collecting siblings along the same paths. Servers have flexibility in how they store and retrieve the necessary data, as long as generated proofs pass verification.
A server maintaining only the accumulator (leaf count and peaks) can generate proofs for the current state but cannot efficiently serve proofs against historical commitment heights without storing additional data.
For full historical proof support, servers may store all internal nodes produced by merge operations. For n leaves, this requires n - popcount(n) hashes, since each merge produces exactly one internal node. Leaf hashes need not be stored separately if they are available from an existing block index.
With all internal nodes stored, the server can generate proofs against any historical commitment height in O(log n) time by traversing the appropriate path and collecting siblings.
Alternative caching strategies are possible. For example, a server could store accumulator snapshots at regular intervals (e.g., every 1024 blocks) and extend from the nearest snapshot when serving proofs for intermediate heights. This trades storage for computation, requiring at most 1023 leaf appends per served proof while maintaining only O(n / interval) cached states.
RPC API for Simplified Header Verification
This section specifies RPC methods for querying SHV data from a local node. These methods are intended for wallet backends, block explorers, and debugging tools.
getshv
Returns an inclusion proof for a block header.
Arguments:
| # | Name | Type | Description |
|---|---|---|---|
| 1 | type | string | Proof type: "root" or "peak" |
| 2 | commitment_height | number | Height of the commitment (0-indexed) |
| 3 | block_height | number | Height of the block to prove (0-indexed) |
Result (type = "root"):
{
"branch": ["hash", ...], // Sibling hashes from leaf to root
"header": "hex", // Block header (80 bytes, hex-encoded)
"root": "hash" // Merkle root at commitment_height
}
Result (type = "peak"):
{
"branch": ["hash", ...], // Sibling hashes from leaf to peak
"header": "hex", // Block header (80 bytes, hex-encoded)
"peak": "hash" // Target peak
}
Errors:
| Code | Message | Condition |
|---|---|---|
| -1 | MMR index is not enabled | Node started without -mmrindex |
| -8 | Unknown type | type is not "root" or "peak" |
| -8 | commitment_height must be non-negative | commitment_height < 0 |
| -8 | block_height must be non-negative | block_height < 0 |
| -8 | block_height cannot exceed commitment_height | block_height > commitment_height |
| -8 | Block not found | block_height beyond chain tip |
| -8 | Failed to generate proof | commitment_height beyond chain tip |
Examples:
$ bitcoin-cli getshv "root" 1000 500
$ bitcoin-cli getshv "peak" 1000 500
Block and Header Response Extensions
When the node is started with -mmrindex, the following RPC methods include an additional shvroot field:
getblockgetblockheader
The shvroot field contains the Merkle root at that block's height, allowing clients to verify proofs or use the root as a checkpoint.
Example:
$ bitcoin-cli getblockheader "00000000..."
{
...
"height": 1000,
"shvroot": "abcd1234...",
...
}
Configuration
| Option | Default | Description |
|---|---|---|
| -mmrindex | 1 (when serving SPV) | Maintain MMR index for header proofs |
When -mmrindex=1, the node:
- Builds the MMR from the block index on startup
- Updates the MMR as blocks are connected and disconnected
- Advertises NODE_SHV service bit to peers
- Responds to
getshvP2P messages - Includes
shvrootin block and header RPC responses - Enables the
getshvRPC method
P2P Protocol Extension for Simplified Header Verification
This section specifies a P2P protocol extension enabling BIP-37 and Neutrino clients (BIP-157/158) to use SHV without reliance on Electrum infrastructure.
Full nodes advertise support via a service bit and respond to getshv proof requests.
Service Bit
| Name | Bit | Description |
|---|---|---|
| NODE_SHV | 1 << 9 | Node maintains MMR data structure computed over block headers and serves SHV proofs and data |
Nodes advertising this bit MUST respond to getshv messages.
Nodes not advertising this bit SHOULD ignore getshv messages silently.
A node need not advertise NODE_SHV to send getshv requests.
Clients SHOULD NOT send getshv to peers that do not advertise NODE_SHV.
getshv
Request block header inclusion proofs.
| Field | Type | Description |
|---|---|---|
| request_count | compactSize uint | Number of requests |
| requests | SHVRequest[request_count] | The requests |
Servers SHOULD reject getshv messages with more than 100 requests.
Each SHVRequest:
| Field | Type | Description |
|---|---|---|
| type | uint8 | Request type bitfield |
| commitment_height | compactSize uint | Height of the commitment |
| block_height_or_hash | byte[32] | Block height (32-byte little-endian) or block hash |
Type bitfield:
| Bits | Meaning |
|---|---|
| 0 | Request type: 0 = PROOF_TO_PEAK, 1 = PROOF_TO_ROOT |
| 1 | Block selector: 0 = by height, 1 = by hash |
| 2-7 | Reserved, must be 0 |
When bit 1 = 0, block_height_or_hash contains the block height as a 32-byte little-endian integer. When bit 1 = 1, block_height_or_hash contains the block hash.
shv
Response to getshv.
Contains one entry per valid request.
Invalid requests are silently omitted.
| Field | Type | Description |
|---|---|---|
| response_count | compactSize uint | Number of responses |
| responses | SHVResponse[response_count] | The responses |
Servers MAY split responses across multiple shv messages; response order is not guaranteed.
Each SHVResponse:
| Field | Type | Description |
|---|---|---|
| type | uint8 | Echoed from request |
| commitment_height | compactSize uint | Echoed from request |
| block_height | compactSize uint | Echoed or resolved from request |
| header | byte[80] | Block header |
| proof | compactSize uint + uint256[] | Sibling hashes from leaf toward target |
| target | uint256 | Peak (type 0) or root (type 1) |
Type Byte Examples
| Decimal | Binary | Meaning |
|---|---|---|
| 0 | 0000 0000 | PROOF_TO_PEAK, block by height |
| 1 | 0000 0001 | PROOF_TO_ROOT, block by height |
| 2 | 0000 0010 | PROOF_TO_PEAK, block by hash |
| 3 | 0000 0011 | PROOF_TO_ROOT, block by hash |
Validation Rules
Server MUST omit response if:
- Bits 2-7 of type are non-zero
- By-height request (bit 1 = 0) and bytes 8-31 of block_height_or_hash are non-zero
- By-height request and block_height > commitment_height
- By-hash request (bit 1 = 1) and block_hash does not exist in active chain
- By-hash request and resolved block_height > commitment_height
- commitment_height > server's chain height
The block_height > commitment_height check implicitly covers bytes 0-7, since any valid commitment_height fits in fewer than 8 bytes.
Client MUST match responses to requests by comparing (type, commitment_height, block_height) tuples. For by-hash requests, the client computes block_hash by hashing the returned header and looking up his original request.
Proof Verification
The client verifies the proof by:
- Computing leaf_hash = sha256d(header).
- If request was by block_hash, verifying leaf_hash equals the requested hash.
- Walking the proof using block_height bits for orientation (0 = sibling on right, 1 = sibling on left; lowest bit for lowest level).
- Comparing the result to target.
- Verifying target against a trusted peak (type 0) or root (type 1).
For type 0, proof may be empty when the leaf is a lone peak; verification reduces to leaf_hash == target.
For type 1 with commitment_height = 0, proof is empty; verification reduces to leaf_hash == target.
Implementations
Reference Implementation
A complete implementation is available as a Bitcoin Cash Node merge request:
The implementation includes:
- MMR server (
src/shv/mmr.cpp,src/shv/mmr.h): Stores internal nodes, generates proofs for any historical commitment height. - MMR client accumulator (
src/shv/test/mmr_accumulator.cpp,src/shv/test/mmr_accumulator.h): Stores only peaks, extends and verifies proofs. - Chain integration (
src/shv/chain_mmr.cpp,src/shv/chain_mmr.h): Maintains MMR over block headers, handles connect/disconnect. - P2P protocol (
src/shv/shv.cpp,src/shv/shv.h): Message serialization for getshv/shv. - RPC interface (
src/rpc/blockchain.cpp): The getshv method and shvroot field.
Client Libraries
Standalone client-side accumulator implementations are available in the mmr-accumulator repository:
| Language | Package | Path |
|---|---|---|
| TypeScript | @0353F40E/mmr-accumulator-ts |
ts/ |
| Python | mmr-accumulator |
python/ |
These libraries implement the SHV Client Specification and share test vectors with the reference C++ implementation.
Wallet Implementations
Electron Cash
Electron Cash wallet has been upgraded to offer optional automatic checkpoint extension and automatic header pruning:
The implementation uses the mmr-accumulator Python library.
Instead of keeping the accumulator synced at all times during runtime, it implements a simpler approach:
- On startup: Bootstraps MMR accumulator from the already-verified checkpoint proof (no extra network request needed).
- On shutdown: Extends MMR using locally-stored headers, writes new checkpoint height and Merkle root to config, prunes old headers.
- Next startup: Applies the extended checkpoint; headers below it are fetched on-demand with proofs when needed.
Test Cases
Test Vectors
Test vectors are available in a shared JSON format, present in both BCHN implementation and library implementations repositories:
- BCHN unit tests: src/test/data/mmr_test_vectors.json
- Library implementations: test_vectors/mmr_test_vectors.json
The same JSON file is used in both.
Block Merkle Root Vectors
Block Merkle roots used to verify the MMR produces identical roots to Bitcoin's construction:
| Block Height | Transaction Count | Peak Configuration | Merkle Root |
|---|---|---|---|
| 53066 | 8 | Single peak (2³) | 271eafea9cfeb730c6fae8c39da387b37967646d26224a10878e04f3f6212fbe |
| 57113 | 10 | Two peaks (2³ + 2¹) | dd9bfa795a0dfe64975eb03fddf8419e03f48fe6b5a97aa736b2536c035df864 |
| 57286 | 11 | Three peaks (2³ + 2¹ + 2⁰) | 23d97ad1b6e828398aff13122e312883c47986e8c8a9d1f4042876fa2e9e1fe4 |
Header Segment Vectors
First 16 Bitcoin block hashes (heights 0-15) used for proof verification tests.
A forged variant is included for CVE-2012-2459 testing, where the first 11 hashes are real and the last 5 are duplicates creating phantom leaves (indices 11-15 duplicate indices 10, 8, 9, 10, 10 respectively).
Electrum Proof Vectors
Inclusion proofs in Electrum protocol format, used to verify compatibility:
| Proof Key | height | cp_height | Description |
|---|---|---|---|
| proof_10_0 | 0 | 10 | First leaf in 8-leaf mountain |
| proof_10_6 | 6 | 10 | Interior of 8-leaf mountain |
| proof_10_7 | 7 | 10 | Last leaf of 8-leaf mountain |
| proof_10_8 | 8 | 10 | First leaf of 2-leaf mountain |
| proof_10_9 | 9 | 10 | Last leaf of 2-leaf mountain |
| proof_10_10 | 10 | 10 | Lone leaf peak (odd count) |
| proof_11_11 | 11 | 11 | Last leaf after extension |
| proof_12_12 | 12 | 12 | Last leaf, odd count |
| proof_15_15 | 15 | 15 | Last leaf of 16-leaf tree |
Each proof includes the branch (sibling hashes), raw header, and expected root.
CVE-2012-2459 Vectors
Demonstrates the duplicate subtree attack and its mitigation:
- Real tree: 11 leaves, root
8b8f513a34feeb1f2cdac70fcd97042be23ccd64de9d66d36f9407bbc1809f5f - Forged tree: 16 leaves with duplicates, same root
The forged tree reuses proofs from the real tree at phantom positions:
| Forged Index | Maps to Real Index | Proof Used |
|---|---|---|
| 11 | 10 | proof_10_10 |
| 12 | 8 | proof_10_8 |
| 13 | 9 | proof_10_9 |
| 14 | 10 | proof_10_10 |
| 15 | 10 | proof_10_10 |
These vectors verify that the left-sibling duplicate check correctly rejects forged proofs.
Test Plan
Client Tests
Tests the MMR accumulator client implementations across BCHN (C++), TypeScript, and Python. All implementations share the same JSON test vectors and test the same functionality.
| Category | Tests |
|---|---|
| Empty state | Empty accumulator returns correct defaults; proof verification fails |
| Single leaf | Root equals leaf; empty proofs verify; single peak |
| Root equivalence | Accumulator root matches known Bitcoin Merkle roots (8, 10, 11 tx blocks) |
| Peak structure | Power-of-two yields single peak; other counts yield multiple peaks |
| Two peaks | Independent subtrees combine correctly (10 leaves = 8 + 2) |
| Rewind pattern | Past state reconstructed via extend; peaks match after extension |
| Proof-to-root | Electrum proofs verify; invalid proofs rejected |
| Proof-to-peak | Proof lengths match mountain heights; proofs verify against peaks |
| Bootstrap from proof | Peaks extracted from last-leaf proof; state matches reference |
| Bootstrap edge cases | Empty, single leaf, power-of-two, wrong proof length rejected |
| Clear/reset | Accumulator resets to empty; extends correctly after clear |
| Out of bounds | Proof verification rejects invalid leaf indices |
| Wrong sibling count | Proof verification rejects wrong proof lengths |
| CVE-2012-2459 | Forged proofs rejected by verify and bootstrap; attack premise demonstrated |
| Input validation | Invalid hash lengths rejected; constructor validates peak count |
| Equality | State comparison works correctly |
| Serialization | Roundtrip preserves state (TypeScript/Python only) |
BCHN Server Tests (src/test/mmr_tests.cpp)
Tests the server-side MMR class in addition to client accumulator:
| Category | Tests |
|---|---|
| MMR empty state | Empty MMR returns correct defaults |
| MMR extend | Nodes added correctly; leaf/node counts accurate |
| MMR rewind | Reverts to prior state; node count matches |
| MMR proof generation | GetProofToPeak and GetProofToBitcoinRoot produce valid proofs |
| Cross-verification | MMR and accumulator produce identical roots and peaks |
| Round-trip | MMR-generated proofs verify in accumulator |
BCHN Integration Tests (src/test/chain_mmr_tests.cpp)
Tests the MMRIndex integration with the block index:
| Category | Tests |
|---|---|
| Lifecycle | Start/stop/restart preserves state; queries fail when not synced |
| Consistency | MMRIndex matches independently built accumulator at every height |
| Peak configurations | Correct peak counts at powers of two, maximum peaks, chain tip |
| Proof generation | Proofs verify for all block/commitment height combinations |
| Edge cases | Genesis block, lone peaks, mountain boundaries |
| Block connect | MMR extends correctly; proofs for new blocks verify |
| Block disconnect | MMR rewinds correctly; historical state restored |
| Reorganization | Connect/disconnect/connect sequences handled correctly |
| Invalid parameters | Out-of-range heights return nullopt |
| Cross-verification | Range proofs, bootstrapping, proof-to-peak prefix of proof-to-root |
| Deterministic | Rebuild produces identical state |
BCHN Functional Tests (test/functional/bchn-p2p-shv.py)
Tests the P2P protocol:
| Category | Tests |
|---|---|
| Service bit | NODE_SHV advertised when -mmrindex=1 |
| Proof-to-peak | By height and by hash; correct response fields |
| Proof-to-root | By height and by hash; proof verifies |
| Invalid requests | Reserved bits, height exceeds commitment, unknown hash, non-zero upper bytes |
| Multiple requests | Batch requests; mixed valid/invalid |
| Edge cases | Genesis block (empty proof), lone peak (empty proof) |
| Bootstrapping | Last-leaf proof contains extractable peaks |
| Disabled index | NODE_SHV not advertised; requests ignored |
BCHN Functional Tests (test/functional/rpc_blockchain.py)
Tests the RPC interface:
| Category | Tests |
|---|---|
| Error handling | Disabled index, invalid type, negative heights, out-of-range |
| Proof-to-root | Correct fields returned |
| Proof-to-peak | Correct fields returned |
| Edge cases | Genesis block, lone peak |
| Block response | shvroot field present when enabled, absent when disabled |
| Header response | shvroot field matches block response |
Evaluation of Alternatives
The MMR accumulator is well-established for append-only data. However, the method of reducing peaks to a single root ("bagging the peaks") admits several approaches. This section examines the alternatives considered.
We adopt Bitcoin's Merkle tree construction for both Electrum compatibility and new P2P infrastructure:
- Familiarity: Bitcoin's tree structure is well understood, with plenty of existing code and libraries available.
- Standardization: Its use for header commitments is already implemented in production by the Electrum protocol.
- Adoption Cost: Using a single construction for both Electrum and P2P simplifies implementation and avoids protocol fragmentation.
- Path Simplicity: Because the tree is padded with duplicates to form a balanced structure, proof-to-peak and proof-to-root use the same traversal algorithm; only the target differs.
Null Sibling
Similar to Bitcoin's construction, unpaired nodes can be paired with a null value (empty string) instead of duplicating the hash. This avoids the duplicate vulnerability but produces a structure incompatible with existing Bitcoin Merkle proof libraries. Because headers form a hash chain, the duplicate vulnerability does not apply, so there is nothing to gain by implementing this. The method also requires distinguishing between null siblings and actual zero-valued hashes, adding implementation complexity.
Hash Chain
In 2012, Todd ("Merkle Mountain Ranges") proposed a procedure to commit to MMR peaks and named it "bagging the peaks":
We've created a list of the peaks of each mountain, and in turn created a merkle tree from that. For obscure reasons this operation is referred to as bagging the peaks.
He did not specify the algorithm precisely. The provided diagram was ambiguous due to the small number of peaks (3): it could either be a tree built on peaks or a hash chain. Later work (Todd, Grin) adopted the hash chain method:
Finally, once all the positions of the peaks are known, "bagging" the peaks consists of hashing them iteratively from the right, using the total size of the MMR as prefix. For a MMR of size N with 3 peaks p1, p2 and p3 we get the final top peak:
P = Blake2b(N | Blake2b(N | Node(p3) | Node(p2)) | Node(p1))
This method has since been standardized by Grin, Nervos, Neptune, Zcash, and others, so there are plenty of libraries available. An alternative method would hash left to right, but we are not aware of such implementations.
Due to a structural vulnerability (Chainsecurity, 2023), the leaf count must be included in the root commitment, adding an additional hash operation per proof verification.
Node Promotion
Unpaired nodes can be iteratively promoted and paired with an available higher-level sibling. Two variants exist, depending on promotion direction.
Both variants improve over Bitcoin's construction and hash chaining by reducing both the number of bagging merges and proof-to-root overhead.
Bitcoin-style bagging produces proofs of size bit_width(leaf_count - 1) regardless of leaf position.
Hash chaining produces proofs of size mountain_height + peak_count - 1.
The promotion approach produces proofs of size mountain_height + log(log(n)) + log(log(log(n))) + ..., which adds only ~3 hashes for practical values of n.
The promotion approach also eliminates both the duplicate vulnerability found in the Bitcoin method and the structural vulnerability found in the hash chain method.
Despite these advantages, we do not adopt either promotion variant:
- Electrum incompatibility: Neither variant produces roots compatible with existing Electrum infrastructure.
- Proof-to-peak suffices: Clients maintaining the full accumulator already receive small proofs for recent headers. The promotion approach's main benefit (smaller proofs to a single root) matters primarily for checkpointing, where proof size is less critical.
- Single construction: Using Bitcoin's construction for both Electrum and P2P avoids protocol fragmentation and simplifies implementation.
Rightward Promotion (Recursive MMR)
This variant reduces the accumulator by recursively building MMRs over the previous MMR's peaks. Unpaired peaks are promoted rightward to the next level.
Second bag MMR: **root**
____/ \____
/ \
First bag MMR: ((I)) |
_______/ \______ |
/ \ |
Base MMR: (H) | |
_ / \ _ | |
/ \ | |
F G | |
/ \ / \ | |
A B C D (E) |
/ \ / \ / \ / \ / \ |
0 1 2 3 4 5 6 7 8 9 ((10))
( ) = peaks of the base MMR
(( )) = peaks of the first bag MMR
root = only peak of the second bag MMR
Properties:
- The last leaf always has a 1-hash proof.
- Recent leaves have smaller proofs than under Bitcoin's construction.
- No duplicate vulnerability: unpaired nodes are promoted rather than duplicated.
Leftward Promotion (RFC 6962)
RFC 6962 (2013) specified leftward promotion: the lowest unpaired node is paired with the first unpaired node to its left, and the process repeats until reaching the highest unpaired node. This is equivalent to the recursive MMR approach with non-base layers built in reverse.
This method has better existing library coverage due to its use in Certificate Transparency, but it loses the property of minimal proofs for recent leaves.
Acknowledgements
Neil Booth (kyuupichan), for effectively implementing SHV in Electrum in 2018. Roger Taylor (rt121212121) and Electron Cash developers, for being among first SHV adopters in 2018. Authors of the Utreexo paper, which I skimmed in 2021 and forgot about, for planting the idea of a Merkle forest in my head, and emergent_reasons for pointing me to it. Mainnet Pat for planting the idea of an extensible Merkle tree in my head in 2023. Thomas Zander for pointing me to Electrum's existing checkpoint system in 2024. Claude AI for pointing me to "Merkle Mountain Ranges" when I tried to implement my "CHIP-2025-03: Merkle Header Commitment for Enhanced SPV Scalability".