1mod branch_child_idx;
2mod cursor;
3mod nodes;
4
5use branch_child_idx::{BranchChildIdx, BranchChildIter};
6use cursor::{ArenaCursor, NextResult, SeekResult};
7use nodes::{
8 ArenaSparseNode, ArenaSparseNodeBranch, ArenaSparseNodeBranchChild, ArenaSparseNodeState,
9};
10
11use crate::{
12 LeafLookup, LeafLookupError, LeafUpdate, SparseTrie, SparseTrieUpdates, TrieNodeEpoch,
13};
14use alloc::{boxed::Box, collections::VecDeque, vec::Vec};
15use alloy_primitives::{keccak256, map::B256Map, B256};
16use alloy_trie::TrieMask;
17use core::{cmp::Reverse, mem};
18use reth_execution_errors::SparseTrieResult;
19use reth_trie_common::{
20 BranchNodeMasks, BranchNodeRef, ExtensionNodeRef, LeafNodeRef, Nibbles, ProofTrieNodeV2,
21 ProofV2TargetParent, RlpNode, TrieNodeV2, EMPTY_ROOT_HASH,
22};
23use slotmap::{DefaultKey, SlotMap};
24use smallvec::SmallVec;
25use tracing::{instrument, trace};
26
27type Index = DefaultKey;
29type NodeArena = SlotMap<Index, ArenaSparseNode>;
31
32const TRACE_TARGET: &str = "trie::arena";
33
34const UPPER_TRIE_MAX_DEPTH: usize = 2;
37
38fn compact_arena(arena: &mut NodeArena, root: &mut Index) {
42 let mut new_arena = SlotMap::with_capacity(arena.len());
43 let mut queue = VecDeque::new();
44
45 let root_node = arena.remove(*root).expect("root exists");
46 let new_root = new_arena.insert(root_node);
47 queue.push_back(new_root);
48
49 while let Some(new_idx) = queue.pop_front() {
50 let old_children: SmallVec<[(usize, Index); 16]> = match &new_arena[new_idx] {
55 ArenaSparseNode::Branch(b) => b
56 .children
57 .iter()
58 .enumerate()
59 .filter_map(|(i, c)| match c {
60 ArenaSparseNodeBranchChild::Revealed(old_idx) => Some((i, *old_idx)),
61 _ => None,
62 })
63 .collect(),
64 _ => continue,
65 };
66
67 for (child_pos, old_child_idx) in old_children {
68 let child_node = arena.remove(old_child_idx).expect("child exists");
69 let new_child_idx = new_arena.insert(child_node);
70 let ArenaSparseNode::Branch(b) = &mut new_arena[new_idx] else { unreachable!() };
71 b.children[child_pos] = ArenaSparseNodeBranchChild::Revealed(new_child_idx);
72 queue.push_back(new_child_idx);
73 }
74 }
75
76 debug_assert!(
77 arena.is_empty(),
78 "compact_arena: {} orphaned nodes remaining after BFS drain",
79 arena.len(),
80 );
81
82 *arena = new_arena;
83 *root = new_root;
84}
85
86#[derive(Debug, Default, Clone)]
89struct ArenaTrieBuffers {
90 cursor: ArenaCursor,
92 updates: Option<SparseTrieUpdates>,
95 rlp_buf: Vec<u8>,
97 rlp_node_buf: Vec<RlpNode>,
99}
100
101impl ArenaTrieBuffers {
102 fn clear(&mut self) {
103 if let Some(updates) = self.updates.as_mut() {
104 updates.clear();
105 }
106 self.rlp_buf.clear();
107 self.rlp_node_buf.clear();
108 }
109}
110
111#[derive(Debug, Clone)]
115struct ArenaSparseSubtrie {
116 arena: NodeArena,
118 root: Index,
120 path: Nibbles,
122 buffers: ArenaTrieBuffers,
124 required_proofs: Vec<(usize, ArenaRequiredProof)>,
128 num_leaves: u64,
130 num_dirty_leaves: u64,
132}
133
134impl ArenaSparseSubtrie {
135 fn new(record_updates: bool) -> Box<Self> {
139 let mut arena = SlotMap::new();
140 let root =
141 arena.insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Revealed });
142 let buffers = ArenaTrieBuffers {
143 updates: record_updates.then(SparseTrieUpdates::default),
144 ..Default::default()
145 };
146 Box::new(Self {
147 arena,
148 root,
149 path: Nibbles::default(),
150 buffers,
151 required_proofs: Vec::new(),
152 num_leaves: 0,
153 num_dirty_leaves: 0,
154 })
155 }
156
157 #[cfg(debug_assertions)]
159 fn debug_assert_counters(&self) {
160 let (actual_leaves, actual_dirty) =
161 ArenaParallelSparseTrie::count_leaves_and_dirty(&self.arena, self.root);
162 debug_assert_eq!(
163 self.num_leaves, actual_leaves,
164 "subtrie {:?} num_leaves mismatch: stored {} vs actual {}",
165 self.path, self.num_leaves, actual_leaves,
166 );
167 debug_assert_eq!(
168 self.num_dirty_leaves, actual_dirty,
169 "subtrie {:?} num_dirty_leaves mismatch: stored {} vs actual {}",
170 self.path, self.num_dirty_leaves, actual_dirty,
171 );
172 }
173
174 fn prune(&mut self, prune_before: TrieNodeEpoch) -> usize {
179 if !matches!(&self.arena[self.root], ArenaSparseNode::Branch(_)) {
181 return 0;
182 }
183
184 debug_assert_eq!(self.num_dirty_leaves, 0, "prune must run after hashing");
185
186 if prune_before == TrieNodeEpoch::UNMODIFIED {
187 return 0;
188 }
189
190 let old_count = self.arena.len();
191 let mut new_arena = SlotMap::new();
193 let mut new_num_leaves = 0u64;
194
195 let root_node = self.arena.remove(self.root).expect("root exists");
197 let new_root = new_arena.insert(root_node);
198 let mut stack = Vec::new();
199 if let Some(frame) =
200 prepare_retained_node(&new_arena, new_root, self.path, &mut new_num_leaves)
201 {
202 stack.push(frame);
203 }
204
205 while let Some(frame) = stack.last_mut() {
206 let Some((child_pos, nibble, old_child_idx)) = frame.next_revealed_child(&new_arena)
207 else {
208 stack.pop();
209 continue;
210 };
211
212 let parent_new_idx = frame.new_idx;
213 let mut child_path = frame.branch_logical_path;
214 child_path.push(nibble);
215
216 let child_epoch = self.arena[old_child_idx]
217 .state_ref()
218 .and_then(ArenaSparseNodeState::cached_epoch)
219 .expect("prune must run after hashing");
220
221 if child_epoch.should_prune(prune_before) {
222 let node = &self.arena[old_child_idx];
223 let rlp_node = node
224 .state_ref()
225 .and_then(ArenaSparseNodeState::cached_rlp_node)
226 .cloned()
227 .expect("prune must run after hashing");
228 trace!(
229 target: TRACE_TARGET,
230 path = ?child_path,
231 variant = %AsRef::<str>::as_ref(node),
232 cached_rlp_node = ?rlp_node,
233 "pruning node",
234 );
235 let ArenaSparseNode::Branch(b) = &mut new_arena[parent_new_idx] else {
236 unreachable!()
237 };
238 b.children[child_pos] = ArenaSparseNodeBranchChild::Blinded(rlp_node);
239 } else {
240 let child_node = self.arena.remove(old_child_idx).expect("child exists");
241 let new_child_idx = new_arena.insert(child_node);
242 if let Some(frame) = prepare_retained_node(
243 &new_arena,
244 new_child_idx,
245 child_path,
246 &mut new_num_leaves,
247 ) {
248 stack.push(frame);
249 }
250 let ArenaSparseNode::Branch(b) = &mut new_arena[parent_new_idx] else {
251 unreachable!()
252 };
253 b.children[child_pos] = ArenaSparseNodeBranchChild::Revealed(new_child_idx);
254 }
255 }
256
257 let pruned = old_count - new_arena.len();
258 self.num_leaves = new_num_leaves;
259 self.num_dirty_leaves = 0;
260 self.arena = new_arena;
261 self.root = new_root;
262
263 #[cfg(debug_assertions)]
264 self.debug_assert_counters();
265 return pruned;
266
267 struct CopyFrame {
268 new_idx: Index,
269 branch_logical_path: Nibbles,
270 state_mask: TrieMask,
271 remaining_child_mask: TrieMask,
272 }
273
274 impl CopyFrame {
275 fn next_revealed_child(&mut self, new_arena: &NodeArena) -> Option<(usize, u8, Index)> {
276 let ArenaSparseNode::Branch(b) = &new_arena[self.new_idx] else { unreachable!() };
277
278 loop {
279 let nibble = self.remaining_child_mask.first_set_bit_index()?;
280 self.remaining_child_mask.unset_bit(nibble);
281 let child_idx = BranchChildIdx::new(self.state_mask, nibble)
282 .expect("remaining_child_mask must be a subset of state_mask");
283
284 if let ArenaSparseNodeBranchChild::Revealed(old_idx) = b.children[child_idx] {
285 return Some((child_idx.get(), nibble, old_idx))
286 }
287 }
288 }
289 }
290
291 fn prepare_retained_node(
294 new_arena: &NodeArena,
295 new_idx: Index,
296 node_path: Nibbles,
297 new_num_leaves: &mut u64,
298 ) -> Option<CopyFrame> {
299 let ArenaSparseNode::Branch(b) = &new_arena[new_idx] else {
300 if matches!(&new_arena[new_idx], ArenaSparseNode::Leaf { .. }) {
301 *new_num_leaves += 1;
302 }
303 return None;
304 };
305
306 let mut branch_logical_path = node_path;
307 branch_logical_path.extend(&b.short_key);
308
309 Some(CopyFrame {
310 new_idx,
311 branch_logical_path,
312 state_mask: b.state_mask,
313 remaining_child_mask: b.state_mask,
314 })
315 }
316 }
317
318 #[instrument(
326 level = "trace",
327 target = TRACE_TARGET,
328 skip_all,
329 fields(
330 subtrie = ?self.path,
331 num_updates = sorted_updates.len(),
332 ),
333 )]
334 fn update_leaves(&mut self, sorted_updates: &[(B256, Nibbles, LeafUpdate)]) {
335 if sorted_updates.is_empty() {
336 return;
337 }
338 trace!(target: TRACE_TARGET, "Subtrie update_leaves");
339
340 debug_assert!(
341 !matches!(self.arena[self.root], ArenaSparseNode::EmptyRoot { .. }),
342 "subtrie root must not be EmptyRoot at start of update_leaves"
343 );
344
345 self.buffers.cursor.reset(&self.arena, self.root, self.path);
346
347 for (idx, &(key, ref full_path, ref update)) in sorted_updates.iter().enumerate() {
348 let find_result = self.buffers.cursor.seek(&mut self.arena, full_path);
349
350 if matches!(find_result, SeekResult::Blinded) {
352 let logical_len = self.buffers.cursor.head_logical_branch_path_len(&self.arena);
353 self.required_proofs.push((
354 idx,
355 ArenaRequiredProof { key, parent: ProofV2TargetParent::new(logical_len) },
356 ));
357 continue;
358 }
359
360 match update {
361 LeafUpdate::Changed(value) if !value.is_empty() => {
362 let (_result, deltas) = ArenaParallelSparseTrie::upsert_leaf(
364 &mut self.arena,
365 &mut self.buffers.cursor,
366 &mut self.root,
367 full_path,
368 value,
369 find_result,
370 );
371 self.num_leaves = (self.num_leaves as i64 + deltas.num_leaves_delta) as u64;
372 self.num_dirty_leaves =
373 (self.num_dirty_leaves as i64 + deltas.num_dirty_leaves_delta) as u64;
374 }
375 LeafUpdate::Changed(_) => {
376 let (result, deltas) = ArenaParallelSparseTrie::remove_leaf(
377 &mut self.arena,
378 &mut self.buffers.cursor,
379 &mut self.root,
380 key,
381 full_path,
382 find_result,
383 &mut self.buffers.updates,
384 );
385 self.num_leaves = (self.num_leaves as i64 + deltas.num_leaves_delta) as u64;
386 self.num_dirty_leaves =
387 (self.num_dirty_leaves as i64 + deltas.num_dirty_leaves_delta) as u64;
388
389 if let RemoveLeafResult::NeedsProof { key, proof_key, parent } = result {
390 self.required_proofs
391 .push((idx, ArenaRequiredProof { key: proof_key, parent }));
392 self.required_proofs.push((idx, ArenaRequiredProof { key, parent }));
393 }
394 }
395 LeafUpdate::Touched => {}
396 }
397 }
398
399 self.buffers.cursor.drain(&mut self.arena);
401
402 #[cfg(debug_assertions)]
403 self.debug_assert_counters();
404 }
405
406 fn reveal_nodes(&mut self, nodes: &mut [ProofTrieNodeV2]) -> SparseTrieResult<()> {
409 if nodes.is_empty() {
410 return Ok(());
411 }
412 trace!(target: TRACE_TARGET, path = ?self.path, num_nodes = nodes.len(), "Subtrie reveal_nodes");
413
414 debug_assert!(
415 !matches!(self.arena[self.root], ArenaSparseNode::EmptyRoot { .. }),
416 "subtrie root must not be EmptyRoot in reveal_nodes"
417 );
418
419 self.buffers.cursor.reset(&self.arena, self.root, self.path);
420
421 for node in nodes.iter_mut() {
422 let find_result = self.buffers.cursor.seek(&mut self.arena, &node.path);
423 if ArenaParallelSparseTrie::reveal_node(
424 &mut self.arena,
425 &self.buffers.cursor,
426 node,
427 find_result,
428 )
429 .is_some_and(|child_idx| matches!(self.arena[child_idx], ArenaSparseNode::Leaf { .. }))
430 {
431 self.num_leaves += 1;
432 }
433 }
434
435 self.buffers.cursor.drain(&mut self.arena);
437
438 #[cfg(debug_assertions)]
439 self.debug_assert_counters();
440
441 Ok(())
442 }
443
444 fn update_cached_rlp(&mut self, new_epoch: TrieNodeEpoch) {
449 ArenaParallelSparseTrie::update_cached_rlp(
450 &mut self.arena,
451 self.root,
452 self.path,
453 &mut self.buffers,
454 new_epoch,
455 );
456 self.num_dirty_leaves = 0;
457 #[cfg(debug_assertions)]
458 self.debug_assert_counters();
459 }
460}
461
462#[derive(Debug, Default)]
466struct SubtrieCounterDeltas {
467 num_leaves_delta: i64,
468 num_dirty_leaves_delta: i64,
469}
470
471#[derive(Debug)]
474enum UpsertLeafResult {
475 Updated,
477 NewLeaf,
479 NewChild,
482}
483
484#[derive(Debug)]
487enum RemoveLeafResult {
488 Removed,
490 NotFound,
492 NeedsProof { key: B256, proof_key: B256, parent: ProofV2TargetParent },
495}
496
497#[derive(Debug, Clone)]
499struct ArenaRequiredProof {
500 key: B256,
502 parent: ProofV2TargetParent,
504}
505
506#[derive(Debug, Clone, Copy, PartialEq, Eq)]
511pub struct ArenaParallelismThresholds {
512 pub min_dirty_leaves: u64,
516 pub min_revealed_nodes: usize,
520 pub min_updates: usize,
524 pub min_leaves_for_prune: u64,
528}
529
530impl Default for ArenaParallelismThresholds {
531 fn default() -> Self {
532 Self {
533 min_dirty_leaves: 64,
534 min_revealed_nodes: 16,
535 min_updates: 128,
536 min_leaves_for_prune: 128,
537 }
538 }
539}
540
541#[derive(Debug, Clone)]
598pub struct ArenaParallelSparseTrie {
599 upper_arena: NodeArena,
601 root: Index,
603 buffers: ArenaTrieBuffers,
605 parallelism_thresholds: ArenaParallelismThresholds,
607}
608
609impl ArenaParallelSparseTrie {
610 pub const fn with_parallelism_thresholds(
612 mut self,
613 thresholds: ArenaParallelismThresholds,
614 ) -> Self {
615 self.parallelism_thresholds = thresholds;
616 self
617 }
618
619 const fn should_be_subtrie(path_len: usize) -> bool {
622 path_len == UPPER_TRIE_MAX_DEPTH
623 }
624
625 fn maybe_wrap_in_subtrie(&mut self, child_idx: Index, child_path: &Nibbles) {
630 if !Self::should_be_subtrie(child_path.len()) {
631 return;
632 }
633
634 if !matches!(
636 self.upper_arena[child_idx],
637 ArenaSparseNode::Branch(_) | ArenaSparseNode::Leaf { .. }
638 ) {
639 return;
640 }
641
642 trace!(target: TRACE_TARGET, ?child_path, "Wrapping child into subtrie");
643 let mut subtrie = ArenaSparseSubtrie::new(self.buffers.updates.is_some());
644 subtrie.path = *child_path;
645 let mut root_node =
646 mem::replace(&mut self.upper_arena[child_idx], ArenaSparseNode::TakenSubtrie);
647
648 if let ArenaSparseNode::Branch(b) = &mut root_node {
650 for child in &mut b.children {
651 if let ArenaSparseNodeBranchChild::Revealed(idx) = child {
652 *idx =
653 Self::migrate_nodes(&mut subtrie.arena, &mut self.upper_arena, *idx, None);
654 }
655 }
656 }
657
658 subtrie.arena[subtrie.root] = root_node;
659 let (leaves, dirty) = Self::count_leaves_and_dirty(&subtrie.arena, subtrie.root);
660 subtrie.num_leaves = leaves;
661 subtrie.num_dirty_leaves = dirty;
662 #[cfg(debug_assertions)]
663 subtrie.debug_assert_counters();
664 self.upper_arena[child_idx] = ArenaSparseNode::Subtrie(subtrie);
665 }
666
667 fn maybe_wrap_branch_children(&mut self, cursor: &ArenaCursor) {
672 let head = cursor.head().expect("cursor is non-empty");
673 let head_idx = head.index;
674 let head_path = head.path;
675
676 let ArenaSparseNode::Branch(b) = &self.upper_arena[head_idx] else { return };
677 let short_key = b.short_key;
678 let children: SmallVec<[_; 4]> = b
679 .child_iter()
680 .filter_map(|(nibble, child)| match child {
681 ArenaSparseNodeBranchChild::Revealed(idx) => Some((nibble, *idx)),
682 ArenaSparseNodeBranchChild::Blinded(_) => None,
683 })
684 .collect();
685
686 for (nibble, child_idx) in children {
687 let mut child_path = head_path;
688 child_path.extend(&short_key);
689 child_path.push_unchecked(nibble);
690 self.maybe_wrap_in_subtrie(child_idx, &child_path);
691 }
692 }
693
694 #[instrument(
703 level = "trace",
704 target = TRACE_TARGET,
705 skip_all,
706 fields(subtrie_path = ?cursor.head().expect("cursor is non-empty").path),
707 )]
708 fn maybe_unwrap_subtrie(&mut self, cursor: &mut ArenaCursor) {
709 let subtrie_idx = cursor.head().expect("cursor is non-empty").index;
710
711 let ArenaSparseNode::Subtrie(subtrie) = &self.upper_arena[subtrie_idx] else {
712 return;
713 };
714
715 if !matches!(subtrie.arena[subtrie.root], ArenaSparseNode::EmptyRoot { .. }) {
716 return;
717 }
718
719 let child_nibble = cursor
720 .head()
721 .expect("cursor is non-empty")
722 .path
723 .last()
724 .expect("subtrie path must have at least one nibble");
725 let parent_idx = cursor.parent().expect("cursor has parent").index;
726
727 cursor.pop(&mut self.upper_arena);
730
731 self.recycle_subtrie_from_idx(subtrie_idx);
732
733 trace!(target: TRACE_TARGET, "Unwrapping empty subtrie, removing child slot");
734 let parent_branch = self.upper_arena[parent_idx].branch_mut();
735 let child_idx = BranchChildIdx::new(parent_branch.state_mask, child_nibble)
736 .expect("child nibble not found in parent state_mask");
737
738 parent_branch.children.remove(child_idx.get());
739 parent_branch.unset_child_bit(child_nibble);
740 parent_branch.state = parent_branch.state.to_dirty();
742
743 self.maybe_collapse_or_remove_branch(cursor);
744 }
745
746 fn recycle_subtrie(&mut self, node: ArenaSparseNode) {
752 let ArenaSparseNode::Subtrie(mut subtrie) = node else {
753 unreachable!("recycle_subtrie called on non-Subtrie node")
754 };
755 Self::merge_subtrie_updates(&mut self.buffers.updates, &mut subtrie.buffers.updates);
756 }
757
758 fn recycle_subtrie_from_idx(&mut self, idx: Index) {
760 let node = self.upper_arena.remove(idx).expect("subtrie exists in arena");
761 self.recycle_subtrie(node);
762 }
763
764 fn maybe_collapse_or_remove_branch(&mut self, cursor: &mut ArenaCursor) {
775 loop {
776 let branch_entry = cursor.head().expect("cursor is non-empty");
777 let branch_idx = branch_entry.index;
778 let branch_path = branch_entry.path;
779
780 let count = {
783 let ArenaSparseNode::Branch(b) = &self.upper_arena[branch_idx] else {
784 return;
785 };
786 b.state_mask.count_bits()
787 };
788
789 if count >= 2 {
790 return;
791 }
792
793 if count == 0 {
794 if branch_idx == self.root {
795 self.upper_arena[branch_idx] =
796 ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Dirty };
797 return;
798 }
799 let branch_nibble = branch_path.last().expect("non-root branch");
801 cursor.pop(&mut self.upper_arena);
802 self.upper_arena.remove(branch_idx);
803 let parent_idx = cursor.head().expect("cursor is non-empty").index;
804 let parent_branch = self.upper_arena[parent_idx].branch_mut();
805 let child_idx = BranchChildIdx::new(parent_branch.state_mask, branch_nibble)
806 .expect("child nibble not found in parent state_mask");
807 parent_branch.children.remove(child_idx.get());
808 parent_branch.unset_child_bit(branch_nibble);
809 parent_branch.state = parent_branch.state.to_dirty();
810 continue; }
812
813 let (remaining_nibble, remaining_child_idx) = {
815 let b = self.upper_arena[branch_idx].branch_ref();
816 let nibble = b.state_mask.iter().next().expect("branch has at least one child");
817 let child_idx = match &b.children[0] {
818 ArenaSparseNodeBranchChild::Revealed(idx) => Some(*idx),
819 ArenaSparseNodeBranchChild::Blinded(_) => None,
820 };
821 (nibble, child_idx)
822 };
823
824 let Some(child_idx) = remaining_child_idx else {
825 debug_assert!(false, "single remaining child is blinded — should have been caught by check_subtrie_collapse_needs_proof");
826 return;
827 };
828
829 if matches!(self.upper_arena[child_idx], ArenaSparseNode::TakenSubtrie) {
830 return;
833 }
834
835 let is_empty_subtrie = matches!(
837 &self.upper_arena[child_idx],
838 ArenaSparseNode::Subtrie(s) if matches!(s.arena[s.root], ArenaSparseNode::EmptyRoot { .. })
839 );
840
841 if is_empty_subtrie {
842 self.recycle_subtrie_from_idx(child_idx);
843 let branch = self.upper_arena[branch_idx].branch_mut();
844 branch.children.remove(0);
845 branch.unset_child_bit(remaining_nibble);
846 branch.state = branch.state.to_dirty();
847 continue; }
849
850 Self::collapse_branch(
852 &mut self.upper_arena,
853 cursor,
854 &mut self.root,
855 &mut self.buffers.updates,
856 );
857
858 let child_idx = cursor.head().expect("cursor is non-empty").index;
863 if let ArenaSparseNode::Subtrie(_) = &self.upper_arena[child_idx] {
864 let ArenaSparseNode::Subtrie(mut subtrie) =
865 mem::replace(&mut self.upper_arena[child_idx], ArenaSparseNode::TakenSubtrie)
866 else {
867 unreachable!()
868 };
869 Self::migrate_nodes(
870 &mut self.upper_arena,
871 &mut subtrie.arena,
872 subtrie.root,
873 Some(child_idx),
874 );
875 Self::merge_subtrie_updates(
876 &mut self.buffers.updates,
877 &mut subtrie.buffers.updates,
878 );
879
880 self.maybe_wrap_branch_children(cursor);
884 }
885 return;
886 }
887 }
888
889 fn merge_subtrie_updates(
892 dst: &mut Option<SparseTrieUpdates>,
893 src: &mut Option<SparseTrieUpdates>,
894 ) {
895 if let Some(dst) = dst.as_mut() {
896 dst.append(src.as_mut().expect("updates are enabled"));
897 }
898 }
899
900 fn nibbles_to_padded_b256(path: &Nibbles) -> B256 {
902 let mut bytes = [0u8; 32];
903 path.pack_to(&mut bytes);
904 B256::from(bytes)
905 }
906
907 fn get_branch_masks(arena: &NodeArena, branch: &ArenaSparseNodeBranch) -> BranchNodeMasks {
909 let mut masks = BranchNodeMasks::default();
910
911 for (nibble, child) in branch.child_iter() {
912 let (hash_bit, tree_bit) = match child {
913 ArenaSparseNodeBranchChild::Blinded(_) => (
914 branch.branch_masks.hash_mask.is_bit_set(nibble),
915 branch.branch_masks.tree_mask.is_bit_set(nibble),
916 ),
917 ArenaSparseNodeBranchChild::Revealed(child_idx) => {
918 let child = &arena[*child_idx];
919 (child.hash_mask_bit(), child.tree_mask_bit())
920 }
921 };
922
923 masks.set_child_bits(nibble, hash_bit, tree_bit);
924 }
925
926 masks
927 }
928
929 #[instrument(level = "trace", target = TRACE_TARGET, skip_all, fields(base_path = ?base_path), ret)]
942 fn update_cached_rlp(
943 arena: &mut NodeArena,
944 root: Index,
945 base_path: Nibbles,
946 buffers: &mut ArenaTrieBuffers,
947 new_epoch: TrieNodeEpoch,
948 ) -> RlpNode {
949 let cursor = &mut buffers.cursor;
950 let rlp_buf = &mut buffers.rlp_buf;
951 let rlp_node_buf = &mut buffers.rlp_node_buf;
952 let updates = &mut buffers.updates;
953
954 rlp_node_buf.clear();
955
956 match &arena[root] {
960 ArenaSparseNode::EmptyRoot { state } => {
961 let node_epoch = match state {
962 ArenaSparseNodeState::Cached { epoch, .. } => *epoch,
963 ArenaSparseNodeState::Revealed => TrieNodeEpoch::UNMODIFIED,
964 ArenaSparseNodeState::Dirty => new_epoch,
965 };
966 let rlp_node = RlpNode::word_rlp(&EMPTY_ROOT_HASH);
967 *arena[root].state_mut() =
968 ArenaSparseNodeState::Cached { rlp_node: rlp_node.clone(), epoch: node_epoch };
969 return rlp_node
970 }
971 ArenaSparseNode::Leaf { .. } => {
972 Self::encode_leaf(arena, root, rlp_buf, rlp_node_buf, new_epoch);
973 return rlp_node_buf.pop().expect("encode_leaf must push an RlpNode");
974 }
975 ArenaSparseNode::Branch(b) => {
976 if let ArenaSparseNodeState::Cached { rlp_node, .. } = &b.state {
977 let rlp_node = rlp_node.clone();
978 return rlp_node;
979 }
980 }
981 ArenaSparseNode::Subtrie(_) | ArenaSparseNode::TakenSubtrie => {
982 unreachable!("Subtrie/TakenSubtrie should not appear inside a subtrie's own arena");
983 }
984 }
985
986 cursor.reset(arena, root, base_path);
987
988 loop {
992 let result = cursor.next(&mut *arena, |_, node| {
993 matches!(
994 node,
995 ArenaSparseNode::Branch(b) if matches!(b.state, ArenaSparseNodeState::Dirty)
996 )
997 });
998
999 match result {
1000 NextResult::Done => break,
1001 NextResult::NonBranch => {
1002 unreachable!("should_descend only returns true for dirty branches")
1003 }
1004 NextResult::Branch => {}
1005 };
1006
1007 let head = cursor.head().expect("cursor is non-empty");
1008 let head_idx = head.index;
1009 let head_path = head.path;
1010
1011 trace!(
1015 target: TRACE_TARGET,
1016 branch_path = ?head_path,
1017 branch_short_key = ?arena[head_idx].short_key().expect("head is a branch"),
1018 state_mask = ?arena[head_idx].branch_ref().state_mask,
1019 "Calculating branch RlpNode",
1020 );
1021
1022 rlp_node_buf.clear();
1023 let mut node_epoch = TrieNodeEpoch::UNMODIFIED;
1024 let state_mask = arena[head_idx].branch_ref().state_mask;
1025 for (child_idx, _nibble) in BranchChildIter::new(state_mask) {
1026 match &arena[head_idx].branch_ref().children[child_idx] {
1027 ArenaSparseNodeBranchChild::Blinded(rlp_node) => {
1028 rlp_node_buf.push(rlp_node.clone());
1029 }
1030 ArenaSparseNodeBranchChild::Revealed(child_idx) => {
1031 let child_idx = *child_idx;
1032 match &arena[child_idx] {
1033 ArenaSparseNode::Leaf { .. } => {
1034 Self::encode_leaf(
1035 arena,
1036 child_idx,
1037 rlp_buf,
1038 rlp_node_buf,
1039 new_epoch,
1040 );
1041 }
1042 ArenaSparseNode::Branch(child_b) => {
1043 let ArenaSparseNodeState::Cached { rlp_node, .. } = &child_b.state
1044 else {
1045 panic!("child branch must be cached after DFS");
1046 };
1047 let rlp_node = rlp_node.clone();
1048 rlp_node_buf.push(rlp_node);
1049 }
1050 ArenaSparseNode::Subtrie(subtrie) => {
1051 let subtrie_root = &subtrie.arena[subtrie.root];
1052 match subtrie_root {
1053 ArenaSparseNode::Branch(ArenaSparseNodeBranch {
1054 state: ArenaSparseNodeState::Cached { rlp_node, .. },
1055 ..
1056 }) |
1057 ArenaSparseNode::Leaf {
1058 state: ArenaSparseNodeState::Cached { rlp_node, .. },
1059 ..
1060 } => {
1061 rlp_node_buf.push(rlp_node.clone());
1062 }
1063 _ => panic!("subtrie root must be a cached Branch or Leaf"),
1064 }
1065 }
1066 ArenaSparseNode::TakenSubtrie | ArenaSparseNode::EmptyRoot { .. } => {
1067 unreachable!("Unexpected child {:?}", arena[child_idx]);
1068 }
1069 }
1070 let Some(ArenaSparseNodeState::Cached { epoch: child_epoch, .. }) =
1071 arena[child_idx].state_ref()
1072 else {
1073 panic!("revealed child must be cached after encoding");
1074 };
1075 node_epoch = node_epoch.max(*child_epoch);
1076 }
1077 }
1078 }
1079
1080 let b = arena[head_idx].branch_ref();
1082 let short_key = b.short_key;
1083 let state_mask = b.state_mask;
1084 let prev_branch_masks = b.branch_masks;
1085 let new_branch_masks = Self::get_branch_masks(arena, b);
1086 let was_dirty = matches!(b.state, ArenaSparseNodeState::Dirty);
1087 if was_dirty {
1088 node_epoch = node_epoch.max(new_epoch);
1089 }
1090
1091 rlp_buf.clear();
1092 let rlp_node = BranchNodeRef::new(rlp_node_buf, state_mask).rlp(rlp_buf);
1093
1094 let rlp_node = if short_key.is_empty() {
1095 rlp_node
1096 } else {
1097 rlp_buf.clear();
1098 ExtensionNodeRef::new(&short_key, &rlp_node).rlp(rlp_buf)
1099 };
1100
1101 trace!(
1102 target: TRACE_TARGET,
1103 path = ?head_path,
1104 short_key = ?arena[head_idx].short_key(),
1105 children = ?state_mask.iter().zip(rlp_node_buf.iter()).collect::<Vec<_>>(),
1106 rlp_node = ?rlp_node,
1107 "Calculated branch RlpNode",
1108 );
1109
1110 let branch = arena[head_idx].branch_mut();
1111 branch.state = ArenaSparseNodeState::Cached { rlp_node, epoch: node_epoch };
1112 branch.branch_masks = new_branch_masks;
1113
1114 if let Some(trie_updates) = updates.as_mut().filter(|_| was_dirty) {
1117 let mut logical_path = head_path;
1118 logical_path.extend(&short_key);
1119
1120 if !logical_path.is_empty() {
1121 if !prev_branch_masks.is_empty() && new_branch_masks.is_empty() {
1122 trie_updates.push((logical_path, None));
1123 } else if !new_branch_masks.is_empty() {
1124 let compact = arena[head_idx].branch_ref().branch_node_compact(arena);
1125 trie_updates.push((logical_path, Some(compact)));
1126 }
1127 }
1128 }
1129 }
1130
1131 let ArenaSparseNodeState::Cached { rlp_node, .. } = &arena[root].branch_ref().state else {
1132 panic!("root must be cached after update_cached_rlp");
1133 };
1134 rlp_node.clone()
1135 }
1136
1137 fn get_leaf_value_in_arena<'a>(
1140 arena: &'a NodeArena,
1141 mut current: Index,
1142 full_path: &Nibbles,
1143 mut path_offset: usize,
1144 ) -> Option<&'a Vec<u8>> {
1145 loop {
1146 match &arena[current] {
1147 ArenaSparseNode::EmptyRoot { .. } | ArenaSparseNode::TakenSubtrie => return None,
1148 ArenaSparseNode::Leaf { key, value, .. } => {
1149 let remaining = full_path.slice(path_offset..);
1150 return (remaining == *key).then_some(value);
1151 }
1152 ArenaSparseNode::Branch(b) => {
1153 let short_key = &b.short_key;
1154 let logical_end = path_offset + short_key.len();
1155 if full_path.len() <= logical_end ||
1156 full_path.slice(path_offset..logical_end) != *short_key
1157 {
1158 return None;
1159 }
1160
1161 let child_nibble = full_path.get_unchecked(logical_end);
1162 let child_idx = BranchChildIdx::new(b.state_mask, child_nibble)?;
1163 match &b.children[child_idx] {
1164 ArenaSparseNodeBranchChild::Blinded(_) => return None,
1165 ArenaSparseNodeBranchChild::Revealed(child_idx) => {
1166 current = *child_idx;
1167 path_offset = logical_end + 1;
1168 }
1169 }
1170 }
1171 ArenaSparseNode::Subtrie(subtrie) => {
1172 return Self::get_leaf_value_in_arena(
1173 &subtrie.arena,
1174 subtrie.root,
1175 full_path,
1176 path_offset,
1177 );
1178 }
1179 }
1180 }
1181 }
1182
1183 fn find_leaf_in_arena(
1187 arena: &NodeArena,
1188 mut current: Index,
1189 full_path: &Nibbles,
1190 mut path_offset: usize,
1191 expected_value: Option<&Vec<u8>>,
1192 ) -> Result<LeafLookup, LeafLookupError> {
1193 loop {
1194 match &arena[current] {
1195 ArenaSparseNode::EmptyRoot { .. } | ArenaSparseNode::TakenSubtrie => {
1196 return Ok(LeafLookup::NonExistent);
1197 }
1198 ArenaSparseNode::Leaf { key, value, .. } => {
1199 let remaining = full_path.slice(path_offset..);
1200 if remaining != *key {
1201 return Ok(LeafLookup::NonExistent);
1202 }
1203 if let Some(expected) = expected_value &&
1204 *expected != *value
1205 {
1206 return Err(LeafLookupError::ValueMismatch {
1207 path: *full_path,
1208 expected: Some(expected.clone()),
1209 actual: value.clone(),
1210 });
1211 }
1212 return Ok(LeafLookup::Exists);
1213 }
1214 ArenaSparseNode::Branch(b) => {
1215 let short_key = &b.short_key;
1216 let logical_end = path_offset + short_key.len();
1217
1218 if full_path.len() <= logical_end {
1219 return Ok(LeafLookup::NonExistent);
1220 }
1221
1222 if full_path.slice(path_offset..logical_end) != *short_key {
1223 return Ok(LeafLookup::NonExistent);
1224 }
1225
1226 let child_nibble = full_path.get_unchecked(logical_end);
1227 let Some(child_idx) = BranchChildIdx::new(b.state_mask, child_nibble) else {
1228 return Ok(LeafLookup::NonExistent);
1229 };
1230
1231 match &b.children[child_idx] {
1232 ArenaSparseNodeBranchChild::Blinded(rlp_node) => {
1233 let hash = rlp_node
1234 .as_hash()
1235 .unwrap_or_else(|| keccak256(rlp_node.as_slice()));
1236 let mut blinded_path = full_path.slice(..logical_end);
1237 blinded_path.push_unchecked(child_nibble);
1238 return Err(LeafLookupError::BlindedNode { path: blinded_path, hash });
1239 }
1240 ArenaSparseNodeBranchChild::Revealed(child_idx) => {
1241 current = *child_idx;
1242 path_offset = logical_end + 1;
1243 }
1244 }
1245 }
1246 ArenaSparseNode::Subtrie(subtrie) => {
1247 return Self::find_leaf_in_arena(
1248 &subtrie.arena,
1249 subtrie.root,
1250 full_path,
1251 path_offset,
1252 expected_value,
1253 );
1254 }
1255 }
1256 }
1257 }
1258
1259 fn encode_leaf(
1263 arena: &mut NodeArena,
1264 idx: Index,
1265 rlp_buf: &mut Vec<u8>,
1266 rlp_node_buf: &mut Vec<RlpNode>,
1267 new_epoch: TrieNodeEpoch,
1268 ) {
1269 let (key, value, state) = match &arena[idx] {
1270 ArenaSparseNode::Leaf { key, value, state } => (key, value, state),
1271 _ => unreachable!("encode_leaf called on non-Leaf node"),
1272 };
1273
1274 let epoch = match state {
1275 ArenaSparseNodeState::Cached { rlp_node, .. } => {
1276 rlp_node_buf.push(rlp_node.clone());
1277 return;
1278 }
1279 ArenaSparseNodeState::Revealed => TrieNodeEpoch::UNMODIFIED,
1280 ArenaSparseNodeState::Dirty => new_epoch,
1281 };
1282
1283 rlp_buf.clear();
1284 let rlp_node = LeafNodeRef { key, value }.rlp(rlp_buf);
1285
1286 *arena[idx].state_mut() =
1287 ArenaSparseNodeState::Cached { rlp_node: rlp_node.clone(), epoch };
1288 rlp_node_buf.push(rlp_node);
1289 }
1290
1291 fn split_and_insert_leaf(
1305 arena: &mut NodeArena,
1306 cursor: &mut ArenaCursor,
1307 root: &mut Index,
1308 new_leaf_path: Nibbles,
1309 value: &[u8],
1310 ) -> bool {
1311 let old_child_entry = cursor.head().expect("cursor must have head");
1312 let old_child_idx = old_child_entry.index;
1313 let old_child_short_key = arena[old_child_idx].short_key().expect("top of stack is a leaf");
1314 let diverge_len = new_leaf_path.common_prefix_length(old_child_short_key);
1315
1316 trace!(
1317 target: TRACE_TARGET,
1318 path = ?old_child_entry.path,
1319 ?new_leaf_path,
1320 ?old_child_short_key,
1321 diverge_len,
1322 "Splitting node and inserting new leaf",
1323 );
1324
1325 let old_child_nibble = old_child_short_key.get_unchecked(diverge_len);
1326 let old_child_suffix = old_child_short_key.slice(diverge_len + 1..);
1327
1328 let newly_dirtied_existing = match &mut arena[old_child_idx] {
1331 ArenaSparseNode::Leaf { key, state, .. } => {
1332 *key = old_child_suffix;
1333 let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
1334 *state = ArenaSparseNodeState::Dirty;
1335 was_clean
1336 }
1337 ArenaSparseNode::Branch(b) => {
1338 b.short_key = old_child_suffix;
1339 b.state = b.state.to_dirty();
1340 false
1342 }
1343 _ => unreachable!("split_and_insert_leaf called on non-Leaf/Branch node"),
1344 };
1345
1346 let short_key = new_leaf_path.slice(..diverge_len);
1347 let new_leaf_nibble = new_leaf_path.get_unchecked(diverge_len);
1348 debug_assert_ne!(old_child_nibble, new_leaf_nibble);
1349
1350 let new_leaf_idx = arena.insert(ArenaSparseNode::Leaf {
1351 state: ArenaSparseNodeState::Dirty,
1352 key: new_leaf_path.slice(diverge_len + 1..),
1353 value: value.to_vec(),
1354 });
1355
1356 let (first_nibble, first_child, second_nibble, second_child) =
1357 if old_child_nibble < new_leaf_nibble {
1358 (old_child_nibble, old_child_idx, new_leaf_nibble, new_leaf_idx)
1359 } else {
1360 (new_leaf_nibble, new_leaf_idx, old_child_nibble, old_child_idx)
1361 };
1362
1363 let state_mask = TrieMask::from_nibble(first_nibble) | TrieMask::from_nibble(second_nibble);
1364 let mut children = SmallVec::with_capacity(2);
1365 children.push(ArenaSparseNodeBranchChild::Revealed(first_child));
1366 children.push(ArenaSparseNodeBranchChild::Revealed(second_child));
1367
1368 let new_branch_idx = arena.insert(ArenaSparseNode::Branch(ArenaSparseNodeBranch {
1369 state: ArenaSparseNodeState::Dirty,
1370 children,
1371 state_mask,
1372 short_key,
1373 branch_masks: BranchNodeMasks::default(),
1374 }));
1375
1376 cursor.replace_head_index(arena, root, new_branch_idx);
1377 newly_dirtied_existing
1378 }
1379
1380 #[instrument(level = "trace", target = TRACE_TARGET, skip_all, fields(full_path = ?full_path))]
1395 fn upsert_leaf(
1396 arena: &mut NodeArena,
1397 cursor: &mut ArenaCursor,
1398 root: &mut Index,
1399 full_path: &Nibbles,
1400 value: &[u8],
1401 find_result: SeekResult,
1402 ) -> (UpsertLeafResult, SubtrieCounterDeltas) {
1403 trace!(target: TRACE_TARGET, ?find_result, "Upserting leaf");
1404 let head = cursor.head().expect("cursor is non-empty");
1405
1406 match find_result {
1407 SeekResult::Blinded => {
1408 unreachable!("Blinded case must be handled by caller")
1409 }
1410 SeekResult::EmptyRoot => {
1411 let head_idx = head.index;
1412 let head_path = head.path;
1413 arena[head_idx] = ArenaSparseNode::Leaf {
1414 state: ArenaSparseNodeState::Dirty,
1415 key: full_path.slice(head_path.len()..),
1416 value: value.to_vec(),
1417 };
1418 (
1419 UpsertLeafResult::NewLeaf,
1420 SubtrieCounterDeltas { num_leaves_delta: 1, num_dirty_leaves_delta: 1 },
1421 )
1422 }
1423 SeekResult::RevealedLeaf => {
1424 let head_idx = head.index;
1426 let was_clean =
1427 if let ArenaSparseNode::Leaf { value: v, state, .. } = &mut arena[head_idx] {
1428 v.clear();
1429 v.extend_from_slice(value);
1430 let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
1431 *state = ArenaSparseNodeState::Dirty;
1432 was_clean
1433 } else {
1434 unreachable!("RevealedLeaf but cursor head is not a leaf")
1435 };
1436 (
1437 UpsertLeafResult::Updated,
1438 SubtrieCounterDeltas {
1439 num_leaves_delta: 0,
1440 num_dirty_leaves_delta: was_clean as i64,
1441 },
1442 )
1443 }
1444 SeekResult::Diverged => {
1445 let head_path = head.path;
1446 let full_path_from_head = full_path.slice(head_path.len()..);
1447
1448 let split_dirtied_existing =
1449 Self::split_and_insert_leaf(arena, cursor, root, full_path_from_head, value);
1450
1451 let result = if cursor.depth() >= 1 {
1452 UpsertLeafResult::NewChild
1453 } else {
1454 UpsertLeafResult::NewLeaf
1455 };
1456 (
1457 result,
1458 SubtrieCounterDeltas {
1459 num_leaves_delta: 1,
1460 num_dirty_leaves_delta: 1 + split_dirtied_existing as i64,
1461 },
1462 )
1463 }
1464 SeekResult::NoChild { child_nibble } => {
1465 let head_idx = head.index;
1466
1467 let head_branch_logical_path = cursor.head_logical_branch_path(arena);
1468 let leaf_key = full_path.slice(head_branch_logical_path.len() + 1..);
1469 let new_leaf = arena.insert(ArenaSparseNode::Leaf {
1470 state: ArenaSparseNodeState::Dirty,
1471 key: leaf_key,
1472 value: value.to_vec(),
1473 });
1474
1475 let branch = arena[head_idx].branch_mut();
1476 branch.set_child(child_nibble, ArenaSparseNodeBranchChild::Revealed(new_leaf));
1477
1478 cursor.seek(arena, full_path);
1480
1481 (
1482 UpsertLeafResult::NewChild,
1483 SubtrieCounterDeltas { num_leaves_delta: 1, num_dirty_leaves_delta: 1 },
1484 )
1485 }
1486 SeekResult::RevealedSubtrie => {
1487 unreachable!("RevealedSubtrie must be handled by caller")
1488 }
1489 }
1490 }
1491
1492 fn remove_leaf(
1508 arena: &mut NodeArena,
1509 cursor: &mut ArenaCursor,
1510 root: &mut Index,
1511 key: B256,
1512 full_path: &Nibbles,
1513 find_result: SeekResult,
1514 updates: &mut Option<SparseTrieUpdates>,
1515 ) -> (RemoveLeafResult, SubtrieCounterDeltas) {
1516 match find_result {
1517 SeekResult::Blinded | SeekResult::RevealedSubtrie => {
1518 unreachable!("Blinded/RevealedSubtrie must be handled by caller")
1519 }
1520 SeekResult::EmptyRoot | SeekResult::Diverged | SeekResult::NoChild { .. } => {
1521 (RemoveLeafResult::NotFound, SubtrieCounterDeltas::default())
1522 }
1523 SeekResult::RevealedLeaf => {
1524 let head = cursor.head().expect("cursor is non-empty");
1526 let head_idx = head.index;
1527 let head_path = head.path;
1528
1529 trace!(
1530 target: TRACE_TARGET,
1531 path = ?head_path,
1532 ?full_path,
1533 "Removing leaf",
1534 );
1535
1536 if let Some(parent_entry) = cursor.parent() {
1539 let parent_idx = parent_entry.index;
1540 let child_nibble = head_path.last().expect("non-root leaf");
1541 let parent_branch = arena[parent_idx].branch_ref();
1542
1543 if parent_branch.state_mask.count_bits() == 2 &&
1544 parent_branch.sibling_child(child_nibble).is_blinded()
1545 {
1546 let sibling_nibble = parent_branch
1547 .state_mask
1548 .iter()
1549 .find(|&n| n != child_nibble)
1550 .expect("branch has two children");
1551 let mut sibling_path = cursor.parent_logical_branch_path(arena);
1552 sibling_path.push_unchecked(sibling_nibble);
1553 trace!(target: TRACE_TARGET, ?full_path, ?sibling_path, "Removal would collapse branch onto blinded sibling, requesting proof");
1554 return (
1555 RemoveLeafResult::NeedsProof {
1556 key,
1557 proof_key: Self::nibbles_to_padded_b256(&sibling_path),
1558 parent: ProofV2TargetParent::new(
1559 sibling_path
1560 .len()
1561 .checked_sub(1)
1562 .expect("sibling path has a child nibble"),
1563 ),
1564 },
1565 SubtrieCounterDeltas::default(),
1566 );
1567 }
1568 }
1569
1570 let removed_was_dirty =
1572 matches!(arena[head_idx].state_ref(), Some(ArenaSparseNodeState::Dirty));
1573
1574 if cursor.depth() == 0 {
1575 arena.remove(head_idx);
1578 *root = arena
1579 .insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Dirty });
1580 cursor.reset(arena, *root, head_path);
1581 return (
1582 RemoveLeafResult::Removed,
1583 SubtrieCounterDeltas {
1584 num_leaves_delta: -1,
1585 num_dirty_leaves_delta: -(removed_was_dirty as i64),
1586 },
1587 );
1588 }
1589
1590 cursor.pop(arena);
1592
1593 let parent_entry = cursor.head().expect("cursor is non-empty");
1595 let parent_idx = parent_entry.index;
1596 let child_nibble = head_path.last().expect("non-root leaf");
1597
1598 arena.remove(head_idx);
1600 let parent_branch = arena[parent_idx].branch_mut();
1601 parent_branch.remove_child(child_nibble);
1602
1603 let collapse_dirtied_leaf = if parent_branch.state_mask.count_bits() == 1 {
1606 Self::collapse_branch(arena, cursor, root, updates)
1607 } else {
1608 false
1609 };
1610 (
1611 RemoveLeafResult::Removed,
1612 SubtrieCounterDeltas {
1613 num_leaves_delta: -1,
1614 num_dirty_leaves_delta: (collapse_dirtied_leaf as i64) -
1615 (removed_was_dirty as i64),
1616 },
1617 )
1618 }
1619 }
1620 }
1621
1622 fn check_subtrie_collapse_needs_proof(
1628 arena: &NodeArena,
1629 cursor: &ArenaCursor,
1630 subtrie_updates: &[(B256, Nibbles, LeafUpdate)],
1631 ) -> Option<ArenaRequiredProof> {
1632 let num_removals = subtrie_updates
1633 .iter()
1634 .filter(|(_, _, u)| matches!(u, LeafUpdate::Changed(v) if v.is_empty()))
1635 .count() as u64;
1636
1637 let num_changed =
1645 subtrie_updates.iter().filter(|(_, _, u)| matches!(u, LeafUpdate::Changed(_))).count()
1646 as u64;
1647
1648 if num_removals == 0 || num_removals != num_changed {
1649 return None;
1650 }
1651
1652 let subtrie_entry = cursor.head()?;
1654 let subtrie_num_leaves = match &arena[subtrie_entry.index] {
1655 ArenaSparseNode::Subtrie(s) => s.num_leaves,
1656 _ => return None,
1657 };
1658 if num_removals < subtrie_num_leaves {
1659 return None;
1660 }
1661
1662 let child_nibble =
1663 subtrie_entry.path.last().expect("subtrie path must have at least one nibble");
1664
1665 let parent_entry = cursor.parent()?;
1666 let parent_branch = arena[parent_entry.index].branch_ref();
1667 if parent_branch.state_mask.count_bits() != 2 {
1668 return None;
1669 }
1670
1671 if !parent_branch.sibling_child(child_nibble).is_blinded() {
1672 return None;
1673 }
1674
1675 let sibling_nibble = parent_branch
1676 .state_mask
1677 .iter()
1678 .find(|&n| n != child_nibble)
1679 .expect("branch has two children");
1680 let mut sibling_path = cursor.parent_logical_branch_path(arena);
1681 sibling_path.push_unchecked(sibling_nibble);
1682
1683 Some(ArenaRequiredProof {
1684 key: Self::nibbles_to_padded_b256(&sibling_path),
1685 parent: ProofV2TargetParent::new(
1686 sibling_path.len().checked_sub(1).expect("sibling path has a child nibble"),
1687 ),
1688 })
1689 }
1690
1691 fn collapse_branch(
1702 arena: &mut NodeArena,
1703 cursor: &mut ArenaCursor,
1704 root: &mut Index,
1705 updates: &mut Option<SparseTrieUpdates>,
1706 ) -> bool {
1707 let branch_entry = cursor.head().expect("cursor is non-empty");
1708 let branch_idx = branch_entry.index;
1709 let branch = arena[branch_idx].branch_ref();
1710 let remaining_nibble =
1711 branch.state_mask.iter().next().expect("branch has at least one child");
1712 let branch_short_key = branch.short_key;
1713
1714 debug_assert_eq!(
1715 branch.state_mask.count_bits(),
1716 1,
1717 "collapse_branch requires exactly 1 child"
1718 );
1719 debug_assert!(
1720 !branch.children[0].is_blinded(),
1721 "collapse_branch called with a blinded remaining child"
1722 );
1723
1724 trace!(
1725 target: TRACE_TARGET,
1726 path = ?branch_entry.path,
1727 short_key = ?branch_short_key,
1728 branch_masks = ?branch.branch_masks,
1729 ?remaining_nibble,
1730 "Collapsing single-child branch",
1731 );
1732
1733 if let Some(trie_updates) = updates.as_mut() &&
1736 !branch.branch_masks.is_empty()
1737 {
1738 let logical_path = cursor.head_logical_branch_path(arena);
1739 if !logical_path.is_empty() {
1740 trie_updates.push((logical_path, None));
1741 }
1742 }
1743
1744 let mut prefix = branch_short_key;
1746 prefix.push_unchecked(remaining_nibble);
1747
1748 let ArenaSparseNodeBranchChild::Revealed(child_idx) = branch.children[0] else {
1749 unreachable!()
1750 };
1751
1752 let newly_dirtied_leaf = match &mut arena[child_idx] {
1755 ArenaSparseNode::Leaf { key, state, .. } => {
1756 let mut new_key = prefix;
1757 new_key.extend(key);
1758 *key = new_key;
1759 let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
1760 *state = ArenaSparseNodeState::Dirty;
1761 was_clean
1762 }
1763 ArenaSparseNode::Branch(b) => {
1764 let mut new_short_key = prefix;
1765 new_short_key.extend(&b.short_key);
1766 b.short_key = new_short_key;
1767 b.state = b.state.to_dirty();
1768 false
1769 }
1770 ArenaSparseNode::Subtrie(subtrie) => {
1771 subtrie.path = branch_entry.path;
1772 match &mut subtrie.arena[subtrie.root] {
1773 ArenaSparseNode::Branch(b) => {
1774 let mut new_short_key = prefix;
1775 new_short_key.extend(&b.short_key);
1776 b.short_key = new_short_key;
1777 b.state = b.state.to_dirty();
1778 }
1779 ArenaSparseNode::Leaf { key, state, .. } => {
1780 let mut new_key = prefix;
1781 new_key.extend(key);
1782 *key = new_key;
1783 let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
1784 *state = ArenaSparseNodeState::Dirty;
1785 if was_clean {
1786 subtrie.num_dirty_leaves += 1;
1787 }
1788 }
1789 _ => {
1790 unreachable!("subtrie root must be a Branch or Leaf during collapse_branch")
1791 }
1792 }
1793 false
1794 }
1795 _ => unreachable!("remaining child must be Leaf, Branch, or Subtrie"),
1796 };
1797
1798 cursor.replace_head_index(arena, root, child_idx);
1800
1801 arena.remove(branch_idx);
1803 newly_dirtied_leaf
1804 }
1805
1806 fn count_leaves_and_dirty(arena: &NodeArena, idx: Index) -> (u64, u64) {
1808 match &arena[idx] {
1809 ArenaSparseNode::Leaf { state, .. } => {
1810 let dirty = matches!(state, ArenaSparseNodeState::Dirty) as u64;
1811 (1, dirty)
1812 }
1813 ArenaSparseNode::Branch(b) => {
1814 let mut leaves = 0u64;
1815 let mut dirty = 0u64;
1816 for c in &b.children {
1817 if let ArenaSparseNodeBranchChild::Revealed(child_idx) = c {
1818 let (l, d) = Self::count_leaves_and_dirty(arena, *child_idx);
1819 leaves += l;
1820 dirty += d;
1821 }
1822 }
1823 (leaves, dirty)
1824 }
1825 _ => (0, 0),
1826 }
1827 }
1828
1829 #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
1835 #[cfg(debug_assertions)]
1836 fn debug_assert_subtrie_structure(&mut self) {
1837 let mut cursor = mem::take(&mut self.buffers.cursor);
1838 cursor.reset(&self.upper_arena, self.root, Nibbles::default());
1839
1840 loop {
1841 let result = cursor.next(&mut self.upper_arena, |_, _| true);
1842 match result {
1843 NextResult::Done => break,
1844 NextResult::NonBranch | NextResult::Branch => {
1845 let head = cursor.head().expect("cursor is non-empty");
1846 let path_len = head.path.len();
1847 let node = &self.upper_arena[head.index];
1848
1849 if Self::should_be_subtrie(path_len) {
1850 debug_assert!(
1851 matches!(
1852 node,
1853 ArenaSparseNode::Subtrie(_) | ArenaSparseNode::TakenSubtrie
1854 ),
1855 "node at path_len={path_len} should be a Subtrie but is {node:?}",
1856 );
1857 } else {
1858 debug_assert!(
1859 !matches!(node, ArenaSparseNode::Subtrie(_)),
1860 "node at path_len={path_len} should NOT be a Subtrie but is",
1861 );
1862 }
1863 }
1864 }
1865 }
1866
1867 self.buffers.cursor = cursor;
1868 }
1869
1870 fn migrate_nodes(
1878 dst: &mut NodeArena,
1879 src: &mut NodeArena,
1880 src_idx: Index,
1881 dst_slot: Option<Index>,
1882 ) -> Index {
1883 let mut node = src.remove(src_idx).expect("node exists in source arena");
1884
1885 if let ArenaSparseNode::Branch(b) = &mut node {
1887 for child in &mut b.children {
1888 if let ArenaSparseNodeBranchChild::Revealed(child_idx) = child {
1889 *child_idx = Self::migrate_nodes(dst, src, *child_idx, None);
1890 }
1891 }
1892 }
1893
1894 if let Some(slot) = dst_slot {
1895 dst[slot] = node;
1896 slot
1897 } else {
1898 dst.insert(node)
1899 }
1900 }
1901
1902 fn remove_pruned_node(
1905 arena: &mut NodeArena,
1906 cursor: &ArenaCursor,
1907 idx: Index,
1908 nibble: Option<u8>,
1909 ) -> ArenaSparseNode {
1910 let path = cursor.head().expect("cursor is non-empty").path;
1911 let node = arena.remove(idx).expect("node must exist to be pruned");
1912 let rlp_node = node
1913 .state_ref()
1914 .and_then(ArenaSparseNodeState::cached_rlp_node)
1915 .cloned()
1916 .expect("prune must run after hashing");
1917 trace!(
1918 target: TRACE_TARGET,
1919 ?path,
1920 variant = %AsRef::<str>::as_ref(&node),
1921 cached_rlp_node = ?rlp_node,
1922 "pruning node",
1923 );
1924
1925 let parent_idx = cursor.parent().expect("pruned child has parent").index;
1926 let child_nibble = nibble.expect("non-root child");
1927 let parent_branch = arena[parent_idx].branch_mut();
1928 let child_idx = BranchChildIdx::new(parent_branch.state_mask, child_nibble)
1929 .expect("child nibble not found in parent state_mask");
1930 parent_branch.children[child_idx] = ArenaSparseNodeBranchChild::Blinded(rlp_node);
1931
1932 node
1933 }
1934
1935 #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
1944 fn reveal_node(
1945 arena: &mut NodeArena,
1946 cursor: &ArenaCursor,
1947 node: &mut ProofTrieNodeV2,
1948 find_result: SeekResult,
1949 ) -> Option<Index> {
1950 let SeekResult::Blinded = find_result else {
1951 return None;
1953 };
1954
1955 let head = cursor.head().expect("cursor is non-empty");
1956 let head_idx = head.index;
1957 let head_branch_logical_path = cursor.head_logical_branch_path(arena);
1958
1959 debug_assert_eq!(
1960 node.path.len(),
1961 head_branch_logical_path.len() + 1,
1962 "proof node path {:?} is not a direct child of branch at {:?} (expected depth {})",
1963 node.path,
1964 head_branch_logical_path,
1965 head_branch_logical_path.len() + 1,
1966 );
1967
1968 let child_nibble = node.path.get_unchecked(head_branch_logical_path.len());
1969 let head_branch = arena[head_idx].branch_ref();
1970 let dense_child_idx = BranchChildIdx::new(head_branch.state_mask, child_nibble)
1971 .expect("Blinded result but child nibble not in state_mask");
1972
1973 let cached_rlp = match &head_branch.children[dense_child_idx] {
1974 ArenaSparseNodeBranchChild::Blinded(rlp) => rlp.clone(),
1975 ArenaSparseNodeBranchChild::Revealed(_) => return None,
1976 };
1977
1978 trace!(
1979 target: TRACE_TARGET,
1980 path = ?node.path,
1981 rlp_node = ?cached_rlp,
1982 "Revealing node",
1983 );
1984
1985 let proof_node = mem::replace(node, ProofTrieNodeV2::empty());
1986 let mut arena_node = ArenaSparseNode::from_proof_node(proof_node);
1987
1988 let state = arena_node.state_mut();
1989 *state =
1990 ArenaSparseNodeState::Cached { rlp_node: cached_rlp, epoch: TrieNodeEpoch::UNMODIFIED };
1991
1992 let child_idx = arena.insert(arena_node);
1993 arena[head_idx].branch_mut().children[dense_child_idx] =
1994 ArenaSparseNodeBranchChild::Revealed(child_idx);
1995
1996 Some(child_idx)
1997 }
1998
1999 #[cfg(debug_assertions)]
2000 fn collect_reachable_nodes(
2001 arena: &NodeArena,
2002 idx: Index,
2003 reachable: &mut alloy_primitives::map::HashSet<Index>,
2004 ) {
2005 if !reachable.insert(idx) {
2006 return;
2007 }
2008 if let ArenaSparseNode::Branch(b) = &arena[idx] {
2009 for child in &b.children {
2010 if let ArenaSparseNodeBranchChild::Revealed(child_idx) = child {
2011 Self::collect_reachable_nodes(arena, *child_idx, reachable);
2012 }
2013 }
2014 }
2015 }
2016
2017 #[cfg(debug_assertions)]
2018 fn assert_no_orphaned_nodes(arena: &NodeArena, root: Index, label: &str) {
2019 let mut reachable = alloy_primitives::map::HashSet::default();
2020 Self::collect_reachable_nodes(arena, root, &mut reachable);
2021 let all_indices: alloy_primitives::map::HashSet<Index> =
2022 arena.iter().map(|(idx, _)| idx).collect();
2023 let orphaned: Vec<_> = all_indices.difference(&reachable).collect();
2024 debug_assert!(
2025 orphaned.is_empty(),
2026 "{label} has {} orphaned node(s): {orphaned:?}",
2027 orphaned.len(),
2028 );
2029 }
2030}
2031
2032#[cfg(debug_assertions)]
2033impl Drop for ArenaParallelSparseTrie {
2034 fn drop(&mut self) {
2035 Self::assert_no_orphaned_nodes(&self.upper_arena, self.root, "upper arena");
2036
2037 for (_, node) in &self.upper_arena {
2038 if let Some(subtrie) = node.as_subtrie() {
2039 Self::assert_no_orphaned_nodes(
2040 &subtrie.arena,
2041 subtrie.root,
2042 &alloc::format!("subtrie {:?}", subtrie.path),
2043 );
2044 }
2045 }
2046 }
2047}
2048
2049impl Default for ArenaParallelSparseTrie {
2050 fn default() -> Self {
2051 let mut upper_arena = SlotMap::new();
2052 let root = upper_arena
2053 .insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Revealed });
2054 Self {
2055 upper_arena,
2056 root,
2057 buffers: ArenaTrieBuffers::default(),
2058 parallelism_thresholds: ArenaParallelismThresholds::default(),
2059 }
2060 }
2061}
2062
2063impl ArenaParallelSparseTrie {
2064 fn update_upper_subtrie(&mut self, head_idx: Index, new_epoch: TrieNodeEpoch) {
2066 let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[head_idx] else {
2067 unreachable!()
2068 };
2069
2070 if !subtrie.arena[subtrie.root].is_cached() {
2071 subtrie.update_cached_rlp(new_epoch);
2072 }
2073
2074 Self::merge_subtrie_updates(&mut self.buffers.updates, &mut subtrie.buffers.updates);
2075 }
2076}
2077
2078impl SparseTrie for ArenaParallelSparseTrie {
2079 #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
2080 fn set_root(
2081 &mut self,
2082 root: TrieNodeV2,
2083 masks: Option<BranchNodeMasks>,
2084 retain_updates: bool,
2085 ) -> SparseTrieResult<()> {
2086 debug_assert!(
2087 matches!(self.upper_arena[self.root], ArenaSparseNode::EmptyRoot { .. }),
2088 "set_root called on a trie that already has revealed nodes"
2089 );
2090
2091 self.set_updates(retain_updates);
2092
2093 match root {
2094 TrieNodeV2::EmptyRoot => {
2095 trace!(target: TRACE_TARGET, "Setting empty root");
2096 self.upper_arena[self.root] =
2097 ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Revealed };
2098 }
2099 TrieNodeV2::Leaf(leaf) => {
2100 trace!(target: TRACE_TARGET, key = ?leaf.key, "Setting leaf root");
2101 self.upper_arena[self.root] = ArenaSparseNode::Leaf {
2102 state: ArenaSparseNodeState::Revealed,
2103 key: leaf.key,
2104 value: leaf.value,
2105 };
2106 }
2107 TrieNodeV2::Branch(branch) => {
2108 trace!(target: TRACE_TARGET, state_mask = ?branch.state_mask, num_children = branch.state_mask.count_bits(), "Setting branch root");
2109 let mut children = SmallVec::with_capacity(branch.state_mask.count_bits() as usize);
2110 for (stack_ptr, _nibble) in branch.state_mask.iter().enumerate() {
2111 children
2112 .push(ArenaSparseNodeBranchChild::Blinded(branch.stack[stack_ptr].clone()));
2113 }
2114
2115 self.upper_arena[self.root] = ArenaSparseNode::Branch(ArenaSparseNodeBranch {
2116 state: ArenaSparseNodeState::Revealed,
2117 children,
2118 state_mask: branch.state_mask,
2119 short_key: branch.key,
2120 branch_masks: masks.unwrap_or_default(),
2121 });
2122 }
2123 TrieNodeV2::Extension(_) => {
2124 panic!("set_root does not support Extension nodes; extensions are represented as branches with a short_key")
2125 }
2126 }
2127
2128 Ok(())
2129 }
2130
2131 fn set_updates(&mut self, retain_updates: bool) {
2132 if retain_updates {
2133 self.buffers.updates.get_or_insert_with(SparseTrieUpdates::default).clear();
2134 } else {
2135 self.buffers.updates = None;
2136 }
2137 }
2138
2139 #[instrument(level = "trace", target = TRACE_TARGET, skip_all, fields(num_nodes = nodes.len()))]
2140 fn reveal_nodes(&mut self, nodes: &mut [ProofTrieNodeV2]) -> SparseTrieResult<()> {
2141 if nodes.is_empty() {
2142 return Ok(());
2143 }
2144
2145 if matches!(self.upper_arena[self.root], ArenaSparseNode::EmptyRoot { .. }) {
2146 trace!(target: TRACE_TARGET, "Skipping reveal_nodes on empty root");
2147 return Ok(());
2148 }
2149
2150 nodes.sort_unstable_by_key(|n| n.path);
2152
2153 let threshold = self.parallelism_thresholds.min_revealed_nodes;
2154
2155 let mut cursor = mem::take(&mut self.buffers.cursor);
2157 cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2158
2159 let mut node_idx = if nodes[0].path.is_empty() { 1 } else { 0 };
2161
2162 let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>, Vec<ProofTrieNodeV2>)> = Vec::new();
2166
2167 while node_idx < nodes.len() {
2168 let find_result = cursor.seek(&mut self.upper_arena, &nodes[node_idx].path);
2169
2170 match find_result {
2171 SeekResult::RevealedLeaf => {
2172 trace!(target: TRACE_TARGET, path = ?nodes[node_idx].path, "Skipping reveal: leaf head");
2173 node_idx += 1;
2174 }
2175 SeekResult::Blinded => {
2176 let child_path = nodes[node_idx].path;
2178 let child_idx = Self::reveal_node(
2179 &mut self.upper_arena,
2180 &cursor,
2181 &mut nodes[node_idx],
2182 SeekResult::Blinded,
2183 );
2184 node_idx += 1;
2185
2186 if let Some(child_idx) = child_idx {
2187 self.maybe_wrap_in_subtrie(child_idx, &child_path);
2188 }
2189 }
2190 SeekResult::RevealedSubtrie => {
2191 let subtrie_entry = cursor.head().expect("cursor is non-empty");
2192 let child_idx = subtrie_entry.index;
2193 let prefix = subtrie_entry.path;
2194
2195 let subtrie_start = node_idx;
2196 while node_idx < nodes.len() && nodes[node_idx].path.starts_with(&prefix) {
2197 node_idx += 1;
2198 }
2199 let num_subtrie_nodes = node_idx - subtrie_start;
2200
2201 if num_subtrie_nodes >= threshold {
2202 trace!(target: TRACE_TARGET, ?prefix, num_subtrie_nodes, "Taking subtrie for parallel reveal");
2204 let ArenaSparseNode::Subtrie(subtrie) = mem::replace(
2205 &mut self.upper_arena[child_idx],
2206 ArenaSparseNode::TakenSubtrie,
2207 ) else {
2208 unreachable!("RevealedSubtrie must point to a Subtrie node")
2209 };
2210 let node_vec: Vec<ProofTrieNodeV2> = (subtrie_start..node_idx)
2211 .map(|i| mem::replace(&mut nodes[i], ProofTrieNodeV2::empty()))
2212 .collect();
2213 taken.push((child_idx, subtrie, node_vec));
2214 } else {
2215 trace!(target: TRACE_TARGET, ?prefix, num_subtrie_nodes, "Revealing subtrie inline");
2217 let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[child_idx]
2218 else {
2219 unreachable!("RevealedSubtrie must point to a Subtrie node")
2220 };
2221 let mut subtrie_nodes: Vec<ProofTrieNodeV2> = (subtrie_start..node_idx)
2222 .map(|i| mem::replace(&mut nodes[i], ProofTrieNodeV2::empty()))
2223 .collect();
2224 subtrie.reveal_nodes(&mut subtrie_nodes)?;
2225 }
2226 }
2227 _ => {
2228 trace!(target: TRACE_TARGET, path = ?nodes[node_idx].path, ?find_result, "Skipping reveal: no blinded child");
2229 node_idx += 1;
2230 }
2231 }
2232 }
2233
2234 cursor.drain(&mut self.upper_arena);
2236 self.buffers.cursor = cursor;
2237
2238 if taken.is_empty() {
2239 return Ok(());
2240 }
2241
2242 if taken.len() == 1 {
2244 let (_, subtrie, node_vec) = &mut taken[0];
2245 subtrie.reveal_nodes(node_vec)?;
2246 } else {
2247 use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator};
2248
2249 let parent_span = tracing::Span::current();
2250 let results: Vec<SparseTrieResult<()>> = taken
2251 .par_iter_mut()
2252 .map(|(_, subtrie, node_vec)| {
2253 let _guard = parent_span.enter();
2254 subtrie.reveal_nodes(node_vec)
2255 })
2256 .collect();
2257
2258 if let Some(err) = results.into_iter().find(|r| r.is_err()) {
2259 for (idx, subtrie, _) in taken {
2261 self.upper_arena[idx] = ArenaSparseNode::Subtrie(subtrie);
2262 }
2263 return err;
2264 }
2265 }
2266
2267 for (idx, subtrie, _) in taken {
2269 self.upper_arena[idx] = ArenaSparseNode::Subtrie(subtrie);
2270 }
2271
2272 #[cfg(debug_assertions)]
2273 self.debug_assert_subtrie_structure();
2274
2275 Ok(())
2276 }
2277
2278 #[instrument(level = "trace", target = TRACE_TARGET, skip_all, ret)]
2279 fn root(&mut self, new_epoch: TrieNodeEpoch) -> B256 {
2280 self.update_subtrie_hashes(new_epoch);
2281
2282 let rlp_node = Self::update_cached_rlp(
2283 &mut self.upper_arena,
2284 self.root,
2285 Nibbles::default(),
2286 &mut self.buffers,
2287 new_epoch,
2288 );
2289
2290 rlp_node.as_hash().expect("root RlpNode must be a hash")
2291 }
2292
2293 fn is_root_cached(&self) -> bool {
2294 self.upper_arena[self.root].is_cached()
2295 }
2296
2297 fn root_epoch(&self) -> Option<TrieNodeEpoch> {
2298 match self.upper_arena[self.root].state_ref()? {
2299 ArenaSparseNodeState::Revealed => Some(TrieNodeEpoch::UNMODIFIED),
2300 ArenaSparseNodeState::Cached { epoch, .. } => Some(*epoch),
2301 ArenaSparseNodeState::Dirty => None,
2302 }
2303 }
2304
2305 #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
2306 fn update_subtrie_hashes(&mut self, new_epoch: TrieNodeEpoch) {
2307 trace!(target: TRACE_TARGET, "Updating subtrie hashes");
2308
2309 if !matches!(&self.upper_arena[self.root], ArenaSparseNode::Branch(_)) {
2311 return;
2312 }
2313
2314 let mut total_dirty_leaves: u64 = 0;
2316 let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>)> = Vec::new();
2317 for (idx, node) in &mut self.upper_arena {
2318 let ArenaSparseNode::Subtrie(s) = node else { continue };
2319 if s.num_dirty_leaves == 0 {
2320 continue;
2321 }
2322 total_dirty_leaves += s.num_dirty_leaves;
2323 let ArenaSparseNode::Subtrie(subtrie) =
2324 mem::replace(node, ArenaSparseNode::TakenSubtrie)
2325 else {
2326 unreachable!()
2327 };
2328 taken.push((idx, subtrie));
2329 }
2330
2331 if !taken.is_empty() {
2333 if taken.len() == 1 || total_dirty_leaves < self.parallelism_thresholds.min_dirty_leaves
2334 {
2335 for (_, subtrie) in &mut taken {
2336 subtrie.update_cached_rlp(new_epoch);
2337 }
2338 } else {
2339 use rayon::iter::{IntoParallelIterator, ParallelIterator};
2340
2341 let parent_span = tracing::Span::current();
2342 taken = taken
2343 .into_par_iter()
2344 .map(|(idx, mut subtrie)| {
2345 let _guard = parent_span.enter();
2346 subtrie.update_cached_rlp(new_epoch);
2347 (idx, subtrie)
2348 })
2349 .collect();
2350 }
2351 }
2352
2353 if taken.is_empty() && self.upper_arena[self.root].is_cached() {
2356 return;
2357 }
2358
2359 taken.sort_unstable_by_key(|(_, b)| Reverse(b.path));
2363
2364 self.buffers.cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2365
2366 loop {
2367 let result = self.buffers.cursor.next(&mut self.upper_arena, |_, child| match child {
2368 ArenaSparseNode::Branch(_) | ArenaSparseNode::Subtrie(_) => !child.is_cached(),
2369 ArenaSparseNode::TakenSubtrie => true,
2370 _ => false,
2371 });
2372
2373 match result {
2374 NextResult::Done => break,
2375 NextResult::Branch => continue,
2376 NextResult::NonBranch => {}
2377 }
2378
2379 let head_idx = self.buffers.cursor.head().expect("cursor is non-empty").index;
2381
2382 if matches!(&self.upper_arena[head_idx], ArenaSparseNode::TakenSubtrie) {
2383 let (_, subtrie) = taken.pop().expect("taken subtries must not be exhausted");
2384 debug_assert_eq!(
2385 subtrie.path,
2386 self.buffers.cursor.head().expect("cursor is non-empty").path,
2387 "taken subtrie path mismatch",
2388 );
2389 self.upper_arena[head_idx] = ArenaSparseNode::Subtrie(subtrie);
2390 }
2391
2392 self.update_upper_subtrie(head_idx, new_epoch);
2393 }
2394 }
2395
2396 fn get_leaf_value(&self, full_path: &Nibbles) -> Option<&Vec<u8>> {
2397 Self::get_leaf_value_in_arena(&self.upper_arena, self.root, full_path, 0)
2398 }
2399
2400 fn find_leaf(
2401 &self,
2402 full_path: &Nibbles,
2403 expected_value: Option<&Vec<u8>>,
2404 ) -> Result<LeafLookup, LeafLookupError> {
2405 Self::find_leaf_in_arena(&self.upper_arena, self.root, full_path, 0, expected_value)
2406 }
2407
2408 fn take_updates(&mut self) -> SparseTrieUpdates {
2409 let Some(updates) = self.buffers.updates.as_mut() else { return Vec::new() };
2410
2411 updates.sort_by_key(|(path, _)| *path);
2414 updates.dedup_by(|later, earlier| {
2415 if later.0 == earlier.0 {
2416 mem::swap(earlier, later);
2417 true
2418 } else {
2419 false
2420 }
2421 });
2422 let capacity = updates.len();
2423 mem::replace(updates, Vec::with_capacity(capacity))
2424 }
2425
2426 #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
2427 fn clear(&mut self) {
2428 self.upper_arena = SlotMap::new();
2429 self.root = self
2430 .upper_arena
2431 .insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Revealed });
2432 self.buffers.clear();
2433 }
2434
2435 #[instrument(
2436 level = "trace",
2437 target = TRACE_TARGET,
2438 skip_all,
2439 fields(prune_before = prune_before.get()),
2440 )]
2441 fn prune(&mut self, prune_before: TrieNodeEpoch) -> usize {
2442 assert!(self.root_epoch().is_some(), "prune cannot run on a dirty trie");
2443
2444 if !matches!(&self.upper_arena[self.root], ArenaSparseNode::Branch(_)) {
2446 return 0;
2447 }
2448
2449 let threshold = self.parallelism_thresholds.min_leaves_for_prune;
2450
2451 let mut cursor = mem::take(&mut self.buffers.cursor);
2452 cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2453
2454 let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>)> = Vec::new();
2456
2457 let mut pruned = 0;
2458
2459 loop {
2460 let result = cursor.next(&mut self.upper_arena, |_, child| {
2461 matches!(
2462 child,
2463 ArenaSparseNode::Branch(_) |
2464 ArenaSparseNode::Subtrie(_) |
2465 ArenaSparseNode::Leaf { .. }
2466 )
2467 });
2468
2469 if matches!(result, NextResult::Done) {
2470 break
2471 }
2472
2473 let head = cursor.head().expect("cursor is non-empty");
2474 let head_idx = head.index;
2475 let head_path = head.path;
2476
2477 match &self.upper_arena[head_idx] {
2478 ArenaSparseNode::Branch(_) | ArenaSparseNode::Leaf { .. } => {
2479 if cursor.depth() == 0 {
2481 continue;
2482 }
2483
2484 let node_epoch = self.upper_arena[head_idx]
2485 .state_ref()
2486 .and_then(ArenaSparseNodeState::cached_epoch)
2487 .expect("prune must run after hashing");
2488 if !node_epoch.should_prune(prune_before) {
2489 continue;
2490 }
2491
2492 Self::remove_pruned_node(
2493 &mut self.upper_arena,
2494 &cursor,
2495 head_idx,
2496 head_path.last(),
2497 );
2498 pruned += 1;
2499 }
2500 ArenaSparseNode::Subtrie(_) => {
2501 let root_epoch = self.upper_arena[head_idx]
2502 .state_ref()
2503 .and_then(ArenaSparseNodeState::cached_epoch)
2504 .expect("prune must run after hashing");
2505 if root_epoch.should_prune(prune_before) {
2506 let removed = Self::remove_pruned_node(
2507 &mut self.upper_arena,
2508 &cursor,
2509 head_idx,
2510 head_path.last(),
2511 );
2512 let ArenaSparseNode::Subtrie(s) = &removed else { unreachable!() };
2513 pruned += s.arena.len();
2514 self.recycle_subtrie(removed);
2515 continue;
2516 }
2517
2518 let ArenaSparseNode::Subtrie(subtrie) = &self.upper_arena[head_idx] else {
2519 unreachable!()
2520 };
2521 if subtrie.num_leaves >= threshold {
2522 let ArenaSparseNode::Subtrie(subtrie) = mem::replace(
2523 &mut self.upper_arena[head_idx],
2524 ArenaSparseNode::TakenSubtrie,
2525 ) else {
2526 unreachable!()
2527 };
2528 taken.push((head_idx, subtrie));
2529 } else {
2530 let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[head_idx]
2531 else {
2532 unreachable!()
2533 };
2534 pruned += subtrie.prune(prune_before);
2535 }
2536 }
2537 _ => unreachable!("NonBranch in prune walk must be Subtrie, Leaf, or Branch"),
2538 }
2539 }
2540
2541 self.buffers.cursor = cursor;
2542
2543 if !taken.is_empty() {
2544 if taken.len() == 1 {
2546 let (_, ref mut subtrie) = taken[0];
2547 pruned += subtrie.prune(prune_before);
2548 } else {
2549 use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator};
2550
2551 let parent_span = tracing::Span::current();
2552 pruned += taken
2553 .par_iter_mut()
2554 .map(|(_, subtrie)| {
2555 let _guard = parent_span.enter();
2556 let _span = tracing::trace_span!(
2557 target: TRACE_TARGET,
2558 "subtrie_prune",
2559 subtrie = ?subtrie.path,
2560 )
2561 .entered();
2562
2563 subtrie.prune(prune_before)
2564 })
2565 .sum::<usize>();
2566 }
2567
2568 for (child_idx, subtrie) in taken {
2570 self.upper_arena[child_idx] = ArenaSparseNode::Subtrie(subtrie);
2571 }
2572 }
2573
2574 if pruned > 0 {
2575 compact_arena(&mut self.upper_arena, &mut self.root);
2576 }
2577
2578 pruned
2579 }
2580
2581 #[instrument(
2582 level = "trace",
2583 target = TRACE_TARGET,
2584 skip_all,
2585 fields(num_updates = updates.len()),
2586 )]
2587 fn update_leaves(
2588 &mut self,
2589 updates: &mut B256Map<LeafUpdate>,
2590 mut proof_required_fn: impl FnMut(B256, ProofV2TargetParent),
2591 ) -> SparseTrieResult<()> {
2592 if updates.is_empty() {
2593 return Ok(());
2594 }
2595
2596 let mut sorted: Vec<_> =
2598 updates.drain().map(|(key, update)| (key, Nibbles::unpack(key), update)).collect();
2599 sorted.sort_unstable_by_key(|entry| entry.1);
2600
2601 let threshold = self.parallelism_thresholds.min_updates;
2602 let parallelize_distributed_updates = sorted.len() >= threshold.saturating_mul(4);
2603
2604 let mut cursor = mem::take(&mut self.buffers.cursor);
2605 cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2606
2607 let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>, core::ops::Range<usize>)> = Vec::new();
2609
2610 let mut update_idx = 0;
2611 while update_idx < sorted.len() {
2612 let (key, ref full_path, ref update) = sorted[update_idx];
2613
2614 let find_result = cursor.seek(&mut self.upper_arena, full_path);
2615
2616 match find_result {
2617 SeekResult::Blinded => {
2619 let logical_len = cursor.head_logical_branch_path_len(&self.upper_arena);
2620 let parent = ProofV2TargetParent::new(logical_len);
2621 trace!(target: TRACE_TARGET, ?key, ?parent, "Update hit blinded node, requesting proof");
2622 proof_required_fn(key, parent);
2623 updates.insert(key, update.clone());
2624 }
2625 SeekResult::RevealedSubtrie => {
2627 let subtrie_entry = cursor.head().expect("cursor is non-empty");
2628 let child_idx = subtrie_entry.index;
2629 let subtrie_root_path = subtrie_entry.path;
2630
2631 let subtrie_start = update_idx;
2632 while update_idx < sorted.len() &&
2633 sorted[update_idx].1.starts_with(&subtrie_root_path)
2634 {
2635 update_idx += 1;
2636 }
2637
2638 let subtrie_updates = &sorted[subtrie_start..update_idx];
2639
2640 if let Some(proof) = Self::check_subtrie_collapse_needs_proof(
2644 &self.upper_arena,
2645 &cursor,
2646 subtrie_updates,
2647 ) {
2648 trace!(target: TRACE_TARGET, proof_key = ?proof.key, proof_parent = ?proof.parent, "Subtrie collapse would need blinded sibling, requesting proof");
2649 proof_required_fn(proof.key, proof.parent);
2650 for &(key, _, ref update) in subtrie_updates {
2651 updates.insert(key, update.clone());
2652 }
2653 continue;
2655 }
2656
2657 let num_subtrie_updates = update_idx - subtrie_start;
2658
2659 let all_removals = subtrie_updates
2663 .iter()
2664 .filter(|(_, _, u)| matches!(u, LeafUpdate::Changed(_)))
2668 .all(|(_, _, u)| matches!(u, LeafUpdate::Changed(v) if v.is_empty()));
2669 let subtrie_num_leaves = match &self.upper_arena[child_idx] {
2670 ArenaSparseNode::Subtrie(s) => s.num_leaves,
2671 _ => 0,
2672 };
2673 let might_empty_subtrie =
2674 all_removals && num_subtrie_updates as u64 >= subtrie_num_leaves;
2675
2676 if (num_subtrie_updates >= threshold || parallelize_distributed_updates) &&
2677 !might_empty_subtrie
2678 {
2679 trace!(target: TRACE_TARGET, ?subtrie_root_path, num_subtrie_updates, "Taking subtrie for parallel update");
2681 let ArenaSparseNode::Subtrie(subtrie) = mem::replace(
2682 &mut self.upper_arena[child_idx],
2683 ArenaSparseNode::TakenSubtrie,
2684 ) else {
2685 unreachable!()
2686 };
2687 taken.push((child_idx, subtrie, subtrie_start..update_idx));
2688 } else {
2689 trace!(target: TRACE_TARGET, ?subtrie_root_path, num_subtrie_updates, "Updating subtrie inline");
2691 let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[child_idx]
2692 else {
2693 unreachable!()
2694 };
2695
2696 subtrie.update_leaves(subtrie_updates);
2697
2698 for (target_idx, proof) in subtrie.required_proofs.drain(..) {
2699 proof_required_fn(proof.key, proof.parent);
2700 let (key, _, ref update) = subtrie_updates[target_idx];
2701 updates.insert(key, update.clone());
2702 }
2703
2704 self.maybe_unwrap_subtrie(&mut cursor);
2706 }
2707
2708 continue;
2710 }
2711 find_result @ (SeekResult::EmptyRoot |
2713 SeekResult::RevealedLeaf |
2714 SeekResult::Diverged |
2715 SeekResult::NoChild { .. }) => match update {
2716 LeafUpdate::Changed(v) if !v.is_empty() => {
2717 let (result, _deltas) = Self::upsert_leaf(
2718 &mut self.upper_arena,
2719 &mut cursor,
2720 &mut self.root,
2721 full_path,
2722 v,
2723 find_result,
2724 );
2725 match result {
2726 UpsertLeafResult::NewChild => {
2727 let head = cursor.head().expect("cursor is non-empty");
2728 if Self::should_be_subtrie(head.path.len()) {
2729 self.maybe_wrap_in_subtrie(head.index, &head.path);
2732 } else {
2733 self.maybe_wrap_branch_children(&cursor);
2737 }
2738 }
2739 UpsertLeafResult::NewLeaf => {
2740 self.maybe_wrap_branch_children(&cursor);
2743 }
2744 UpsertLeafResult::Updated => {}
2745 }
2746 }
2747 LeafUpdate::Changed(_) => {
2748 let (result, _deltas) = Self::remove_leaf(
2749 &mut self.upper_arena,
2750 &mut cursor,
2751 &mut self.root,
2752 key,
2753 full_path,
2754 find_result,
2755 &mut self.buffers.updates,
2756 );
2757 match result {
2758 RemoveLeafResult::NeedsProof { key, proof_key, parent } => {
2759 proof_required_fn(proof_key, parent);
2760 let update =
2761 mem::replace(&mut sorted[update_idx].2, LeafUpdate::Touched);
2762 updates.insert(key, update);
2763 }
2764 RemoveLeafResult::Removed => {
2765 self.maybe_collapse_or_remove_branch(&mut cursor);
2774 let head =
2775 cursor.head().expect("cursor always has root after collapse");
2776 self.maybe_wrap_in_subtrie(head.index, &head.path);
2777 }
2778 RemoveLeafResult::NotFound => {}
2779 }
2780 }
2781 LeafUpdate::Touched => {}
2782 },
2783 }
2784
2785 update_idx += 1;
2786 }
2787
2788 cursor.drain(&mut self.upper_arena);
2790 self.buffers.cursor = cursor;
2791
2792 if taken.is_empty() {
2793 #[cfg(debug_assertions)]
2794 self.debug_assert_subtrie_structure();
2795
2796 return Ok(());
2797 }
2798
2799 if taken.len() == 1 {
2801 let (_, ref mut subtrie, ref range) = taken[0];
2802 subtrie.update_leaves(&sorted[range.clone()]);
2803 } else {
2804 use rayon::iter::{IntoParallelRefMutIterator, ParallelIterator};
2805
2806 let parent_span = tracing::Span::current();
2807 taken.par_iter_mut().for_each(|(_, subtrie, range)| {
2808 let _guard = parent_span.enter();
2809 subtrie.update_leaves(&sorted[range.clone()]);
2810 });
2811 }
2812
2813 let taken_paths: Vec<Nibbles> = taken.iter().map(|(_, s, _)| s.path).collect();
2816 for (child_idx, mut subtrie, range) in taken {
2817 let subtrie_updates = &sorted[range];
2818 for (target_idx, proof) in subtrie.required_proofs.drain(..) {
2819 proof_required_fn(proof.key, proof.parent);
2820 let (key, _, ref update) = subtrie_updates[target_idx];
2821 updates.insert(key, update.clone());
2822 }
2823
2824 self.upper_arena[child_idx] = ArenaSparseNode::Subtrie(subtrie);
2826 }
2827
2828 {
2834 let mut cursor = mem::take(&mut self.buffers.cursor);
2835 cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2836
2837 for path in &taken_paths {
2838 let find_result = cursor.seek(&mut self.upper_arena, path);
2839 match find_result {
2840 SeekResult::RevealedSubtrie => {
2841 debug_assert!(
2842 {
2843 let head_idx = cursor.head().expect("cursor is non-empty").index;
2844 !matches!(
2845 &self.upper_arena[head_idx],
2846 ArenaSparseNode::Subtrie(s) if matches!(s.arena[s.root], ArenaSparseNode::EmptyRoot { .. })
2847 )
2848 },
2849 "taken subtrie became EmptyRoot — should have been forced inline"
2850 );
2851
2852 cursor.pop(&mut self.upper_arena);
2853
2854 self.maybe_collapse_or_remove_branch(&mut cursor);
2858 }
2859 _ => {
2860 }
2863 }
2864 }
2865
2866 cursor.drain(&mut self.upper_arena);
2867 self.buffers.cursor = cursor;
2868 }
2869
2870 #[cfg(debug_assertions)]
2871 self.debug_assert_subtrie_structure();
2872
2873 Ok(())
2874 }
2875}
2876
2877#[cfg(test)]
2878mod tests {
2879 use super::TRACE_TARGET;
2880 use crate::{
2881 ArenaParallelSparseTrie, ArenaParallelismThresholds, LeafUpdate, SparseTrie, TrieNodeEpoch,
2882 };
2883 use alloy_primitives::{map::B256Map, B256, U256};
2884 use rand::{seq::SliceRandom, Rng, SeedableRng};
2885 use reth_trie::test_utils::TrieTestHarness;
2886 use reth_trie_common::ProofV2Target;
2887 use std::collections::BTreeMap;
2888 use tracing::{info, trace};
2889
2890 const fn epoch(value: u64) -> TrieNodeEpoch {
2891 TrieNodeEpoch::new(value)
2892 }
2893
2894 struct ArenaTrieTestHarness {
2899 inner: TrieTestHarness,
2901 }
2902
2903 impl std::ops::Deref for ArenaTrieTestHarness {
2904 type Target = TrieTestHarness;
2905 fn deref(&self) -> &Self::Target {
2906 &self.inner
2907 }
2908 }
2909
2910 impl std::ops::DerefMut for ArenaTrieTestHarness {
2911 fn deref_mut(&mut self) -> &mut Self::Target {
2912 &mut self.inner
2913 }
2914 }
2915
2916 impl ArenaTrieTestHarness {
2917 fn new(storage: BTreeMap<B256, U256>) -> Self {
2919 Self { inner: TrieTestHarness::new(storage) }
2920 }
2921
2922 fn assert_changes(
2926 &self,
2927 apst: &mut ArenaParallelSparseTrie,
2928 changes: BTreeMap<B256, U256>,
2929 ) {
2930 let (expected_root, mut expected_trie_updates) = if changes.is_empty() {
2932 (self.original_root(), Default::default())
2933 } else {
2934 self.get_root_with_updates(&changes)
2935 };
2936
2937 self.minimize_trie_updates(&mut expected_trie_updates);
2938
2939 let mut leaf_updates: B256Map<LeafUpdate> = changes
2942 .iter()
2943 .map(|(&slot, &value)| {
2944 let rlp_value = if value == U256::ZERO {
2945 Vec::new()
2946 } else {
2947 alloy_rlp::encode_fixed_size(&value).to_vec()
2948 };
2949 (slot, LeafUpdate::Changed(rlp_value))
2950 })
2951 .collect();
2952
2953 loop {
2956 let mut targets: Vec<ProofV2Target> = Vec::new();
2957 apst.update_leaves(&mut leaf_updates, |key, parent| {
2958 targets.push(ProofV2Target::new(key).with_parent(parent));
2959 })
2960 .expect("update_leaves should succeed");
2961
2962 if targets.is_empty() {
2963 break;
2964 }
2965
2966 let (mut proof_nodes, _) = self.proof_v2(&mut targets);
2967 apst.reveal_nodes(&mut proof_nodes).expect("reveal_nodes should succeed");
2968 }
2969
2970 let actual_root = apst.root(epoch(0));
2972 let mut actual_updates = apst.take_updates();
2973
2974 actual_updates.retain(|(path, node)| match node {
2975 Some(node) => self.storage_trie_updates().storage_nodes.get(path) != Some(node),
2976 None => self.storage_trie_updates().storage_nodes.contains_key(path),
2977 });
2978 pretty_assertions::assert_eq!(
2979 expected_trie_updates.into_sorted().storage_nodes,
2980 actual_updates,
2981 "trie updates mismatch"
2982 );
2983 assert_eq!(expected_root, actual_root, "storage root mismatch");
2984 }
2985 }
2986
2987 use proptest::prelude::*;
2988 use proptest_arbitrary_interop::arb;
2989
2990 fn build_changeset(
2997 base: &BTreeMap<B256, U256>,
2998 new_keys: BTreeMap<B256, U256>,
2999 overlap_pct: f64,
3000 delete_pct: f64,
3001 rng: &mut rand::rngs::StdRng,
3002 ) -> BTreeMap<B256, U256> {
3003 let num_overlap = (base.len() as f64 * overlap_pct) as usize;
3004 let num_delete = (num_overlap as f64 * delete_pct) as usize;
3005
3006 let mut all_keys: Vec<B256> = base.keys().copied().collect();
3007 all_keys.shuffle(rng);
3008 let overlap_keys = &all_keys[..num_overlap];
3009
3010 let mut changeset = new_keys;
3011 for (i, &key) in overlap_keys.iter().enumerate() {
3012 let value =
3013 if i < num_delete { U256::ZERO } else { U256::from(rng.random::<u64>() | 1) };
3014 changeset.entry(key).or_insert(value);
3015 }
3016 changeset
3017 }
3018
3019 proptest! {
3020 #![proptest_config(ProptestConfig::with_cases(1000))]
3021 #[test]
3022 fn arena_trie_proptest(
3023 initial in proptest::collection::btree_map(arb::<B256>(), arb::<U256>(), 0..=100usize),
3024 changeset1_new_keys in proptest::collection::btree_map(arb::<B256>(), arb::<U256>(), 0..=30usize),
3025 changeset2_new_keys in proptest::collection::btree_map(arb::<B256>(), arb::<U256>(), 0..=30usize),
3026 overlap_pct in 0.0..=0.5f64,
3027 delete_pct in 0.0..=0.33f64, shuffle_seed in arb::<u64>(),
3029 ) {
3030 reth_tracing::init_test_tracing();
3031 info!(target: TRACE_TARGET, ?shuffle_seed, "PROPTEST START");
3032
3033 let initial: BTreeMap<B256, U256> = initial.into_iter()
3035 .filter(|(_, v)| *v != U256::ZERO)
3036 .collect();
3037
3038 let mut rng = rand::rngs::StdRng::seed_from_u64(shuffle_seed);
3039
3040 let changeset1 = build_changeset(&initial, changeset1_new_keys, overlap_pct, delete_pct, &mut rng);
3041 for (i, (k, v)) in changeset1.iter().enumerate() {
3042 trace!(target: TRACE_TARGET, ?i, ?k, ?v, "Changeset 1 entry");
3043 }
3044
3045 let mut harness = ArenaTrieTestHarness::new(initial);
3046
3047 let root_node = harness.root_node();
3049 let mut apst = ArenaParallelSparseTrie::default().with_parallelism_thresholds(
3050 ArenaParallelismThresholds {
3051 min_dirty_leaves: 3,
3052 min_revealed_nodes: 3,
3053 min_updates: 3,
3054 min_leaves_for_prune: 3,
3055 },
3056 );
3057 apst.set_root(root_node.node, root_node.masks, true).expect("set_root should succeed");
3058
3059 harness.assert_changes(&mut apst, changeset1.clone());
3060
3061 harness.apply_changeset(changeset1);
3063
3064 apst.prune(epoch(1));
3067
3068 let changeset2 = build_changeset(harness.storage(), changeset2_new_keys, overlap_pct, delete_pct, &mut rng);
3069 for (i, (k, v)) in changeset2.iter().enumerate() {
3070 trace!(target: TRACE_TARGET, ?i, ?k, ?v, "Changeset 2 entry");
3071 }
3072
3073 harness.assert_changes(&mut apst, changeset2);
3074 }
3075 }
3076}