diff --git a/grovedb-bulk-append-tree/src/tree/append.rs b/grovedb-bulk-append-tree/src/tree/append.rs index 5b7e56626..a3ca53b5c 100644 --- a/grovedb-bulk-append-tree/src/tree/append.rs +++ b/grovedb-bulk-append-tree/src/tree/append.rs @@ -5,7 +5,10 @@ use grovedb_merkle_mountain_range::{ }; use grovedb_storage::StorageContext; -use super::{capacity_for_height, hash::compute_state_root, AppendResult, BulkAppendTree}; +use super::{ + capacity_for_height, hash::compute_state_root, AppendNoStateRootResult, AppendResult, + BulkAppendTree, +}; use crate::{chunk::serialize_chunk_blob, BulkAppendError}; impl<'db, S: StorageContext<'db>> BulkAppendTree { @@ -20,6 +23,8 @@ impl<'db, S: StorageContext<'db>> BulkAppendTree { total_count: 0, dense_tree, mmr_overlay: Vec::new(), + // Empty tree → empty MMR → zero root. + last_mmr_root: Some([0u8; 32]), }) } @@ -44,28 +49,63 @@ impl<'db, S: StorageContext<'db>> BulkAppendTree { total_count, dense_tree, mmr_overlay: Vec::new(), + // Lazy: the restored MMR may not be readable until an append occurs, + // so don't compute the root here. The first append fills the cache. + last_mmr_root: None, }) } /// Append a value to the tree. /// /// Handles dense tree insert, auto-compaction when the buffer fills, and - /// state root computation. + /// state root computation. For batched inserts prefer + /// [`append_many`](Self::append_many) or [`append_no_state_root`](Self::append_no_state_root) + /// — they skip the per-leaf state-root blake3 call. pub fn append(&mut self, value: &[u8]) -> Result { + let r = self.append_no_state_root(value)?; + let state_root = self.compute_current_state_root()?; + Ok(AppendResult { + state_root, + global_position: r.global_position, + // +1 for the blake3 state-root computation we just did. + hash_count: r.hash_count.saturating_add(1), + compacted: r.compacted, + }) + } + + /// Append a value without computing the per-leaf state root. + /// + /// Equivalent to [`append`](Self::append) minus the final + /// `compute_state_root` blake3 hash. Use inside a batch (typically via + /// [`append_many`](Self::append_many) or + /// [`CommitmentTree::append_many_raw`]) and recover the state root once at + /// the end via [`compute_current_state_root`](Self::compute_current_state_root). + /// Storage mutation is identical to [`append`](Self::append). + /// + /// [`CommitmentTree::append_many_raw`]: ../../grovedb_commitment_tree/struct.CommitmentTree.html#method.append_many_raw + pub fn append_no_state_root( + &mut self, + value: &[u8], + ) -> Result { let mut hash_count: u32 = 0; let global_position = self.total_count; - // 1. Try to insert into the dense tree buffer + // 1. Try to insert into the dense tree buffer. let try_result = self.dense_tree.try_insert(value).unwrap().map_err(|e| { BulkAppendError::StorageError(format!("dense tree insert failed: {}", e)) })?; - let (compacted, mmr_root, final_dense_root) = match try_result { - Some((dense_root, _position)) => { - // Inserted successfully, no compaction needed + let compacted = match try_result { + Some((_dense_root, _position)) => { + // Inserted successfully, no compaction needed. The MMR is + // untouched, so its root is unchanged — keep the cache as-is. + // (On the very first append after a lazy open the cache is + // `None`; we don't seed it here because we don't need it — + // the caller will recover the state root via + // `compute_current_state_root` at the end of the batch, which + // populates the cache then.) hash_count += self.dense_tree.count() as u32 * 2; - let root = self.get_mmr_root()?; - (false, root, dense_root) + false } None => { // Dense tree is full — compact existing entries + new value. @@ -73,18 +113,15 @@ impl<'db, S: StorageContext<'db>> BulkAppendTree { // self.mmr_size() reflects the pre-compaction state. let (compact_hashes, mmr_root) = self.compact_with_value(value)?; hash_count += compact_hashes; - (true, mmr_root, [0u8; 32]) // empty tree after reset + // MMR mutated by the compaction — refresh the cached root. + self.last_mmr_root = Some(mmr_root); + true } }; self.total_count += 1; - // 2. Compute state root (+1 hash) - let state_root = compute_state_root(&mmr_root, &final_dense_root); - hash_count += 1; - - Ok(AppendResult { - state_root, + Ok(AppendNoStateRootResult { global_position, hash_count, compacted, @@ -92,8 +129,16 @@ impl<'db, S: StorageContext<'db>> BulkAppendTree { } /// Compute the current state root without modifying the tree. + /// + /// Uses the cached MMR root when available, so this is O(1) on the + /// post-first-append fast path (no overlay clone). Falls back to a one-shot + /// `get_mmr_root` only when the cache is empty (e.g. immediately after a + /// lazy `from_state` with no appends yet). pub fn compute_current_state_root(&self) -> Result<[u8; 32], BulkAppendError> { - let mmr_root = self.get_mmr_root()?; + let mmr_root = match self.last_mmr_root { + Some(r) => r, + None => self.get_mmr_root()?, + }; let dense_root = self.dense_tree.root_hash().unwrap().map_err(|e| { BulkAppendError::StorageError(format!("dense tree root_hash failed: {}", e)) })?; diff --git a/grovedb-bulk-append-tree/src/tree/mod.rs b/grovedb-bulk-append-tree/src/tree/mod.rs index 2fe02f8a9..bcea9a521 100644 --- a/grovedb-bulk-append-tree/src/tree/mod.rs +++ b/grovedb-bulk-append-tree/src/tree/mod.rs @@ -40,6 +40,23 @@ pub struct AppendResult { pub compacted: bool, } +/// Result returned by [`BulkAppendTree::append_no_state_root`]. +/// +/// Same as [`AppendResult`] minus the state root, which the caller computes +/// once at the end of a batch via +/// [`BulkAppendTree::compute_current_state_root`]. +#[cfg(feature = "storage")] +#[derive(Debug, Clone, Copy)] +pub struct AppendNoStateRootResult { + /// The 0-based global position of the appended value. + pub global_position: u64, + /// Number of blake3 hash calls performed during this append (excludes the + /// deferred state-root computation). + pub hash_count: u32, + /// Whether compaction (epoch flush) occurred. + pub compacted: bool, +} + /// Compute MMR size from leaf count: `2 * n - popcount(n)`. /// /// This is a well-known MMR property: the total number of nodes (leaves + @@ -75,6 +92,21 @@ pub struct BulkAppendTree { /// lifetimes (compaction cycles) so that reads can find recently-pushed /// nodes without a storage round-trip. pub(crate) mmr_overlay: Vec<(u64, Vec)>, + /// Cached MMR root, refreshed only when a compaction mutates the MMR. + /// + /// The MMR is only touched on compaction (every `epoch_size` appends), so + /// its root is unchanged for the ~`epoch_size - 1` appends in between. + /// Caching it avoids recomputing the root — and cloning the (blob-bearing) + /// `mmr_overlay` — on every append, which would otherwise make bulk + /// appends O(N²) as the overlay grows across compaction cycles. + /// + /// `None` means "not yet known" (the state set by [`from_state`], which must + /// stay lazy: the MMR may not be readable until something is appended). It + /// is computed once on the first append after an open, then kept in sync by + /// compaction. + /// + /// [`from_state`]: BulkAppendTree::from_state + pub(crate) last_mmr_root: Option<[u8; 32]>, } impl BulkAppendTree { diff --git a/grovedb-bulk-append-tree/src/tree/tests.rs b/grovedb-bulk-append-tree/src/tree/tests.rs index 65c5d2c5e..3c3f2e490 100644 --- a/grovedb-bulk-append-tree/src/tree/tests.rs +++ b/grovedb-bulk-append-tree/src/tree/tests.rs @@ -39,6 +39,27 @@ fn from_state_invalid_height() { assert!(BulkAppendTree::from_state(0, 17u8, MemStorageContext::new()).is_err()); } +#[test] +fn cached_mmr_root_matches_recomputation_across_compactions() { + // The append fast-path uses a cached MMR root (`last_mmr_root`) instead of + // recomputing it — and cloning the blob-bearing overlay — on every append. + // This guards that the cache never diverges from a fresh recomputation, + // across both compaction and non-compaction appends. + // + // height=2 → epoch_size=4, so 20 appends span 5 compaction cycles. + let mut tree = BulkAppendTree::new(2u8, MemStorageContext::new()).expect("create tree"); + for i in 0..20u8 { + tree.append(&[i]).expect("append"); + let fresh = tree.get_mmr_root().expect("recompute mmr root"); + assert_eq!( + tree.last_mmr_root, + Some(fresh), + "cached MMR root diverged from recomputation after {} append(s)", + i + 1 + ); + } +} + #[test] fn single_append() { let mut tree = BulkAppendTree::new(2u8, MemStorageContext::new()).expect("create tree"); diff --git a/grovedb-commitment-tree/Cargo.toml b/grovedb-commitment-tree/Cargo.toml index 17f30b65a..2358e59a7 100644 --- a/grovedb-commitment-tree/Cargo.toml +++ b/grovedb-commitment-tree/Cargo.toml @@ -32,7 +32,17 @@ tempfile = { workspace = true } criterion = { workspace = true } rand = { workspace = true } rand_core = "0.6" +# For the `seeding` benchmark: a real RocksDB-backed storage context. +grovedb-storage = { version = "4.0.0", path = "../storage", features = ["rocksdb_storage"] } +grovedb-path = { version = "4.0.0", path = "../path" } [[bench]] name = "verification" harness = false + +# Batched commitment-tree seeding throughput. Run with: +# cargo bench -p grovedb-commitment-tree --bench seeding --features server +[[bench]] +name = "seeding" +harness = false +required-features = ["server"] diff --git a/grovedb-commitment-tree/benches/seeding.rs b/grovedb-commitment-tree/benches/seeding.rs new file mode 100644 index 000000000..a24458c57 --- /dev/null +++ b/grovedb-commitment-tree/benches/seeding.rs @@ -0,0 +1,136 @@ +//! Batched commitment-tree seeding throughput benchmark. +//! +//! Pre-populates a real RocksDB-backed [`CommitmentTree`] with `N` random +//! notes via [`CommitmentTree::append_many_raw`] — the batched API that +//! computes the Sinsemilla anchor and the BulkAppendTree state root once at +//! the end of the batch instead of once per leaf. Byte-for-byte equivalent to +//! `N × CommitmentTree::append_raw`, just without the per-leaf depth-32 +//! Sinsemilla root walk. +//! +//! Run with: +//! ```text +//! cargo bench -p grovedb-commitment-tree --bench seeding --features server +//! ``` +//! +//! The note count defaults to 1,000,000 and can be overridden: +//! ```text +//! SEED_N=200000 cargo bench -p grovedb-commitment-tree --bench seeding --features server +//! ``` + +#[cfg(feature = "server")] +fn main() { + use std::time::Instant; + + use grovedb_commitment_tree::{ + ciphertext_payload_size, merkle_hash_from_bytes, CommitmentTree, DashMemo, + }; + use grovedb_path::SubtreePath; + use grovedb_storage::{rocksdb_storage::RocksDbStorage, Storage, StorageBatch}; + use rand::{rngs::StdRng, Rng, SeedableRng}; + + let n: u64 = std::env::var("SEED_N") + .ok() + .and_then(|s| s.parse().ok()) + .unwrap_or(1_000_000); + // Production value: 2^11 = 2048 notes per completed chunk. + let chunk_power: u8 = 11; + let payload_len = ciphertext_payload_size::(); + let entry_len = 64 + payload_len; // cmx(32) + rho(32) + payload + + // Real on-disk RocksDB in a temp dir. + let tmp = tempfile::TempDir::new().expect("create tempdir"); + let storage = + RocksDbStorage::default_rocksdb_with_path(tmp.path()).expect("open rocksdb storage"); + let tx = storage.start_transaction(); + let batch = StorageBatch::new(); + let ct_path = SubtreePath::from(&[b"shielded_notes" as &[u8]]); + let ctx = storage + .get_transactional_storage_context(ct_path, Some(&batch), &tx) + .value; + let mut ct = + CommitmentTree::<_, DashMemo>::new(chunk_power, ctx).expect("create commitment tree"); + + // Deterministic, lazily-generated note stream — never materialized in full. + // The cmx is rejection-sampled to a valid Pallas field element so the + // batched anchor stays sound (matching what real notes do). + let mut rng = StdRng::seed_from_u64(0xC0FFEE); + let notes = std::iter::from_fn(move || { + let mut cmx = [0u8; 32]; + loop { + rng.fill_bytes(&mut cmx); + if merkle_hash_from_bytes(&cmx).is_some() { + break; + } + } + let mut rho = [0u8; 32]; + let mut payload = vec![0u8; payload_len]; + rng.fill_bytes(&mut rho); + rng.fill_bytes(&mut payload); + Some((cmx, rho, payload)) + }) + .take(n as usize); + + eprintln!( + "Seeding {n} notes via append_many_raw (chunk_power={chunk_power}, payload={payload_len}B, entry={entry_len}B, ~{} MiB of note data)...", + (n as usize * entry_len) / (1024 * 1024) + ); + + // 1. Batched bulk append — compute + in-memory batch accumulation. + // Sinsemilla anchor + bulk state root are each computed exactly once + // at the end, not per leaf. + let t_seed = Instant::now(); + let result = ct + .append_many_raw(notes) + .value + .expect("batched commitment-tree seeding"); + // Flush the MMR overlay into the storage batch now that we're done + // appending. Must come before dropping `ct` (which would lose the overlay) + // and before committing the storage batch (which writes to disk). + ct.commit_mmr().expect("commit_mmr"); + + let seed_elapsed = t_seed.elapsed(); + + // Release the storage context's borrow of the batch before committing. + drop(ct); + + // 2. Flush the batch into the transaction, then commit the transaction to + // disk (the actual RocksDB write). + let t_commit = Instant::now(); + storage + .commit_multi_context_batch(batch, Some(&tx)) + .value + .expect("commit batch into transaction"); + storage + .commit_transaction(tx) + .value + .expect("commit transaction to disk"); + let commit_elapsed = t_commit.elapsed(); + + let total = seed_elapsed + commit_elapsed; + let rate = |d: std::time::Duration| n as f64 / d.as_secs_f64(); + + eprintln!("---------------------------------------------"); + eprintln!("appended : {}", n); + eprintln!("last position : {}", result.global_position); + eprintln!("compacted : {}", result.compacted); + eprintln!( + "seed (compute) : {:.3?} ({:.0} notes/s)", + seed_elapsed, + rate(seed_elapsed) + ); + eprintln!("commit (disk) : {:.3?}", commit_elapsed); + eprintln!( + "TOTAL : {:.3?} ({:.0} notes/s)", + total, + rate(total) + ); + eprintln!("---------------------------------------------"); +} + +#[cfg(not(feature = "server"))] +fn main() { + eprintln!( + "The `seeding` benchmark requires the `server` feature.\n\ + Run: cargo bench -p grovedb-commitment-tree --bench seeding --features server" + ); +} diff --git a/grovedb-commitment-tree/src/commitment_frontier/mod.rs b/grovedb-commitment-tree/src/commitment_frontier/mod.rs index fae356304..2f8a263c3 100644 --- a/grovedb-commitment-tree/src/commitment_frontier/mod.rs +++ b/grovedb-commitment-tree/src/commitment_frontier/mod.rs @@ -43,6 +43,10 @@ impl CommitmentFrontier { /// Returns the new Sinsemilla root hash after the append. The returned /// [`OperationCost`] tracks `sinsemilla_hash_calls`: 32 hashes for the /// leaf-to-root path plus `trailing_ones(position)` ommer hashes. + /// + /// Prefer [`append_no_root`](Self::append_no_root) inside a batch — it + /// skips the per-leaf depth-32 root walk, which dominates the cost of + /// large bulk inserts. pub fn append(&mut self, cmx: [u8; 32]) -> CostResult<[u8; 32], CommitmentTreeError> { let mut cost = OperationCost::default(); let leaf = match merkle_hash_from_bytes(&cmx) { @@ -62,11 +66,49 @@ impl CommitmentFrontier { cost.sinsemilla_hash_calls += 32 + ommer_hashes; if !self.frontier.append(leaf) { + // codecov:ignore — requires 2^32 successful Sinsemilla appends to fill + // the depth-32 tree; never reachable in test or production runs. return Err(CommitmentTreeError::TreeFull).wrap_with_cost(cost); } Ok(self.root_hash()).wrap_with_cost(cost) } + /// Append a commitment without recomputing the root. + /// + /// Cheaper than [`append`](Self::append) for batched inserts: defers the + /// depth-32 Sinsemilla root walk. The caller must call + /// [`root_hash`](Self::root_hash) (or [`anchor`](Self::anchor)) once after + /// the batch to get the post-batch state; intermediate roots are not + /// produced. + /// + /// Cost: amortized ~1 Sinsemilla hash per leaf (the carry chain inside + /// `Frontier::append`) vs ~33 for [`append`](Self::append). + pub fn append_no_root(&mut self, cmx: [u8; 32]) -> CostResult<(), CommitmentTreeError> { + let mut cost = OperationCost::default(); + let leaf = match merkle_hash_from_bytes(&cmx) { + Some(l) => l, + None => { + return Err(CommitmentTreeError::InvalidFieldElement).wrap_with_cost(cost); + } + }; + + // Count only the carry-chain hashes performed by `Frontier::append` + // itself — the depth-32 root walk is *not* done here. + let ommer_hashes = self + .frontier + .value() + .map(|f| u64::from(f.position()).trailing_ones()) + .unwrap_or(0); + cost.sinsemilla_hash_calls += ommer_hashes; + + if !self.frontier.append(leaf) { + // codecov:ignore — requires 2^32 successful Sinsemilla appends to fill + // the depth-32 tree; never reachable in test or production runs. + return Err(CommitmentTreeError::TreeFull).wrap_with_cost(cost); + } + Ok(()).wrap_with_cost(cost) + } + /// Get the current Sinsemilla root hash as 32 bytes. /// /// Returns the empty tree root if no leaves have been appended. @@ -74,6 +116,19 @@ impl CommitmentFrontier { self.frontier.root().to_bytes() } + /// Same as [`root_hash`](Self::root_hash) but attributes the depth-32 + /// Sinsemilla walk to the returned [`OperationCost`]. Used by batched + /// callers (e.g. [`CommitmentTree::append_many_raw`]) so the deferred + /// per-leaf cost is recovered at the single end-of-batch root computation. + /// + /// [`CommitmentTree::append_many_raw`]: crate::CommitmentTree::append_many_raw + pub fn root_hash_with_cost(&self) -> grovedb_costs::CostContext<[u8; 32]> { + let mut cost = OperationCost::default(); + // The Frontier walks `FRONTIER_DEPTH` levels to derive the root. + cost.sinsemilla_hash_calls += FRONTIER_DEPTH as u32; + self.root_hash().wrap_with_cost(cost) + } + /// Get the current root as an Orchard `Anchor`. pub fn anchor(&self) -> Anchor { Anchor::from(self.frontier.root()) diff --git a/grovedb-commitment-tree/src/commitment_tree/mod.rs b/grovedb-commitment-tree/src/commitment_tree/mod.rs index 28b461b66..38473bbcc 100644 --- a/grovedb-commitment-tree/src/commitment_tree/mod.rs +++ b/grovedb-commitment-tree/src/commitment_tree/mod.rs @@ -197,7 +197,8 @@ impl<'db, S: StorageContext<'db>, M: MemoSize> CommitmentTree { // Validate that the frontier and bulk tree agree on the number of // appended items. A mismatch indicates a partial commit or data - // corruption. + // corruption; both [`append_raw`] and [`append_many_raw`] keep the two + // in sync. let frontier_size = frontier.tree_size(); if frontier_size != total_count { return Err(CommitmentTreeError::InvalidData(format!( @@ -322,6 +323,180 @@ impl<'db, S: StorageContext<'db>, M: MemoSize> CommitmentTree { .wrap_with_cost(cost) } + /// Batch-append a sequence of `(cmx, rho, payload)` entries. + /// + /// Byte-for-byte equivalent to calling [`append_raw`](Self::append_raw) + /// once per entry — same dense-buffer state, same chunk MMR, same + /// `CommitmentFrontier` serialization, same final `bulk_state_root` and + /// `sinsemilla_root` — but computes the Sinsemilla anchor and the + /// BulkAppendTree state root **exactly once at the end** instead of once + /// per leaf. + /// + /// # Why batch + /// + /// Per-leaf [`append_raw`](Self::append_raw) walks the full depth-32 + /// Sinsemilla path to derive a fresh anchor on every call — ~32 + /// Sinsemilla hashes per leaf, ~33× the actual carry-chain work the + /// upstream `Frontier::append` performs internally. For 1M leaves that + /// dominates everything. Batching defers the depth walk to one final + /// `root_hash` call. + /// + /// # Returns + /// + /// A [`CommitmentAppendResult`] shaped like what the **final** per-leaf + /// [`append_raw`](Self::append_raw) would have returned: `sinsemilla_root` + /// and `bulk_state_root` are the post-batch values; `global_position` is + /// the position of the last appended entry; `hash_count` is the sum across + /// the batch (including the one final state-root blake3); `compacted` is + /// `true` if any compaction occurred during the batch. + /// + /// # Atomicity + /// + /// On error (e.g. invalid cmx or payload size in the middle of the input) + /// any entries already processed remain in the tree — discard the + /// surrounding transaction if you need all-or-nothing semantics. This + /// matches the per-leaf behavior of calling [`append_raw`](Self::append_raw) + /// in a loop. + /// + /// # Persistence — caller responsibilities + /// + /// Like [`append_raw`](Self::append_raw), this method does **not** flush + /// state to disk on its own. After your final batch — i.e. just before + /// committing the surrounding `StorageBatch` / transaction — the caller + /// **must** call: + /// + /// 1. [`commit_mmr`](Self::commit_mmr) to write MMR nodes staged in the + /// overlay during compactions, and + /// 2. [`save`](Self::save) to persist the Sinsemilla frontier. + /// + /// **Do not call [`commit_mmr`](Self::commit_mmr) between chained + /// `append_many_raw` calls.** A GroveDB `StorageContext::get` does not see + /// writes that are sitting in its `StorageBatch` (reads go straight to the + /// underlying transaction). Flushing the overlay mid-session would put the + /// MMR peaks into the batch, where the *next* batch's compactions can't + /// read them, and the second batch would then fail with `InconsistentStore`. + /// Keeping the overlay alive across chained calls is what lets later + /// compactions resolve their sibling reads in memory. + pub fn append_many_raw( + &mut self, + entries: I, + ) -> CostResult + where + I: IntoIterator)>, + { + let mut cost = OperationCost::default(); + let expected_payload = ciphertext_payload_size::(); + + let mut appended: u64 = 0; + let mut hash_count: u32 = 0; + let mut any_compacted = false; + // Track the last appended position. If the input is empty we fall back + // to the tree's current top of range (or 0 if empty) — the byte-for-byte + // contract only governs frontier+bulk state, not this field for N=0. + let starting_total = self.bulk_tree.total_count; + let mut last_global_position: u64 = starting_total.saturating_sub(1); + + for (cmx, rho, payload) in entries { + // Pre-validate cmx (Pallas field element) and payload size *before* + // any mutation for this entry — mirrors append_raw's ordering so a + // bad entry doesn't leave a half-written row behind. + if crate::commitment_frontier::merkle_hash_from_bytes(&cmx).is_none() { + return Err(CommitmentTreeError::InvalidFieldElement).wrap_with_cost(cost); + } + if payload.len() != expected_payload { + return Err(CommitmentTreeError::InvalidPayloadSize { + expected: expected_payload, + actual: payload.len(), + }) + .wrap_with_cost(cost); + } + + // 1. Build cmx||rho||payload and append to BulkAppendTree, deferring + // the per-leaf state_root blake3. + let mut item_value = Vec::with_capacity(64 + payload.len()); + item_value.extend_from_slice(&cmx); + item_value.extend_from_slice(&rho); + item_value.extend_from_slice(&payload); + + let r = match self.bulk_tree.append_no_state_root(&item_value) { + Ok(r) => r, + // codecov:ignore — only reachable on a storage fault during the + // dense-tree insert or MMR compaction (see `append_raw`'s + // sibling branch for the full rationale). + Err(e) => { + return Err(CommitmentTreeError::InvalidData(format!( + "bulk append: {}", + e + ))) + .wrap_with_cost(cost); + } + }; + hash_count = hash_count.saturating_add(r.hash_count); + if r.compacted { + any_compacted = true; + } + last_global_position = r.global_position; + + // 2. Append cmx to the Sinsemilla frontier, deferring the depth-32 + // root walk. Validation here is now redundant with the pre-check + // above but is cheap and keeps the cost accounting correct. + if let Err(e) = self.frontier.append_no_root(cmx).unwrap_add_cost(&mut cost) { + // codecov:ignore — `append_no_root` can only error on + // `InvalidFieldElement` (already filtered by the pre-validation + // above) or `TreeFull` (2^32 leaves, unreachable). + return Err(e).wrap_with_cost(cost); + } + + appended += 1; + } + + // End-of-batch: pay the deferred costs **once**. + // * `compute_current_state_root` runs one blake3 (matching the +1 each + // per-leaf `append` would have added). + // * `root_hash_with_cost` runs the depth-32 Sinsemilla walk and + // attributes its sinsemilla_hash_calls to `cost`. + let bulk_state_root = match self.bulk_tree.compute_current_state_root() { + Ok(r) => r, + // codecov:ignore — reachable only when an upstream storage read + // fails for the dense-tree root or the cached MMR root. The + // dense-tree write-through cache and the in-session MMR cache + // mean a fault-injecting mock can't hit this from inside + // `append_many_raw` without a separately-opened (cache-cold) tree + // — out of scope for this unit-test fixture. + Err(e) => { + return Err(CommitmentTreeError::InvalidData(format!( + "state root: {}", + e + ))) + .wrap_with_cost(cost); + } + }; + if appended > 0 { + hash_count = hash_count.saturating_add(1); + } + + let root_ctx = self.frontier.root_hash_with_cost(); + cost += root_ctx.cost; + let sinsemilla_root = root_ctx.value; + + // Intentionally do NOT call `commit_mmr` here. Any nodes staged in the + // MMR overlay during compactions must stay in memory until the caller + // finishes the whole session — see the "Persistence" section in the + // method docs. Flushing here would put the peaks into the surrounding + // `StorageBatch`, where the next chained `append_many_raw` would be + // unable to read them (GroveDB `get` does not see batched writes), and + // the next compaction would fail with `InconsistentStore`. + + Ok(CommitmentAppendResult { + sinsemilla_root, + bulk_state_root, + global_position: last_global_position, + hash_count, + compacted: any_compacted, + }) + .wrap_with_cost(cost) + } + /// Persist the current frontier state to storage. pub fn save(&self) -> CostResult<(), CommitmentTreeError> { let mut cost = OperationCost::default(); diff --git a/grovedb-commitment-tree/src/commitment_tree/tests.rs b/grovedb-commitment-tree/src/commitment_tree/tests.rs index 1b6442bbc..9de47c016 100644 --- a/grovedb-commitment-tree/src/commitment_tree/tests.rs +++ b/grovedb-commitment-tree/src/commitment_tree/tests.rs @@ -22,12 +22,19 @@ mod storage_tests { /// since `CommitmentTree` only uses data storage operations. struct MockDataStorageContext { data: std::cell::RefCell, Vec>>, + /// Toggle-able fault flags. Shared via `Rc` so a test can grab a handle + /// before the context is moved into `CommitmentTree`, then flip the + /// flag mid-test to exercise storage-error branches. + fail_get: std::rc::Rc>, + fail_put: std::rc::Rc>, } impl MockDataStorageContext { fn new() -> Self { Self { data: std::cell::RefCell::new(BTreeMap::new()), + fail_get: Default::default(), + fail_put: Default::default(), } } @@ -37,8 +44,21 @@ mod storage_tests { data.insert(key.to_vec(), value); Self { data: std::cell::RefCell::new(data), + fail_get: Default::default(), + fail_put: Default::default(), } } + + /// Clone the (fail_get, fail_put) toggles so a test can flip them + /// after the context has been moved into a `CommitmentTree`. + fn fault_handles( + &self, + ) -> ( + std::rc::Rc>, + std::rc::Rc>, + ) { + (self.fail_get.clone(), self.fail_put.clone()) + } } struct StubBatch; @@ -163,6 +183,15 @@ mod storage_tests { _children_sizes: ChildrenSizesWithIsSumTree, _cost_info: Option, ) -> CostResult<(), grovedb_storage::Error> { + if self.fail_put.get() { + return Err(grovedb_storage::Error::StorageError( + "injected put failure".to_string(), + )) + .wrap_with_cost(OperationCost { + seek_count: 1, + ..Default::default() + }); + } self.data .borrow_mut() .insert(key.as_ref().to_vec(), value.to_vec()); @@ -176,6 +205,15 @@ mod storage_tests { &self, key: K, ) -> CostResult>, grovedb_storage::Error> { + if self.fail_get.get() { + return Err(grovedb_storage::Error::StorageError( + "injected get failure".to_string(), + )) + .wrap_with_cost(OperationCost { + seek_count: 1, + ..Default::default() + }); + } let store = self.data.borrow(); let val = store.get(key.as_ref()).cloned(); let loaded = val.as_ref().map_or(0, |v| v.len() as u64); @@ -1021,4 +1059,361 @@ mod storage_tests { "tree should not have been mutated by invalid cmx" ); } + + // ── Batched append (append_many_raw) ──────────────────────────────── + + /// A correctly-sized DashMemo payload filled with a deterministic pattern. + fn seed_payload(index: u8) -> Vec { + let mut p = vec![0u8; ciphertext_payload_size::()]; + p[0] = index; + p[1] = 0x5D; + p + } + + /// Build a fresh tree, append all `entries` one-by-one via [`append_raw`]. + fn build_via_per_leaf_append( + entries: &[([u8; 32], [u8; 32], Vec)], + ) -> CommitmentTree { + let mut ct = + CommitmentTree::<_, DashMemo>::new(TEST_CHUNK_POWER, MockDataStorageContext::new()) + .expect("new should succeed"); + for (cmx, rho, payload) in entries { + ct.append_raw(*cmx, *rho, payload) + .value + .expect("per-leaf append_raw should succeed"); + } + ct + } + + /// Build a fresh tree by passing all `entries` to [`append_many_raw`] in one call. + fn build_via_append_many_raw( + entries: Vec<([u8; 32], [u8; 32], Vec)>, + ) -> CommitmentTree { + let mut ct = + CommitmentTree::<_, DashMemo>::new(TEST_CHUNK_POWER, MockDataStorageContext::new()) + .expect("new should succeed"); + ct.append_many_raw(entries) + .value + .expect("append_many_raw should succeed"); + ct + } + + /// Build a deterministic test sequence of `n` entries. + fn make_entries(n: u64) -> Vec<([u8; 32], [u8; 32], Vec)> { + (0..n) + .map(|i| { + ( + test_leaf(i), + test_rho((i % 256) as u8), + seed_payload((i % 256) as u8), + ) + }) + .collect() + } + + /// Byte-for-byte equivalence: for the same input sequence, `append_many_raw` + /// must produce the same `CommitmentFrontier` state and the same + /// BulkAppendTree state root as N × `append_raw`. This is the core + /// invariant — if it ever fails, batched callers can produce anchors that + /// don't match what the per-leaf path would have produced. + #[test] + fn append_many_raw_byte_for_byte_matches_per_leaf() { + // 0 / 1 / 2 / 3 cover edge cases around the very-empty and pre-compaction + // shapes; 100 spans the buffer mid-range; 2048 fills exactly one epoch + // (with TEST_CHUNK_POWER=1 we hit MANY compactions, exercising the cache + // + MMR path); 10_000 spans several epochs at meaningful scale. + for n in [0u64, 1, 2, 3, 100, 2048, 10_000] { + let entries = make_entries(n); + let a = build_via_per_leaf_append(&entries); + let b = build_via_append_many_raw(entries); + + assert_eq!( + a.root_hash(), + b.root_hash(), + "Sinsemilla root mismatch at N={}: per-leaf vs append_many_raw", + n + ); + assert_eq!( + a.frontier.serialize(), + b.frontier.serialize(), + "frontier serialization mismatch at N={}: per-leaf vs append_many_raw", + n + ); + let a_state = a.compute_current_state_root().expect("state root A"); + let b_state = b.compute_current_state_root().expect("state root B"); + assert_eq!( + a_state, b_state, + "bulk tree state_root mismatch at N={}: per-leaf vs append_many_raw", + n + ); + assert_eq!( + a.total_count(), + b.total_count(), + "total_count mismatch at N={}: per-leaf vs append_many_raw", + n + ); + assert_eq!(a.total_count(), n, "tree should hold exactly N={} items", n); + } + } + + /// `CommitmentFrontier::append_no_root` is just the carry-chain part of the + /// upstream `Frontier::append`. Its [`OperationCost`] must therefore omit + /// the depth-32 root walk that the eager [`append`] would have counted. + /// + /// Pairing N × `append_no_root` with a single `root_hash_with_cost` recovers + /// the depth walk *once*, exactly as the batched API does in production — + /// so this is also the structural check that justifies the speedup. + #[test] + fn append_no_root_cost_omits_per_leaf_depth_walk() { + // We use a small N here to keep the test fast — the relationship is + // independent of N. + const N: u64 = 16; + + let mut frontier_eager = CommitmentFrontier::new(); + let mut frontier_lazy = CommitmentFrontier::new(); + let mut eager_cost = OperationCost::default(); + let mut lazy_cost = OperationCost::default(); + + for i in 0..N { + let cmx = test_leaf(i); + frontier_eager + .append(cmx) + .unwrap_add_cost(&mut eager_cost) + .expect("eager append"); + frontier_lazy + .append_no_root(cmx) + .unwrap_add_cost(&mut lazy_cost) + .expect("lazy append"); + } + + // Both paths must produce identical frontier state. + assert_eq!(frontier_eager.root_hash(), frontier_lazy.root_hash()); + assert_eq!(frontier_eager.serialize(), frontier_lazy.serialize()); + + // The eager path counts 32 Sinsemilla hashes per call for the depth + // walk; the lazy path counts only the carry chain. Difference is + // exactly 32 × N. + assert_eq!( + eager_cost.sinsemilla_hash_calls - lazy_cost.sinsemilla_hash_calls, + 32 * N as u32, + "eager append must include 32 depth-walk hashes per leaf; lazy must not" + ); + + // Recover the depth walk *once* via root_hash_with_cost. The lazy + // path then matches the eager path minus the deferred walks + // (32 × (N − 1)). + let root_ctx = frontier_lazy.root_hash_with_cost(); + let lazy_total = lazy_cost.sinsemilla_hash_calls + root_ctx.cost.sinsemilla_hash_calls; + assert_eq!( + eager_cost.sinsemilla_hash_calls, + lazy_total + 32 * (N as u32 - 1), + "N × append == N × append_no_root + 1 × root_hash + 32 × (N − 1)" + ); + + // Sanity: lazy carry-chain cost is bounded by N (much less than 32 × N). + assert!( + lazy_cost.sinsemilla_hash_calls < N as u32, + "carry-chain cost should be amortized ~O(1) per leaf, not 32" + ); + } + + /// The Sinsemilla anchor produced by `append_many_raw` must be **spend- + /// usable** — i.e. an Orchard Merkle auth path for a leaf at a known + /// position must verify against the batched-built anchor, exactly as it + /// would against an anchor built leaf-by-leaf. + /// + /// We compute the auth path independently (pairwise Sinsemilla combine to + /// the root, padding upper levels with `empty_root`), then use the orchard + /// `MerklePath` API to derive an anchor from `(position, path, cmx)` and + /// require equality with `ct.anchor()`. + #[test] + fn append_many_raw_anchor_is_spend_usable() { + use crate::{ExtractedNoteCommitment, MerkleHashOrchard, MerklePath}; + + // Modest N keeps the manual auth-path recomputation cheap; the + // verification property is N-agnostic, so a smaller N proves the + // anchor shape. + const N: u64 = 257; + const TARGET_POSITION: usize = 113; + + let entries = make_entries(N); + let owned_cmx_bytes = entries[TARGET_POSITION].0; + let ct = build_via_append_many_raw(entries.clone()); + let anchor = ct.anchor(); + + // Independent auth-path recomputation over the same leaf set. + let leaves: Vec = entries + .iter() + .map(|(cmx, _, _)| { + Option::from(MerkleHashOrchard::from_bytes(cmx)) + .expect("test_leaf produces valid Pallas elements") + }) + .collect(); + + let auth_path = compute_orchard_auth_path(&leaves, TARGET_POSITION); + let target_cmx = Option::::from( + ExtractedNoteCommitment::from_bytes(&owned_cmx_bytes), + ) + .expect("test_leaf produces valid Pallas elements"); + + let merkle_path = MerklePath::from_parts(TARGET_POSITION as u32, auth_path); + let computed = merkle_path.root(target_cmx); + + assert_eq!( + computed, anchor, + "auth path against batched anchor failed — anchor is not spend-usable" + ); + } + + /// Build the Orchard Sinsemilla auth path for `position` over `leaves`, + /// padding upper levels with `MerkleHashOrchard::empty_root(level)` once + /// the tree thins beyond the leaf set. + fn compute_orchard_auth_path( + leaves: &[crate::MerkleHashOrchard], + position: usize, + ) -> [crate::MerkleHashOrchard; 32] { + use crate::{Hashable, Level, MerkleHashOrchard}; + + let mut current: Vec = leaves.to_vec(); + let mut path: Vec = Vec::with_capacity(32); + let mut idx = position; + + for level in 0..32u8 { + let l = Level::from(level); + let empty = MerkleHashOrchard::empty_root(l); + + let sibling_idx = idx ^ 1; + let sibling = current.get(sibling_idx).copied().unwrap_or(empty); + path.push(sibling); + + // Combine pairs up to the next level. Pad with `empty` so the + // upper-level positions align with `idx /= 2` regardless of how + // many leaves there are. + let next_len = current.len().div_ceil(2); + let mut next: Vec = Vec::with_capacity(next_len); + let mut i = 0; + while i < current.len() { + let left = current[i]; + let right = current.get(i + 1).copied().unwrap_or(empty); + next.push(MerkleHashOrchard::combine(l, &left, &right)); + i += 2; + } + current = next; + idx /= 2; + } + + path.try_into() + .expect("32 levels of auth path produced from the loop above") + } + + // ── append_many_raw error-branch coverage ─────────────────────────── + + /// Mid-batch invalid cmx must be rejected via the per-entry pre-validation. + #[test] + fn append_many_raw_rejects_invalid_cmx_mid_batch() { + let ctx = MockDataStorageContext::new(); + let mut ct = + CommitmentTree::<_, DashMemo>::new(TEST_CHUNK_POWER, ctx).expect("new should succeed"); + + // First entry is valid; second has a non-Pallas cmx. The first must be + // accepted, then the batch errors with `InvalidFieldElement` — matching + // the per-leaf `append_raw` semantics. + let entries = vec![ + (test_leaf(0), test_rho(0), seed_payload(0)), + ([0xFFu8; 32], test_rho(1), seed_payload(1)), + ]; + let err = ct + .append_many_raw(entries) + .value + .expect_err("invalid cmx must propagate out of the batch"); + assert!( + matches!(err, CommitmentTreeError::InvalidFieldElement), + "expected InvalidFieldElement, got {err}" + ); + // The first (valid) entry was already applied. + assert_eq!(ct.total_count(), 1, "valid prefix entry was applied"); + } + + /// Mid-batch wrong-sized payload must be rejected via the per-entry + /// pre-validation. + #[test] + fn append_many_raw_rejects_wrong_payload_size_mid_batch() { + let ctx = MockDataStorageContext::new(); + let mut ct = + CommitmentTree::<_, DashMemo>::new(TEST_CHUNK_POWER, ctx).expect("new should succeed"); + + let entries = vec![ + (test_leaf(0), test_rho(0), seed_payload(0)), + (test_leaf(1), test_rho(1), vec![0u8; 1]), // wrong size + ]; + let err = ct + .append_many_raw(entries) + .value + .expect_err("bad payload size must propagate out of the batch"); + assert!( + matches!(err, CommitmentTreeError::InvalidPayloadSize { .. }), + "expected InvalidPayloadSize, got {err}" + ); + } + + /// A storage fault during the bulk-tree side of `append_many_raw` must + /// surface as the wrapped `InvalidData("bulk append: …")` error. + #[test] + fn append_many_raw_surfaces_bulk_storage_error() { + let ctx = MockDataStorageContext::new(); + let (fail_get, fail_put) = ctx.fault_handles(); + let mut ct = + CommitmentTree::<_, DashMemo>::new(TEST_CHUNK_POWER, ctx).expect("new should succeed"); + + // Make the underlying dense-tree storage fail on both reads and writes + // so `BulkAppendTree::append_no_state_root` errors out. + fail_get.set(true); + fail_put.set(true); + + let entries = vec![(test_leaf(0), test_rho(0), seed_payload(0))]; + let err = ct + .append_many_raw(entries) + .value + .expect_err("bulk storage failure should surface"); + assert!( + format!("{err}").contains("bulk append"), + "error should be wrapped as a bulk-append failure: {err}" + ); + } + + /// `CommitmentFrontier::append_no_root` must reject a non-Pallas cmx with + /// `InvalidFieldElement` (mirrors the eager `append` behavior). + #[test] + fn frontier_append_no_root_rejects_invalid_cmx() { + let mut f = CommitmentFrontier::new(); + let err = f + .append_no_root([0xFFu8; 32]) + .value + .expect_err("a non-Pallas cmx must be rejected before any frontier mutation"); + assert!( + matches!(err, CommitmentTreeError::InvalidFieldElement), + "expected InvalidFieldElement, got {err}" + ); + assert_eq!( + f.tree_size(), + 0, + "frontier must not have been mutated by the rejection" + ); + } + + /// `CommitmentTree::commit_mmr` must run the underlying bulk-tree commit + /// to completion (success path). + #[test] + fn commit_mmr_success() { + let ctx = MockDataStorageContext::new(); + let mut ct = + CommitmentTree::<_, DashMemo>::new(TEST_CHUNK_POWER, ctx).expect("new should succeed"); + + // Append enough to trigger at least one compaction (TEST_CHUNK_POWER=1 + // → epoch_size=2), so the MMR overlay has staged nodes. + let notes = (0..4u8).map(|i| (test_leaf(i as u64), test_rho(i), seed_payload(i))); + ct.append_many_raw(notes).value.expect("warmup"); + + ct.commit_mmr().expect("commit_mmr should flush cleanly"); + } }