DeFi Security AllianceRequest an audit
Menu

EVM patterns

Merkle Proof Verification: Empty Sets, Leaf Order and Root Trust

Merkle proof verification establishes a reconstruction result against a chosen root, while application authorization needs its own conditions. In 64 local OpenZeppelin multiproof cases, 8 returned true, including 2 with no selected leaves. Check leaf construction, input order, root provenance and the action policy separately.

Graphite blocks linked as a Merkle tree beside an empty metal input tray connected to a blue verification gauge.

Key facts

Executed population
64 local cases across 2 overloads, 8 scenarios and 4 roots
Outcomes
8 true, 40 false and 16 reverted calls
Empty selected sets
2 of the 8 true results selected no leaf
Overload comparison
32 memory/calldata pairs agreed on every tested outcome
Scope
Pinned OpenZeppelin v5.5.0 pure multiproof wrappers, no token claim

Define the verification contract

Start with the predicate the contract actually evaluates.

In the retained OpenZeppelin implementation, verification reconstructs a hash from the supplied inputs and compares it with the supplied root. That comparison does not establish who approved the root, whether the request contains an actionable entitlement or whether a previous request already consumed it. Those conditions need their own checks.

A Merkle proof provides the sibling hashes needed to reconstruct a root from a leaf. A single inclusion proof follows one branch. A multiproof combines selected leaves with shared intermediate hashes, using proof flags to decide where the next value comes from. Both mechanisms depend on an agreed leaf construction and node-hashing scheme.

Leaf
The value whose inclusion is being checked. The Solidity verifier receives a bytes32 value; it does not infer the account, amount or schema behind that value.
Root
The commitment against which reconstruction is compared. An application must establish which root belongs to the intended distribution or release.
Proof
Sibling hashes supplied to the reconstruction algorithm. An empty sibling array is different from an empty set of selected leaves.
Proof flags
Instructions for a multiproof's queue. They select another queued value or a proof sibling, rather than authenticate the request's business meaning.

Write the application invariant before choosing a helper. For a distribution, that might require a nonempty request, a root selected by the application, correctly encoded recipient entitlements and an unconsumed claim index. A successful membership calculation supplies part of that evidence. It is not a substitute for the entire invariant.

The OpenZeppelin cryptography reference explicitly documents the empty-set multiproof case. Our airdrop contract security guide covers allocation and claim-consumption design. The narrower engineering job here is to make the verifier's acceptance boundary inspectable before attaching an application action.

Keep the two questions separate during debugging: did reconstruction match the chosen commitment, and did the application authorize the intended action? A user interface message such as invalid proof or not eligible can combine failures from different stages. Preserve the underlying result instead of assigning every rejection to the tree.

What 64 local multiproof cases showed

Method

We executed retained OpenZeppelin Contracts v5.5.0 source on . A fixture exposes the default-hasher memory and calldata multiproof helpers through pure wrappers. It neither transfers tokens nor consumes an entitlement. The input leaves are synthetic bytes32 hashes, not encoded claims.

Population
64 cases: 2 overloads, 8 scenarios and 4 root contexts. Every combination was executed; no final-grid cases were excluded.
Scenarios
Complete leaves, swaps within sibling pairs, a cross-pair swap, a tampered leaf, empty selected leaves, one selected leaf, an invalid length equation and an unused proof element.
Root contexts
The canonical constructed root, an unrelated hash, the first leaf hash or zero. Proof inputs remain fixed while the chosen comparison root changes.
Execution
Solidity 0.8.36, optimizer enabled, via IR and a Cancun local EVM. Fresh arrays are constructed for each row.
Records
seo/research/merkle-proof-verification-2026-11-30/measurement.py, MerkleMatrix.t.sol and measurement.json are repository artifacts, not public downloads. The independent checker reconstructs sorted-pair Keccak results and authorization-free branch outcomes.

The complete grid produced 48 completed calls and 16 reverts. Of the completed calls, 8 returned true and 40 returned false. Independent reconciliation checked every row and all 32 memory/calldata pairs. A second execution reproduced the full ledger exactly.

Results

Scenario outcomes across both overloads and all four roots, measured
ScenarioCasesTrueFalseRevert
Complete four leaves8260
Swap within both pairs8260
Swap across pairs8080
Tamper one leaf8080
Empty leaves with root proof8260
One leaf with two siblings8260
Invalid length equation8008
Unused proof element8008

The empty-set rows use no selected leaves, no flags and a proof containing the canonical root. They returned true under that root in both overloads. Consequently, 2 of the 8 true results establish no selected entitlement. This matches the documented no-op behavior; it is not evidence of a library vulnerability.

Root-context outcomes; 16 cases per root from the same grid
Comparison rootTrueFalseRevert
Canonical root844
Unrelated hash0124
First leaf hash0124
Zero0124

Within this fixture, every true result used the canonical comparison root. That observation does not authenticate a production root. It only reconciles the supplied inputs with a known constructed commitment. A root's release history and update authority remain outside the experiment.

