Skip to content

fix(merk,grovedb): refuse backward-reference rows in count-offset proofs - #988

Merged
QuantumExplorer merged 1 commit into
developfrom
fix/count-offset-backward-ref-forgery
Sep 23, 2026
Merged

QuantumExplorer merged 1 commit into
developfrom
fix/count-offset-backward-ref-forgery

Conversation

@QuantumExplorer

@QuantumExplorer QuantumExplorer commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Summary

This fixes a proof-soundness bug in the count-offset verifier. A malicious proof supplier could make an offset-paginated query over a ProvableCountTree, ProvableCountSumTree or ProvableCountProvableSumTree return attacker-chosen item bytes or sum values together with the genuine root hash. The bug was found and reproduced by the 2026-09-23 audit and had not been filed as an issue.

The forgery

An honest count-offset proof returns an in-range item as KVCount(k, item, c) (or KVCountSum on a PCPS host), and the verifier recomputes H(item) from the bytes. KVValueHashFeatureType instead hashes (key, value_hash, aggregates) with value_hash taken from the proof, so its value bytes are not bound. The attacker rewrites the honest node as:

KVValueHashFeatureType(k, forged, H(item), ProvableCountedMerkNode(c))

The node hash does not change, because kv_hash(k, v) == kv_digest_to_kv_hash(k, H(v)), so the root does not change either.

