Skip to content

fix(mmr): reject non-canonical mmr_size in proof verification - #974

Merged
QuantumExplorer merged 1 commit into
developfrom
claude/grovedb-issue-692-4c1702
Sep 17, 2026
Merged

QuantumExplorer merged 1 commit into
developfrom
claude/grovedb-issue-692-4c1702

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Sep 17, 2026 •

Copy link
Copy Markdown
Member

Issue

Closes #692.

MMR proof verification trusted the mmr_size a proof carries. Two things went wrong with that:

  1. Non-canonical sizes verified as a smaller tree. get_peaks / get_peak_map round a size no MMR can have (2, 5, 6, 9, ...) down to the last valid MMR below it. Sizes 5 and 6 share their peak set with size 4, and size 2 shares its with size 1, so an honest proof relabelled with one of those sizes recomputed the honest root and was accepted.
  2. Extreme sizes overflowed position arithmetic. mmr_size_to_leaf_count(u64::MAX) is 2^63, so leaf index 2^63 - 1 passed the idx < leaf_count range check and then hit 2 * leaves_count in leaf_index_to_mmr_size. That is a panic under overflow checks and a wrapped position without them. In GroveDB the size comes from the parent element carried by the proof, so this ran before the element was bound to the trusted root.

Both were reproduced at runtime before the fix (tests written first):

test_verify_rejects_non_canonical_mmr_size ... FAILED   verify must reject: [(0, [97])]
test_verify_rejects_mmr_size_beyond_position_arithmetic ... FAILED
  panicked at grovedb-merkle-mountain-range/src/helper.rs:26:5: attempt to multiply with overflow

No GroveDB root forgery follows from (1). verify_mmr_lower_layer requires the proof's size to equal the element's size, and the element bytes are hash-bound, so a relabelled size changes the derived root. The fix makes the MMR crate's own verifier sound instead of relying on that outer check.

What was done

  • New checked_mmr_size_to_leaf_count(mmr_size) -> Option<u64> in grovedb-merkle-mountain-range. It is the single definition of a canonical size: 2 * leaf_count - popcount(leaf_count) == mmr_size, computed with checked arithmetic. That arithmetic also rejects u64::MAX, the only size whose leaf count (2^63) has a last index that cannot be converted. Every index below a returned count is safe for leaf_index_to_pos / leaf_index_to_mmr_size.
  • Enforced in:
    • calculate_peaks_hashes, which covers every MerkleProof root computation: calculate_root, verify, and both sizes in calculate_root_with_new_leaf
    • verify_incremental
    • calculate_root_with_new_leaf, up front for new_mmr_size (InvalidInput, since it is a caller argument)
    • MmrTreeProof::verify / verify_and_get_root (InvalidProof)
    • MmrTreeProof::generate (InvalidInput)
  • The state-sync validate_mmr_size in grovedb/src/replication/non_merk_sync.rs had its own copy of this check. It now delegates to the shared helper.
  • Doc fixes in helper.rs. The get_peaks doc comment had drifted onto hash_count_for_root_bagging, and the arithmetic-safety notes pointed callers at the unchecked helper.

Not version-gated. Every size a real MMR reaches is canonical, so no honest proof or stored tree changes behaviour. The bulk-append chunk MMR derives its expected size from leaf_count_to_mmr_size(completed_chunks) with completed_chunks <= 2^63 - 1, which is always canonical, so CommitmentTree proofs are unaffected.

Tests

  • helper.rs
    • every reachable size for 1..=1024 leaves round-trips
    • exactly the canonical sizes in 0..=16 are accepted
    • the largest accepted size is u64::MAX - 64 (2^63 - 1 leaves) and its last index converts cleanly
    • every size above that, up to u64::MAX, is refused
  • proof.rs
    • relabelled sizes 2/5/6 are rejected by verify and verify_and_get_root
    • u64::MAX with index 2^63 - 1 returns InvalidProof instead of panicking
    • MerkleProof::calculate_root, calculate_root_with_new_leaf, verify_incremental and MmrTreeProof::generate each reject
  • grovedb/src/tests/non_merk_completeness_budget_tests.rs: a forged parent MmrTree element declaring u64::MAX, u64::MAX - 1, 2, 5 or 6 is refused by GroveDb::verify_query with a bounded InvalidProof.

Test, lint and format runs:

  • cargo test -p grovedb -p grovedb-bulk-append-tree -p grovedb-merkle-mountain-range: all pass (grovedb 3490 passed / 8 ignored, MMR 128, bulk 120)
  • cargo clippy -p grovedb-merkle-mountain-range -p grovedb --all-targets -- -D warnings: clean
  • cargo fmt: clean

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • MMR proof verification now rejects invalid, non-canonical tree sizes.
    • Prevented forged proofs from producing valid roots when using alternative sizes.
    • Added safeguards against overflow-related failures for exceptionally large sizes.
    • State synchronization now consistently validates MMR sizes using the same canonical rules.