Limits

  • Constructed local inputs do not estimate deployed exposure, incident frequency or loss.
  • Only the default commutative Keccak multiproof overloads were executed. Custom hashers and the JavaScript generator were source-reviewed separately.
  • No token distribution, repeated claim, protected action, public-chain fork or gas comparison was executed.
  • The grid is not an exhaustive malformed-array census. Additional input shapes may fail through other paths and need implementation-specific tests.

Match the leaf and node scheme

The verifier sees a hash, not its meaning.

A generator and a contract can both use Keccak while disagreeing about the bytes being hashed. Preserve field types, field order, encoding and the number of hashing steps as part of one interface contract. A mismatch at this boundary should not be repaired by changing arbitrary proof entries until a test passes.

The inspected standard-tree generator hashes an ABI-encoded value and hashes that result again. Its node function hashes a sorted concatenation of the two child hashes. These are different operations. Sorting node pairs does not sort an account and amount inside the leaf encoding, nor does it remove the need to match their declared types.

Source-reviewed construction choices; not separate executed generator routes
ConstructionRelevant behaviorIntegration requirement
Standard treeTyped values are double-hashedRebuild the same encoded leaf
Simple treeCaller supplies bytes32 leavesDocument the prior leaf-hashing scheme
Default Solidity node hashChildren are ordered before KeccakUse a compatible commutative tree

The source warning about 64-byte leaf preimages concerns confusion with a concatenated pair of internal nodes. It does not mean the verifier reads a payload and rejects it because of that length. The standard double-hash construction gives the outer leaf hash a fixed hash-sized input rather than the original encoded payload. Reuse the generator's documented construction instead of inventing a superficially similar encoding.

Our local leaves deliberately avoid an application schema: they are hashes of synthetic labels. The observed acceptance counts therefore say nothing about whether a recipient, amount, chain or distribution identifier was encoded correctly. Those fields must be checked in an application fixture using its actual encoder and contract code.

Do not infer compatibility from a shared root label or library name. The official generator documentation distinguishes standard and simple trees. Retain the generator's input values and encoding definition alongside the root so another reviewer can reconstruct the commitment independently. A root without that material is difficult to diagnose. A migration also needs this boundary. Replacing a generator while keeping an old verifier can alter leaf hashing or tree construction. Compare a known leaf, its sibling path and the resulting root before changing production configuration. Such a comparison is an integration test to perform, not a migration result established by our multiproof grid.

Trace multiproof order and failure

The reconstruction algorithm consumes a queue.

It takes leaves first, then previously computed hashes. A true proof flag takes the next value from that main queue; a false flag takes a supplied proof sibling. The resulting hash goes back into the hash sequence. Reading the flag array without the ordered leaves and proof array loses the operation it describes.

The pinned implementation checks leaves.length + proof.length == proofFlags.length + 1. It also rejects unconsumed proof elements after reconstruction. The length equation is a prerequisite, not a complete acceptance test. Our unused-proof scenario satisfies that equation but still reverts with MerkleProofInvalidMultiproof. Its flags do not consume the supplied sibling. All 16 observed reverts used that custom error selector. Preserve the generator's returned leaf order. Its requested indices and returned multiproof leaves need not have the same order. The documented sufficient construction uses a complete tree, which need not be perfect, and the required reverse traversal of selected leaves. Our executed tree is a small perfect tree; we did not test every supported complete-tree shape.

Commutativity creates a useful negative-control boundary. Swapping both sibling pairs preserved the canonical result in our full-leaf case. Moving a leaf across those pairs did not. Thus neither statement that every reorder fails nor statement that any order works describes the tested behavior. Keep the precise permutation in the record.

Sibling swaps preserve pairs but cross-pair swaps change reconstructionThe tested four-leaf root combines the hash of A and B with the hash of C and D. Swapping A with B and C with D preserves both child hashes. Swapping B with C creates different child pairs and did not verify against that root.Original pairsH(A, B)H(C, D)Within-pair swapsH(B, A)H(D, C)Cross-pair swapH(A, C)H(B, D)Same tested rootSame tested rootDifferent tested result
These are the executed permutations, not a general license to reorder a multiproof.
Pair-preserving change
Exchange siblings within their existing pairs. The tested commutative node hash preserves each pair's output.
Pair-changing control
Move a leaf into another pair while retaining the flags. The tested reconstruction no longer matched the canonical root.

The two overloads agreed on every tested input. That is a compatibility observation, not a gas benchmark. In the calldata variant, proof and flags use calldata while the library's leaves parameter remains memory. Compare the exact signature rather than assuming that an overload name describes every argument's data location.

Finally, retain the result type. A completed call returning false is different from a reverted call. A wrapper can choose to convert a false result into a revert, but that wrapper policy belongs in its own test. Our low-level capture records both outcomes and preserves the revert selector instead of replacing all failures with one boolean.

Bind verification to application policy

The empty-set case needs an explicit policy.

If an endpoint promises to process at least one entitlement, reject an empty selected-leaf set before relying on a successful multiproof. If a batch endpoint intentionally permits no-op requests, document that choice and ensure its other effects are consistent with a no-op. The helper cannot choose the endpoint's meaning.

require(leaves.length != 0, "Empty batch");
require(
    MerkleProof.multiProofVerify(proof, proofFlags, root, leaves),
    "Invalid proof"
);
Proposed nonempty-batch policy sketch, not executed in the measured pure wrappers. Root selection, leaf binding and claim consumption still require application code.

An empty multiproof can reconstruct a root from its single proof element without selecting any leaf. The inspected generator source also produces a root-containing proof for an empty index list. We inspected that generator branch but did not execute JavaScript. Empty-set acceptance is therefore a documented boundary to handle, not a surprising incident to attribute to a deployed project.

Application acceptance conditions and the evidence each needs
ConditionEvidenceUnresolved by pure proof verification
Intended root selectedRelease record and contract rootWho can replace the commitment
Meaningful batchNonempty policy or documented no-opEndpoint-specific side effects
Entitlement boundTyped leaf reconstructionUnencoded recipient or amount changes
Claim not consumedClaim index or equivalent stateRepeated use of valid evidence

Root lifecycle is part of the authority review. Record the distribution version, the configured commitment and any actor able to update it. The administrative authority inventory helps separate that control from ordinary claim submission. A proof against a caller-selected root does not establish that the application approved the corresponding dataset. The inspected Uniswap distributor illustrates a separate application layer: its root is immutable, its leaf binds index, account and amount, and it marks the index claimed before transferring to the account. We source-reviewed those choices; our fixture did not execute that distributor. Do not copy its packed leaf encoding into a standard-tree integration without also matching that generator and schema.

A proof can remain mathematically valid after an entitlement has been consumed. The application needs a consumption rule if repeated action is forbidden. Use the protocol invariant review to connect the commitment check with the permitted state transition. Neither a true result nor a familiar bitmap variable establishes that the complete action path enforces the intended rule.

Build a reproducible verification packet

Debug from stable inputs toward the final action.

Changing the encoding, leaf order and root simultaneously can hide the boundary that failed. Keep one canonical positive control and change one meaningful input at a time. Our pair-preserving and cross-pair permutations demonstrate why the precise mutation matters more than a label such as shuffled leaves.

  1. Identify the executing verifier and exact dependency source. Preserve the package pin and source hashes with the contract implementation.
  2. Retain typed generator inputs, leaf encoding and the generated tree artifact. Reconstruct a known leaf before investigating the sibling path.
  3. Copy the returned multiproof leaves, proof and flags together. Preserve order and distinguish requested indices from returned leaves.
  4. Compare the supplied root with the application's configured root at a named chain, contract and block. Include the distribution or release identifier.
  5. Record call completion, returned boolean or revert data. Then test the separate nonempty, entitlement-binding and consumption conditions in the application fixture.

The dependency evidence guide covers source and version alignment. A stale snippet can describe an overload or behavior that is absent from the installed package. Likewise, a successful generator check should be reproduced against the actual contract verifier before it becomes release evidence. Our local result establishes one pinned source configuration, not every installation sharing its name.

Retain the arrays, not only their lengths. Proof size is useful for diagnosing shape, but equal lengths do not establish equal content or correct queue consumption. Our invalid-length and unused-proof rows fail for different structural reasons. A useful record preserves enough input data to reproduce that difference rather than merely reporting that the transaction reverted.

Profiles such as the Pharos Production member record can help organize a review request. The security tools hub provides supporting checks. Neither a provider listing nor a generic proof generator substitutes for evidence from the implementation and application action being assessed.

The release decision should name the actual result: reconstruction matched the approved root for these encoded entitlements, under this nonempty and consumption policy, in this observed state. Any missing condition remains unresolved. Keep the local ledger's narrower conclusion intact: the tested verifier accepted an empty selected set in its documented no-op case, while application authorization remained outside that pure calculation.

Frequently asked questions

Does an empty sibling proof always fail for a single leaf?

In the inspected single-proof implementation, processProof starts with the leaf and applies each supplied sibling. With no siblings, its result remains the leaf, so verification succeeds if that value equals the supplied root. This source-reviewed boundary differs from an empty selected-leaf multiproof. The local grid did not execute the single-proof overload.

Can a different hash scheme be substituted without changing the proof?

The default implementation uses commutative Keccak node hashing. A custom-hasher overload still needs a compatible commutative construction and safe memory behavior. A directional or differently hashed tree requires its own verifier logic and matching proofs. Bitcoin or another tree family should not be assumed compatible. No custom-hasher route was executed in the grid.

Does a source file update header identify the installed package version?

Record the package or repository pin and the exact source hash. A file header naming the last update is not the same evidence as the release containing that file. This experiment used source retained from the v5.5.0 tag; it did not compare historical releases or prove that every deployment uses that version.

Comments

0

    Leave a comment

    Share a question or observation about this article.

    10 to 3,000 characters.