classify_self (merk/src/proofs/query/count_offset/verify.rs) was the only element-type check on that node, and it refused only Item / SumItem / ItemWithSumItem (has_simple_value_hash). The regular merk verifier execute_proof also refuses the backward-references items there (added in #843). The count-offset verifier rebuilds its tree with execute_with_options, though, so that refusal never ran on this path. The GroveDB post-filter in run_count_offset_layer_dispatch checked only NonCounted, non-empty trees, raw references and the empty-tree hash. So a forged row of any of these types was returned through verify_query, verify_query_with_options, verify_query_raw and verify_path_query under the genuine root:

  • ItemWithBackwardsReferences: arbitrary item bytes
  • SumItemWithBackwardsReferences: an arbitrary sum
  • ItemWithSumItemWithBackwardsReferences: both

Provable* count trees refuse all three at insert, so an honest proof never carries one on a directly read row. Every such row is a forgery.

Scope: offset > 0 queries on PCT / PCS / PCPS hosts with V1 envelopes, under GROVE_V3 (live) and V4, in grovedb >= 6.0.0. No current Dash Platform caller verifies offset queries on these trees, because DAPI refuses document offsets outside the V4 ranked path.

Fix

  • Merk (classify_self): the KVValueHashFeatureType guard is now an allowlist of what an honest prover puts on that node: trees (ElementType::is_tree, which covers every Merk, non-Merk and indexed tree) and references (is_reference). Only these have a combine-hash value hash the verifier cannot recompute. Everything else is refused, including element types added later. This guard is the only one for the indexed-axis callers of verify_count_offset_on_range_proof, which have no GroveDB post-filter.
  • GroveDB (run_count_offset_layer_dispatch), defense in depth: a returned row that did not come through a reference must be a simple item or a tree. Non-empty trees and the empty-tree hash are already checked there. Rows resolved through a reference are exempt, because their value is the target's bytes, bound by the KVRefValueHash* combine. A reference in a count tree may legitimately resolve to an ItemWithBackwardsReferences elsewhere; end_to_end_offset_dereferences_bidirectional_references pins that honest shape, and it still passes.
  • Corrected a stale doc comment: run_count_offset_layer_dispatch is called only from verify_layer_proof_v1. V0 envelopes with an offset are rejected earlier by apply_count_offset_envelope_gate, so neither change touches V0 verification.
  • Book: added the value-substitution attack to the count-offset attack table, and a backward-references row plus a count-offset note to "Which node forms bind their value bytes".

No GroveVersion gate. This is client-side verifier strictness: it rejects only proof shapes an honest prover never emits. The prover and proof bytes are unchanged, and no V0 function is touched.

Tests

New module grovedb/src/tests/count_offset_backward_ref_forgery_tests.rs, built from the audit's reproductions:

  • forged_backward_reference_rows_are_rejected_on_every_host_and_entry_point: 3 forged variants × PCT / PCS / PCPS × GROVE_V3 / latest × ascending / descending × all four public verify entry points. Each case first checks that the honest proof verifies to the real root. It then checks that the rewrite leaves the host root unchanged, so the refusal is not a side effect of a hash mismatch, and that the refusal comes from the merk-level allowlist.
  • grovedb_allowlist_rejects_unresolved_backward_reference_rows: the GroveDB-level check fires by itself, ahead of the parent chain check.
  • forged_plain_item_row_stays_rejected: the pre-existing Item control.
  • count_hosts_refuse_backward_reference_items_at_insert: pins the premise that every Provable* count host refuses all three types at insert.

Plus rejects_backward_reference_items_on_kv_value_hash_feature_type in merk/src/proofs/query/count_offset/tests.rs, for direct merk callers.

Checked against the unfixed code:

  • With both fixes reverted, the forgery test fails with Ok(<genuine root>), the same result the audit reproduced.
  • With only the merk fix reverted, the GroveDB-level allowlist alone still refuses every forged row.
  • The merk test fails without the merk fix.

cargo test -p grovedb-merk passes (775 unit tests and 9 doctests), as do the new grovedb module and the existing count-offset suites. The full cargo test -p grovedb run was still in progress when this PR was opened; I'll follow up here with the result. cargo fmt is clean, and cargo clippy -p grovedb -p grovedb-merk --all-targets -- -D warnings is clean.

Follow-up (not in this PR): execute_proof's KVValueHashFeatureType guard is still a denylist (has_simple_value_hash plus the three backward-references items). Today that matches this allowlist exactly, because every element type is an item, a reference or a tree, but it would not refuse a new item type by default.

🤖 Generated with Claude Code

PR Hygiene · 559c242

  • Bots — coderabbitai ✓ · thepastaclaw not yet — /skip-bots proceeds without the ones not yet reported
  • Self-review — post /self-reviewed once the bots are done
  • Within your 5 open PRs
  • Build green
  • Approvals — you own every area touched; none needed

When every box is checked the PR Hygiene check passes and this can merge.

Summary by CodeRabbit

  • Bug Fixes
    • Count-offset proof verification now rejects forged results that use backward-reference item types, including cases that preserve the original root.
    • Verification also rejects unresolved result rows that are not valid simple items or trees.
  • Documentation
    • Updated proof-system and pagination guidance to explain which element types are accepted and how these forgeries are rejected.

The count-offset verifier's `classify_self` refused only Item / SumItem /
ItemWithSumItem on a KVValueHashFeatureType node. That node hashes the
proof-carried value hash, not the value bytes, so a proof supplier could
re-emit an honest KVCount(k, item, c) as
KVValueHashFeatureType(k, forged, H(item), c) without changing the root and
have a forged ItemWithBackwardsReferences, SumItemWithBackwardsReferences
or ItemWithSumItemWithBackwardsReferences returned as the row under the
genuine root. The verifier rebuilds the tree with execute_with_options, so
the refusal execute_proof applies to these types never ran, and the
GroveDB post-filter did not check for them.

- classify_self now allowlists what an honest prover puts on that node:
  trees and references. Everything else, including future element types,
  is refused.
- run_count_offset_layer_dispatch additionally requires a row not resolved
  through a reference to be a simple item or a tree.

Both run only on the V1 count-offset path and reject only shapes an honest
prover never emits, so no GroveVersion gate is needed. Regression tests
cover all three forged types on PCT, PCS and PCPS hosts under GROVE_V3 and
latest, through every public verify entry point.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: d7c4ec38-9118-47e5-9dde-b279729743a6

📥 Commits

Reviewing files that changed from the base of the PR and between b7f8716 and 559c242.

📒 Files selected for processing (8)
  • docs/book/src/count-offset-paginated-queries.md
  • docs/book/src/proof-system.md
  • grovedb/src/operations/proof/verify.rs
  • grovedb/src/tests/count_offset_backward_ref_forgery_tests.rs
  • grovedb/src/tests/count_offset_paginated_tests.rs
  • grovedb/src/tests/mod.rs
  • merk/src/proofs/query/count_offset/tests.rs
  • merk/src/proofs/query/count_offset/verify.rs

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


📝 Walkthrough

Walkthrough

Count-offset proof verification now rejects forged backward-reference item values on Merk feature-type nodes and unresolved GroveDB count rows. New tests cover these checks across query directions, host types, and public verification entry points. Documentation describes the verifier paths and the allowlists.

Changes

Count-offset proof verification

Layer / File(s) Summary
Merk feature-type allowlist
merk/src/proofs/query/count_offset/verify.rs, merk/src/proofs/query/count_offset/tests.rs
classify_self now accepts only tree and reference element types on KVValueHashFeatureType nodes. Tests forge backward-reference item rows and confirm rejection while preserving the reconstructed root.
GroveDB dispatch check and end-to-end coverage
grovedb/src/operations/proof/verify.rs, grovedb/src/tests/count_offset_backward_ref_forgery_tests.rs, grovedb/src/tests/count_offset_paginated_tests.rs, grovedb/src/tests/mod.rs, docs/book/src/count-offset-paginated-queries.md, docs/book/src/proof-system.md
The count-offset dispatch rejects unresolved rows that are not simple items or trees. New tests cover query directions, host types, verification entry points, and insertion restrictions. Documentation and existing test comments describe the allowlists and their scope.

Priority: ⬆️ High

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

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 559c2

This change tightens count-offset proof verification so that forged backward-reference rows are rejected instead of verifying under the genuine root hash. The new checks accept only the node shapes that honest provers already emit, so valid proofs are not expected to be affected. No merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 6 files. (2 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 backward-reference rows in count-offset proofs across Merk and GroveDB.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Full details: Docstring Coverage

Explanation

Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 6 files. (2 skipped: 2 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR

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.

@github-actions github-actions Bot added the waiting-bots Waiting for the review bots to report on this head label Sep 23, 2026
@thepastaclaw

thepastaclaw commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

🕓 Queued for automated review — 8th in line, estimated start in ~1.9 h (commit 559c242)
Estimated review time once started: ~35 min (two-phase automated review; median of recent runs).

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

@codecov

codecov Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.95%. Comparing base (d5a54b7) to head (559c242).
⚠️ Report is 10 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop     #988   +/-   ##
========================================
  Coverage    92.95%   92.95%           
========================================
  Files          331      331           
  Lines       104500   104516   +16     
========================================
+ Hits         97138    97154   +16     
  Misses        7362     7362           
Components Coverage Δ
grovedb-core 91.23% <100.00%> (+<0.01%) ⬆️
merk 93.98% <100.00%> (ø)
storage 91.94% <ø> (ø)
commitment-tree 95.62% <ø> (ø)
mmr 95.43% <ø> (ø)
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.

@QuantumExplorer
QuantumExplorer merged commit b020b38 into develop Sep 23, 2026
16 of 17 checks passed
@QuantumExplorer
QuantumExplorer deleted the fix/count-offset-backward-ref-forgery branch September 23, 2026 18:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

waiting-bots Waiting for the review bots to report on this head

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants