Skip to content

Commit 979d1c0

Browse files
fix: address CodeRabbit findings for ProvableCountProvableSumTree PR
Addresses every actionable finding from the CodeRabbit review on PR #670. **Critical security fix** - verify.rs::extract_elements_and_leaf_keys: reject Node::KVRefValueHashCountSum in the opaque-hash guard alongside KVRefValueHash{,Count,Sum}. Without this, a forged trunk/branch proof could smuggle an unauthenticated dereferenced value through the new dual-axis reference node — the merk-level hash chain would still appear valid because the embedded opaque hash is treated as authoritative, but the verifier never gets to see the referenced value at this layer. Also extend leaf-count extraction to include KVCountSum. **Major correctness fixes** - grovedb/src/lib.rs::aggregate_consistency_labels: add explicit arm for (ProvableCountProvableSumTree, ProvableCountAndProvableSum) + empty-merk identity case. Without this, valid PCPS trees fell into the catch-all and were reported as aggregate mismatches. - merk/src/proofs/tree.rs::execute_with_options: include KVCountSum / KVDigestCountSum / KVRefValueHashCountSum in the Op::Push and Op::PushInverted BST-order key checks so dual-axis proofs enforce the same monotonic-key invariant as every other keyed node type. - merk/src/proofs/query/verify.rs: thread dual-axis nodes through the lower/upper-bound `last_push` matches, the absence-proof last-push match, the `boundaries_in_proof` helper, and `key_exists_as_boundary_in_proof`. Without these, `Key + Range` queries against ProvableCountProvableSumTree could be wrongly rejected with "Cannot verify lower bound of queried range" or miss legitimate boundaries entirely. - merk/src/proofs/query/mod.rs::to_kv_value_hash_feature_type_node: recognize ProvableCountAndProvableSum aggregates and surface TreeFeatureType::ProvableCountedAndProvableSummedMerkNode (was falling through to self.tree().feature_type(), which would carry the local feature instead of the aggregated (count, sum) that is actually committed in the node hash for KvRefValueHashCountSum reference proofs). - grovedb/src/batch/mod.rs: add ProvableCountProvableSumTree arms in two sites — the LayeredValueDefinedCost match for flag updates and the InsertTreeWithRootHash propagation branch. Without these, valid dual-axis batch inserts fell into the "insertion of element under a non tree" error path during upward propagation. - grovedb/src/operations/proof/generate.rs: add an `is_aggregate_sum_query` short-circuit for empty ProvableSumTree / ProvableCountProvableSumTree under an AggregateSumOnRange carrier. Without this, empty sum-bearing hosts fell through to the generic empty-tree branch and no lower-layer ASOR proof got emitted. - grovedb/src/tests/provable_count_sum_tree_tests.rs::get_node_count: recognize the dual-axis KVCountSum / KVDigestCountSum / KVRefValueHashCountSum variants so rotation/stress proof-tests no longer silently skip dual-axis nodes when verifying counts. Also recognize ProvableCountedAndProvableSummedMerkNode feature types in KVValueHashFeatureType nodes. **Minor error-classification fixes** - merk/src/proofs/query/aggregate_count/{mod,emit}.rs: change all prover-side aggregate invariant failures from InvalidProofError (verifier-class) to CorruptedData (local-corruption-class) per the repo error-handling convention. The corresponding unit test now expects CorruptedData. The sum side already used CorruptedData; this brings the count side into alignment. **Doc updates** - merk/src/merk/{get,prove}.rs: include ProvableCountProvableSumTree in the rustdoc allow-lists for count_aggregate_on_range / sum_aggregate_on_range / prove_aggregate_*_on_range so the contracts match the runtime guards. - grovedb-element/src/element/serialize.rs: list the ProvableSumTree and ProvableCountProvableSumTree variants in the serialize() doc — the wrapper allowlist grew from four to six sum-bearing variants. **Test fixups** - Two existing tests (shape_walk_rejects_kvdigestcountsum_outside_inherited_bounds_pcps, same for the sum side) were relaxed to accept any InvalidProofError message — adding KVDigestCountSum to the BST-order check means Phase 1's key-ordering catches the malformed key before Phase 2's inherited-bounds check does. Either rejection is correct; the goal is that an out-of-bounds boundary key never produces a successful verify. All 1720 grovedb + 540 merk tests pass; cargo fmt clean. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
1 parent 527e3af commit 979d1c0

15 files changed

Lines changed: 230 additions & 59 deletions

File tree

‎grovedb-element/src/element/serialize.rs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ impl Element {
2020
/// - Any wrapper nesting in any combination — `NonCounted`, `NotSummed`,
2121
/// and `NotCountedOrSummed` are mutually exclusive.
2222
/// - `NotSummed(x)` / `NotCountedOrSummed(x)` where `x` is not one of
23-
/// the four sum-tree variants (`SumTree`, `BigSumTree`, `CountSumTree`,
24-
/// `ProvableCountSumTree`).
23+
/// the six sum-bearing tree variants (`SumTree`, `BigSumTree`,
24+
/// `CountSumTree`, `ProvableCountSumTree`, `ProvableSumTree`,
25+
/// `ProvableCountProvableSumTree`).
2526
///
2627
/// Constructed via the `new_non_counted` / `new_not_summed` /
2728
/// `new_not_counted_or_summed` constructors these are impossible, but a

‎grovedb/src/batch/mod.rs‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2910,6 +2910,7 @@ where
29102910
| Element::ProvableCountTree(..)
29112911
| Element::ProvableCountSumTree(..)
29122912
| Element::ProvableSumTree(..)
2913+
| Element::ProvableCountProvableSumTree(..)
29132914
| Element::CommitmentTree(..)
29142915
| Element::MmrTree(..)
29152916
| Element::BulkAppendTree(..)
@@ -3242,6 +3243,22 @@ impl GroveDb {
32423243
..,
32433244
flags,
32443245
) = element
3246+
{
3247+
*mutable_occupied_entry =
3248+
GroveOp::InsertTreeWithRootHash {
3249+
hash: root_hash,
3250+
root_key: calculated_root_key,
3251+
flags: flags.clone(),
3252+
aggregate_data,
3253+
non_counted,
3254+
not_summed,
3255+
not_counted_or_summed,
3256+
}
3257+
} else if let
3258+
Element::ProvableCountProvableSumTree(
3259+
..,
3260+
flags,
3261+
) = element
32453262
{
32463263
*mutable_occupied_entry =
32473264
GroveOp::InsertTreeWithRootHash {

‎grovedb/src/lib.rs‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1287,6 +1287,8 @@ impl GroveDb {
12871287
/// - `ProvableCountTree(_, n, _)` vs. `AggregateData::ProvableCount(m)`.
12881288
/// - `ProvableCountSumTree(_, c, s, _)` vs.
12891289
/// `AggregateData::ProvableCountAndSum(cm, sm)`.
1290+
/// - `ProvableCountProvableSumTree(_, c, s, _)` vs.
1291+
/// `AggregateData::ProvableCountAndProvableSum(cm, sm)`.
12901292
///
12911293
/// A plain `Element::Tree(..)` has no aggregate field; the inner Merk's
12921294
/// `aggregate_data` is `NoAggregateData` by construction, and any other
@@ -1398,6 +1400,25 @@ fn aggregate_consistency_labels(
13981400
))
13991401
}
14001402
}
1403+
(
1404+
Element::ProvableCountProvableSumTree(_, recorded_count, recorded_sum, _),
1405+
AggregateData::ProvableCountAndProvableSum(actual_count, actual_sum),
1406+
) => {
1407+
if recorded_count == actual_count && recorded_sum == actual_sum {
1408+
None
1409+
} else {
1410+
Some((
1411+
format!(
1412+
"ProvableCountProvableSumTree recorded count {} sum {}",
1413+
recorded_count, recorded_sum
1414+
),
1415+
format!(
1416+
"inner aggregate ProvableCountAndProvableSum count {} sum {}",
1417+
actual_count, actual_sum
1418+
),
1419+
))
1420+
}
1421+
}
14011422

14021423
// --- Empty-merk edge case: an empty Merk returns NoAggregateData
14031424
// for any tree type. This is the correct initial state for a
@@ -1431,6 +1452,10 @@ fn aggregate_consistency_labels(
14311452
Element::ProvableCountSumTree(_, recorded_count, recorded_sum, _),
14321453
AggregateData::NoAggregateData,
14331454
) if *recorded_count == 0 && *recorded_sum == 0 => None,
1455+
(
1456+
Element::ProvableCountProvableSumTree(_, recorded_count, recorded_sum, _),
1457+
AggregateData::NoAggregateData,
1458+
) if *recorded_count == 0 && *recorded_sum == 0 => None,
14341459

14351460
// --- Non-Merk data trees: caller skips us via
14361461
// `uses_non_merk_data_storage`; if we end up here anyway, do not

‎grovedb/src/operations/proof/generate.rs‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1239,6 +1239,12 @@ impl GroveDb {
12391239
.query
12401240
.query
12411241
.has_aggregate_count_on_range_anywhere();
1242+
// Same reasoning for aggregate-sum on the new dual-axis
1243+
// ProvableCountProvableSumTree (and the single-axis
1244+
// ProvableSumTree): an empty merk at the sum-bearing host
1245+
// still has to emit a lower-layer ASOR proof (verifier reads
1246+
// it as sum = 0).
1247+
let is_aggregate_sum_query = path_query.query.query.has_aggregate_sum_on_range_anywhere();
12421248

12431249
let mut merk_proof = cost_return_on_error!(
12441250
&mut cost,
@@ -1620,6 +1626,43 @@ impl GroveDb {
16201626
}
16211627
lower_layers.insert(key.clone(), layer_proof);
16221628
}
1629+
// Same descent path for sum-bearing empty
1630+
// hosts (ProvableSumTree and
1631+
// ProvableCountProvableSumTree) when the
1632+
// outer query has an
1633+
// `AggregateSumOnRange` carrier — recurses
1634+
// into prove_subqueries_v1, hits the ASOR
1635+
// short-circuit on the empty merk, and
1636+
// emits an empty sum proof (verifier reads
1637+
// it as sum = 0).
1638+
Ok(Element::ProvableSumTree(None, ..))
1639+
| Ok(Element::ProvableCountProvableSumTree(None, ..))
1640+
if !done_with_results
1641+
&& is_aggregate_sum_query
1642+
&& query.has_subquery_or_matching_in_path_on_key(key) =>
1643+
{
1644+
let mut lower_path = path.clone();
1645+
lower_path.push(key.as_slice());
1646+
1647+
let previous_limit = *overall_limit;
1648+
1649+
let layer_proof = cost_return_on_error!(
1650+
&mut cost,
1651+
self.prove_subqueries_v1(
1652+
lower_path,
1653+
path_query,
1654+
overall_limit,
1655+
prove_options,
1656+
current_depth + 1,
1657+
grove_version,
1658+
)
1659+
);
1660+
1661+
if previous_limit != *overall_limit {
1662+
has_a_result_at_level |= true;
1663+
}
1664+
lower_layers.insert(key.clone(), layer_proof);
1665+
}
16231666
// Empty trees and CommitmentTree without subquery
16241667
Ok(Element::Tree(None, _))
16251668
| Ok(Element::SumTree(None, ..))

‎grovedb/src/operations/proof/verify.rs‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2598,17 +2598,19 @@ impl GroveDb {
25982598
}
25992599
Node::KVRefValueHash(..)
26002600
| Node::KVRefValueHashCount(..)
2601-
| Node::KVRefValueHashSum(..) => {
2602-
// KVRefValueHash{,Count,Sum} carries an opaque
2601+
| Node::KVRefValueHashSum(..)
2602+
| Node::KVRefValueHashCountSum(..) => {
2603+
// KVRefValueHash{,Count,Sum,CountSum} carries an opaque
26032604
// node_value_hash that cannot be recomputed from the value
26042605
// bytes alone — the hash is `combine_hash(node_value_hash,
26052606
// value_hash(referenced_value))`, and the verifier never
26062607
// gets to see the referenced_value at this layer. Without
26072608
// this rejection, a forged value could ride along in a
2608-
// KVRefValueHashSum trunk/branch node while the merk-level
2609-
// hash chain still appears valid, because the embedded
2610-
// opaque hash is treated as authoritative. These node types
2611-
// should never appear in trunk/branch chunk proofs.
2609+
// KVRefValueHashSum / KVRefValueHashCountSum trunk/branch
2610+
// node while the merk-level hash chain still appears
2611+
// valid, because the embedded opaque hash is treated as
2612+
// authoritative. These node types should never appear in
2613+
// trunk/branch chunk proofs.
26122614
return Err(Error::InvalidProof(
26132615
PathQuery::new_unsized(Vec::new(), Query::default()),
26142616
format!(
@@ -2640,6 +2642,9 @@ impl GroveDb {
26402642
}
26412643
Node::KVCount(_, _, count) => Some(*count),
26422644
Node::KVRefValueHashCount(_, _, _, count) => Some(*count),
2645+
// Dual-axis (PCPS) variants — count lives at the same
2646+
// position as the single-axis count.
2647+
Node::KVCountSum(_, _, count, _) => Some(*count),
26432648
_ => None,
26442649
};
26452650

‎grovedb/src/tests/provable_count_sum_tree_tests.rs‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,12 @@ mod tests {
3131
match node {
3232
Node::KVCount(_, _, count) => Some(*count),
3333
Node::KVDigestCount(_, _, count) => Some(*count),
34+
// Dual-axis PCPS counterparts of the count-only variants
35+
// above. Without these arms, the rotation-stress tests
36+
// silently skip PCPS-host nodes when verifying counts.
37+
Node::KVCountSum(_, _, count, _) => Some(*count),
38+
Node::KVDigestCountSum(_, _, count, _) => Some(*count),
39+
Node::KVRefValueHashCountSum(_, _, _, count, _) => Some(*count),
3440
Node::KVValueHashFeatureType(
3541
_,
3642
_,
@@ -57,6 +63,19 @@ mod tests {
5763
TreeFeatureType::ProvableCountedSummedMerkNode(count, _),
5864
_,
5965
) => Some(*count),
66+
Node::KVValueHashFeatureType(
67+
_,
68+
_,
69+
_,
70+
TreeFeatureType::ProvableCountedAndProvableSummedMerkNode(count, _),
71+
)
72+
| Node::KVValueHashFeatureTypeWithChildHash(
73+
_,
74+
_,
75+
_,
76+
TreeFeatureType::ProvableCountedAndProvableSummedMerkNode(count, _),
77+
_,
78+
) => Some(*count),
6079
_ => None,
6180
}
6281
}

‎merk/src/merk/get.rs‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -365,10 +365,11 @@ where
365365
/// merk-level cost is O(log n) in the number of distinct keys, the same
366366
/// as the proof variant.
367367
///
368-
/// The merk's `tree_type` must be one of `ProvableCountTree` or
369-
/// `ProvableCountSumTree`; any other tree type is rejected with
370-
/// `Error::InvalidProofError` before any walking happens. On an empty
371-
/// merk this returns `count = 0`.
368+
/// The merk's `tree_type` must be one of `ProvableCountTree`,
369+
/// `ProvableCountSumTree`, or `ProvableCountProvableSumTree`; any
370+
/// other tree type is rejected with `Error::InvalidProofError`
371+
/// before any walking happens. On an empty merk this returns
372+
/// `count = 0`.
372373
///
373374
/// The returned count is **not** independently verifiable — callers
374375
/// trust the merk's reads. Use `prove_aggregate_count_on_range` +
@@ -412,9 +413,10 @@ where
412413
/// merk-level cost is O(log n) in the number of distinct keys, the
413414
/// same as the proof variant.
414415
///
415-
/// The merk's `tree_type` must be `ProvableSumTree`; any other tree
416-
/// type is rejected with `Error::InvalidProofError` before any
417-
/// walking happens. On an empty merk this returns `sum = 0`.
416+
/// The merk's `tree_type` must be `ProvableSumTree` or
417+
/// `ProvableCountProvableSumTree`; any other tree type is rejected
418+
/// with `Error::InvalidProofError` before any walking happens. On
419+
/// an empty merk this returns `sum = 0`.
418420
///
419421
/// The accumulator carries `i128` end-to-end and narrows to `i64` at
420422
/// the very last step (parallel to the prover and verifier). An

‎merk/src/merk/prove.rs‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -147,10 +147,11 @@ where
147147
/// wrapper at the `Query` level via
148148
/// `Query::validate_aggregate_count_on_range`).
149149
///
150-
/// The merk's `tree_type` must be one of `ProvableCountTree` or
151-
/// `ProvableCountSumTree` (regardless of whether the merk is empty).
152-
/// Any other tree type is rejected with `Error::InvalidProofError`
153-
/// before any walking happens.
150+
/// The merk's `tree_type` must be one of `ProvableCountTree`,
151+
/// `ProvableCountSumTree`, or `ProvableCountProvableSumTree`
152+
/// (regardless of whether the merk is empty). Any other tree type
153+
/// is rejected with `Error::InvalidProofError` before any walking
154+
/// happens.
154155
///
155156
/// On a tree-type-valid but empty Merk this returns
156157
/// `(empty proof, count = 0)` — an empty subtree is a valid input for a
@@ -191,9 +192,10 @@ where
191192
/// Mirror of [`Self::prove_aggregate_count_on_range`] for the
192193
/// `ProvableSumTree` flavor.
193194
///
194-
/// The merk's `tree_type` must be `ProvableSumTree`; any other tree type
195-
/// is rejected with `Error::InvalidProofError` before any walking
196-
/// happens. Empty merk: returns `(empty proof, sum = 0)`.
195+
/// The merk's `tree_type` must be `ProvableSumTree` or
196+
/// `ProvableCountProvableSumTree`; any other tree type is rejected
197+
/// with `Error::InvalidProofError` before any walking happens.
198+
/// Empty merk: returns `(empty proof, sum = 0)`.
197199
pub fn prove_aggregate_sum_on_range(
198200
&self,
199201
inner_range: &QueryItem,

‎merk/src/proofs/query/aggregate_count/emit.rs‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,11 @@ where
103103
let aggregate = match walker.tree().aggregate_data() {
104104
Ok(a) => a,
105105
Err(e) => {
106-
return Err(Error::InvalidProofError(format!("aggregate_data: {}", e)))
106+
// Local prover-side walk over our own merk — if the
107+
// node refuses to surface aggregate_data, that is a
108+
// storage/state corruption, not a peer-supplied
109+
// invalid proof.
110+
return Err(Error::CorruptedData(format!("aggregate_data: {}", e)))
107111
.wrap_with_cost(cost);
108112
}
109113
};
@@ -133,7 +137,11 @@ where
133137
let subtree_sum = match aggregate {
134138
AggregateData::ProvableCountAndProvableSum(_, s) => s,
135139
other => {
136-
return Err(Error::InvalidProofError(format!(
140+
// Prover-side: a host tree declared as
141+
// ProvableCountProvableSumTree must carry a
142+
// ProvableCountAndProvableSum aggregate. Anything
143+
// else is local state corruption.
144+
return Err(Error::CorruptedData(format!(
137145
"expected ProvableCountAndProvableSum for \
138146
ProvableCountProvableSumTree, got {:?}",
139147
other
@@ -178,7 +186,9 @@ where
178186
let node_aggregate = match walker
179187
.tree()
180188
.aggregate_data()
181-
.map_err(|e| Error::InvalidProofError(format!("aggregate_data: {}", e)))
189+
// Local prover-side walk — failure to read aggregate_data is
190+
// local state corruption, not a peer-supplied invalid proof.
191+
.map_err(|e| Error::CorruptedData(format!("aggregate_data: {}", e)))
182192
{
183193
Ok(a) => a,
184194
Err(e) => return Err(e).wrap_with_cost(cost),
@@ -260,7 +270,11 @@ where
260270
let node_sum = match node_aggregate {
261271
AggregateData::ProvableCountAndProvableSum(_, s) => s,
262272
other => {
263-
return Err(Error::InvalidProofError(format!(
273+
// Prover-side invariant: a host tree declared as
274+
// ProvableCountProvableSumTree must carry the dual-axis
275+
// aggregate at every node. Anything else is local
276+
// state corruption.
277+
return Err(Error::CorruptedData(format!(
264278
"expected ProvableCountAndProvableSum for \
265279
ProvableCountProvableSumTree, got {:?}",
266280
other

‎merk/src/proofs/query/aggregate_count/mod.rs‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,17 +62,19 @@ pub(super) fn is_provable_count_bearing(tree_type: TreeType) -> bool {
6262
}
6363

6464
/// Pull the count out of a `ProvableCount` / `ProvableCountAndSum` /
65-
/// `ProvableCountAndProvableSum` aggregate. Returns `Err(InvalidProofError)`
65+
/// `ProvableCountAndProvableSum` aggregate. Returns `Err(CorruptedData)`
6666
/// for any other variant — the entry point has already gated `tree_type`,
6767
/// so reaching the error means the tree's in-memory state disagrees with
68-
/// its declared type.
68+
/// its declared type. This is a local invariant failure on the prover
69+
/// side (we are walking *our own* merk), so `CorruptedData` is the
70+
/// appropriate classification per the repo error-handling convention.
6971
#[cfg(feature = "minimal")]
7072
pub(super) fn provable_count_from_aggregate(data: AggregateData) -> Result<u64, Error> {
7173
match data {
7274
AggregateData::ProvableCount(c) => Ok(c),
7375
AggregateData::ProvableCountAndSum(c, _) => Ok(c),
7476
AggregateData::ProvableCountAndProvableSum(c, _) => Ok(c),
75-
other => Err(Error::InvalidProofError(format!(
77+
other => Err(Error::CorruptedData(format!(
7678
"expected ProvableCount aggregate data on a provable count tree, got {:?}",
7779
other
7880
))),

0 commit comments

Comments
 (0)