The peak helpers round a non-canonical MMR size (2, 5, 6, ...) down to the
last valid MMR below it, so an honest proof relabelled with such a size
recomputed the same root. `u64::MAX` maps to 2^63 leaves, whose last leaf
index passed the range check and then overflowed `leaf_index_to_mmr_size`
(a panic under overflow checks, a wrapped position without them) before the
proof was bound to a trusted root.

Add `checked_mmr_size_to_leaf_count`, the single definition of a canonical
size (`2 * leaves - popcount(leaves) == mmr_size`, checked arithmetic), and
enforce it in `calculate_peaks_hashes` (so every `MerkleProof` root
computation), `verify_incremental`, `calculate_root_with_new_leaf`,
`MmrTreeProof::verify` / `verify_and_get_root` and `MmrTreeProof::generate`.
The state-sync `validate_mmr_size` now delegates to it.

Not version-gated: every size a real MMR reaches is canonical, so no honest
proof changes.

Closes #692

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: 4818298a-228d-4372-aef1-4374b548a814

📥 Commits

Reviewing files that changed from the base of the PR and between dc4fc5c and 07deaa3.

📒 Files selected for processing (6)
  • CHANGELOG.md
  • grovedb-merkle-mountain-range/src/helper.rs
  • grovedb-merkle-mountain-range/src/lib.rs
  • grovedb-merkle-mountain-range/src/proof.rs
  • grovedb/src/replication/non_merk_sync.rs
  • grovedb/src/tests/non_merk_completeness_budget_tests.rs

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The change adds checked canonical MMR size validation. Proof APIs and replication synchronization reject non-canonical sizes before position arithmetic. Unit and integration tests cover forged sizes, including u64::MAX.

Changes

MMR size validation

Layer / File(s) Summary
Canonical size helper and bounds tests
grovedb-merkle-mountain-range/src/helper.rs, grovedb-merkle-mountain-range/src/lib.rs
Adds and re-exports checked_mmr_size_to_leaf_count. Tests cover valid sizes, non-canonical sizes, and position arithmetic bounds.
Proof API validation
grovedb-merkle-mountain-range/src/proof.rs
Proof generation, root calculation, incremental verification, and verification reject non-canonical MMR sizes with structured errors.
Replication integration and regression coverage
grovedb/src/replication/non_merk_sync.rs, grovedb/src/tests/non_merk_completeness_budget_tests.rs, CHANGELOG.md
Replication validation uses the shared helper. Regression tests cover forged sizes. The changelog records the fix.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 07dea

MMR proof and replication handling now reject malformed sizes before unsafe arithmetic, with no remaining concrete merge-blocking risk identified.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: rejecting non-canonical mmr_size values during MMR proof verification.
Linked Issues check ✅ Passed Issue #692 requires canonical mmr_size validation before MMR proof verification and checked arithmetic for extreme sizes, while preserving valid proof behavior. The PR adds `checked_mmr_size_to_leaf…
Out of Scope Changes check ✅ Passed The changes stay within Issue #692. The helper, proof API updates, GroveDB state-sync reuse, changelog entry, and regression tests directly support canonical-size validation or overflow safety. No unr…
Docstring Coverage ✅ Passed Docstring coverage is 92.59% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 27 functions across 5 files. (1 skipped: 1 …
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/grovedb-issue-692-4c1702

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@thepastaclaw

thepastaclaw commented Sep 17, 2026 •

Copy link
Copy Markdown
Contributor

🕓 Queued for automated review — 2nd in line, estimated start in ~40 min (commit 07deaa3)
Estimated review time once started: ~1.4 h (two-phase automated review; median of recent runs).

  • Request priority review — click to move this review to the front of the queue.

@QuantumExplorer QuantumExplorer left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed

@QuantumExplorer
QuantumExplorer merged commit edc346c into develop Sep 17, 2026
12 checks passed
@QuantumExplorer
QuantumExplorer deleted the claude/grovedb-issue-692-4c1702 branch September 17, 2026 04:15
@codecov

codecov Bot commented Sep 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.95%. Comparing base (a579d52) to head (07deaa3).
⚠️ Report is 9 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop     #974      +/-   ##
===========================================
+ Coverage    92.93%   92.95%   +0.01%     
===========================================
  Files          331      331              
  Lines       104225   104450     +225     
===========================================
+ Hits         96864    97088     +224     
- Misses        7361     7362       +1     
Components Coverage Δ
grovedb-core 91.22% <99.04%> (+0.01%) ⬆️
merk 93.97% <ø> (ø)
storage 91.94% <100.00%> (+0.07%) ⬆️
commitment-tree 95.62% <ø> (ø)
mmr 95.43% <100.00%> (+0.31%) ⬆️
bulk-append-tree 92.78% <ø> (ø)
element 97.18% <ø> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[audit][medium] MMR proof verification accepts invalid mmr_size values

2 participants