1use super::{iter_sub_trie_targets, node::*, value::*, SubTrieTargets, TRACE_TARGET};
12use crate::{
13 hashed_cursor::{HashedCursor, HashedStorageCursor},
14 trie_cursor::{depth_first, TrieCursor, TrieStorageCursor},
15};
16use alloy_primitives::{keccak256, B256, U256};
17use alloy_rlp::Encodable;
18use alloy_trie::{BranchNodeCompact, TrieMask};
19use reth_execution_errors::trie::StateProofError;
20use reth_trie_common::{
21 prefix_set::PrefixSet, BranchNode, BranchNodeMasks, Nibbles, ProofTrieNode, ProofV2Target,
22 RlpNode, TrieNode,
23};
24use std::{cmp::Ordering, sync::Arc};
25use tracing::{error, instrument, trace};
26
27const RLP_ENCODE_BUF_SIZE: usize = 1024;
29
30#[derive(Debug)]
42pub struct ProofCalculator<TC, HC, VE: LeafValueEncoder> {
43 trie_cursor: TC,
45 hashed_cursor: HC,
47 branch_stack: Vec<ProofTrieBranch>,
50 branch_path: Nibbles,
52 child_stack: Vec<ProofTrieBranchChild<VE::DeferredEncoder>>,
69 cached_branch_stack: Vec<(Nibbles, BranchNodeCompact)>,
73 retained_proofs: Vec<ProofTrieNode>,
76 rlp_nodes_bufs: Vec<Vec<RlpNode>>,
82 rlp_encode_buf: Vec<u8>,
84 prefix_set: PrefixSet,
86}
87
88impl<TC, HC, VE: LeafValueEncoder> ProofCalculator<TC, HC, VE> {
89 pub fn new(trie_cursor: TC, hashed_cursor: HC) -> Self {
91 Self {
92 trie_cursor,
93 hashed_cursor,
94 branch_stack: Vec::<_>::with_capacity(64),
95 branch_path: Nibbles::new(),
96 child_stack: Vec::<_>::with_capacity(64),
97 cached_branch_stack: Vec::<_>::with_capacity(64),
98 retained_proofs: Vec::<_>::with_capacity(32),
99 rlp_nodes_bufs: Vec::<_>::with_capacity(8),
100 rlp_encode_buf: Vec::<_>::with_capacity(RLP_ENCODE_BUF_SIZE),
101 prefix_set: PrefixSet::default(),
102 }
103 }
104
105 pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {
110 self.prefix_set = prefix_set;
111 self
112 }
113
114 pub(super) fn set_prefix_set(&mut self, prefix_set: PrefixSet) {
116 self.prefix_set = prefix_set;
117 }
118}
119
120impl<TC, HC, VE> ProofCalculator<TC, HC, VE>
121where
122 TC: TrieCursor,
123 HC: HashedCursor,
124 VE: LeafValueEncoder<Value = HC::Value>,
125{
126 fn take_rlp_nodes_buf(&mut self) -> Vec<RlpNode> {
131 self.rlp_nodes_bufs
132 .pop()
133 .map(|mut buf| {
134 buf.clear();
135 buf
136 })
137 .unwrap_or_else(|| Vec::with_capacity(16))
138 }
139
140 #[inline]
147 const fn maybe_parent_nibble(&self) -> usize {
148 !self.branch_stack.is_empty() as usize
149 }
150
151 #[instrument(
187 target = TRACE_TARGET,
188 level = "trace",
189 skip_all,
190 fields(?path, ?check_parent_path),
191 ret,
192 )]
193 fn should_retain<'a>(
194 &self,
195 targets: &mut Option<TargetsCursor<'a>>,
196 path: &Nibbles,
197 check_parent_path: bool,
198 ) -> bool {
199 let Some(targets) = targets.as_mut() else { return false };
201
202 let (mut lower, mut upper) = targets.current();
203
204 loop {
205 if lower.key_nibbles.starts_with(path) {
226 let is_below_parent = |target: &ProofV2Target| {
227 target.parent.path_len().is_none_or(|len| path.len() > len)
228 };
229 return !check_parent_path ||
230 (is_below_parent(lower) ||
231 targets
232 .skip_iter()
233 .take_while(|target| target.key_nibbles.starts_with(path))
234 .any(is_below_parent) ||
235 targets
236 .rev_iter()
237 .take_while(|target| target.key_nibbles.starts_with(path))
238 .any(is_below_parent))
239 }
240
241 if upper
244 .is_some_and(|upper| depth_first::cmp(path, &upper.key_nibbles) != Ordering::Less)
245 {
246 (lower, upper) = targets.next();
247 trace!(target: TRACE_TARGET, target = ?lower, "upper target <= path, next target");
248 } else {
249 return false
250 }
251 }
252 }
253
254 fn commit_child(
263 &mut self,
264 child_path: Nibbles,
265 child: ProofTrieBranchChild<VE::DeferredEncoder>,
266 ) -> Result<RlpNode, StateProofError> {
267 if matches!(&child, ProofTrieBranchChild::RlpNode { .. }) {
269 self.rlp_encode_buf.clear();
270 return child.into_rlp(&mut self.rlp_encode_buf).map(|(node, _)| node)
271 }
272
273 trace!(target: TRACE_TARGET, ?child_path, "Retaining child");
274
275 self.rlp_encode_buf.clear();
280 let (proof_node, branch_node) =
281 child.into_proof_trie_node(child_path, &mut self.rlp_encode_buf)?;
282
283 self.rlp_encode_buf.clear();
286 proof_node.node.encode(&mut self.rlp_encode_buf);
287
288 self.retained_proofs.extend(branch_node);
289 self.retained_proofs.push(proof_node);
290 Ok(RlpNode::from_rlp(&self.rlp_encode_buf))
291 }
292
293 #[inline]
296 fn child_path_at(&self, nibble: u8) -> Nibbles {
297 let mut child_path = self.branch_path;
298 debug_assert!(child_path.len() < 64);
299 child_path.push_unchecked(nibble);
300 child_path
301 }
302
303 #[inline]
309 fn highest_set_nibble(mask: TrieMask) -> u8 {
310 debug_assert!(!mask.is_empty());
311 (u16::BITS - mask.leading_zeros() - 1) as u8
312 }
313
314 fn last_child_path(&self) -> Option<Nibbles> {
317 let Some(branch) = self.branch_stack.last() else {
319 return Some(Nibbles::new());
320 };
321
322 (!branch.state_mask.is_empty())
323 .then(|| self.child_path_at(Self::highest_set_nibble(branch.state_mask)))
324 }
325
326 #[instrument(
337 target = TRACE_TARGET,
338 level = "trace",
339 skip_all,
340 fields(child_path = ?self.last_child_path()),
341 )]
342 fn commit_last_child<'a>(
343 &mut self,
344 targets: &mut Option<TargetsCursor<'a>>,
345 ) -> Result<(), StateProofError> {
346 if matches!(self.child_stack.last(), Some(ProofTrieBranchChild::RlpNode { .. })) {
347 trace!(target: TRACE_TARGET, "Last child already committed, leaving stack unchanged");
348 return Ok(())
349 }
350
351 let Some(child_path) = self.last_child_path() else { return Ok(()) };
352 let child =
353 self.child_stack.pop().expect("child_stack can't be empty if there's a child path");
354
355 if self.should_retain(targets, &child_path, true) {
358 let (hash_mask_bit, tree_mask_bit) = child.mask_bits();
359 let child_rlp_node = self.commit_child(child_path, child)?;
360 trace!(target: TRACE_TARGET, ?child_rlp_node, "Pushing committed child RlpNode onto stack");
361 self.child_stack.push(ProofTrieBranchChild::RlpNode {
362 node: child_rlp_node,
363 short_key: Nibbles::new(),
364 hash_mask_bit,
365 tree_mask_bit,
366 });
367 } else {
368 trace!(target: TRACE_TARGET, "Pushing uncommitted child onto stack");
369 self.child_stack.push(child);
370 }
371
372 Ok(())
373 }
374
375 fn push_child<'a>(
378 &mut self,
379 targets: &mut Option<TargetsCursor<'a>>,
380 mut child: ProofTrieBranchChild<VE::DeferredEncoder>,
381 ) -> Result<(), StateProofError> {
382 let path = *child.short_key();
383
384 loop {
385 trace!(
386 target: TRACE_TARGET,
387 ?path,
388 branch_stack_len = ?self.branch_stack.len(),
389 branch_path = ?self.branch_path,
390 child_stack_len = ?self.child_stack.len(),
391 "push_child: loop",
392 );
393
394 let (nibble, short_key) = match self.branch_stack.last().map(|branch| branch.state_mask)
397 {
398 None if self.child_stack.is_empty() => {
399 self.child_stack.push(child);
401 return Ok(())
402 }
403 None => {
404 debug_assert_eq!(self.child_stack.len(), 1);
406 debug_assert!(!self
407 .child_stack
408 .last()
409 .expect("already checked for emptiness")
410 .short_key()
411 .is_empty());
412 self.push_new_branch(path)
413 }
414 Some(state_mask) => {
415 let common_prefix_len = self.branch_path.common_prefix_length(&path);
417
418 if common_prefix_len < self.branch_path.len() {
421 self.pop_branch(targets)?;
422 continue
423 }
424
425 let nibble = path.get_unchecked(common_prefix_len);
428 if state_mask.is_bit_set(nibble) {
429 self.push_new_branch(path)
430 } else {
431 (nibble, trim_nibbles_prefix(&path, common_prefix_len + 1))
432 }
433 }
434 };
435
436 child.trim_short_key_prefix(path.len() - short_key.len());
438
439 self.commit_last_child(targets)?;
442
443 let branch = self.branch_stack.last_mut().expect("branch_stack cannot be empty");
444 debug_assert!(!branch.state_mask.is_bit_set(nibble));
445
446 branch.state_mask.set_bit(nibble);
449
450 self.child_stack.push(child);
452 return Ok(())
453 }
454 }
455
456 fn push_new_branch(&mut self, new_child_path: Nibbles) -> (u8, Nibbles) {
463 let first_child_path = self
466 .last_child_path()
467 .expect("push_new_branch requires the current branch to have a child");
468
469 let new_child_short_key = trim_nibbles_prefix(&new_child_path, first_child_path.len());
472 let first_child_short_key = *self
473 .child_stack
474 .last()
475 .expect("push_new_branch can't be called with empty child_stack")
476 .short_key();
477 debug_assert!(!first_child_short_key.is_empty());
478
479 let common_prefix_len = first_child_short_key.common_prefix_length(&new_child_short_key);
482 let first_child_nibble = first_child_short_key.get_unchecked(common_prefix_len);
483 let new_child_nibble = new_child_short_key.get_unchecked(common_prefix_len);
484
485 let new_child_short_key = trim_nibbles_prefix(&new_child_short_key, common_prefix_len + 1);
487
488 let branch_path_len = first_child_path.len() + common_prefix_len;
490 self.branch_path = new_child_path.slice_unchecked(0, branch_path_len);
491
492 let first_child = self
495 .child_stack
496 .last_mut()
497 .expect("push_new_branch can't be called with empty child_stack");
498 first_child.trim_short_key_prefix(common_prefix_len + 1);
499
500 self.branch_stack.push(ProofTrieBranch {
504 ext_len: common_prefix_len as u8,
505 state_mask: TrieMask::from_nibble(first_child_nibble),
506 });
507
508 trace!(
509 target: TRACE_TARGET,
510 ?new_child_path,
511 ext_len = ?common_prefix_len,
512 ?first_child_nibble,
513 branch_path = ?self.branch_path,
514 "Pushed new branch",
515 );
516
517 (new_child_nibble, new_child_short_key)
518 }
519
520 #[instrument(target = TRACE_TARGET, level = "trace", skip_all)]
528 fn pop_branch<'a>(
529 &mut self,
530 targets: &mut Option<TargetsCursor<'a>>,
531 ) -> Result<(), StateProofError> {
532 trace!(
533 target: TRACE_TARGET,
534 branch = ?self.branch_stack.last(),
535 branch_path = ?self.branch_path,
536 child_stack_len = ?self.child_stack.len(),
537 "called",
538 );
539
540 self.commit_last_child(targets)?;
543
544 let mut rlp_nodes_buf = self.take_rlp_nodes_buf();
545 let mut masks = BranchNodeMasks::default();
546 let branch = self.branch_stack.pop().expect("branch_stack cannot be empty");
547
548 let num_children = branch.state_mask.count_ones() as usize;
551 debug_assert!(
552 self.child_stack.len() >= num_children,
553 "Stack is missing necessary children ({num_children:?})"
554 );
555 debug_assert!(
556 num_children >= 2,
557 "A branch must have at least two children, got {num_children}"
558 );
559
560 rlp_nodes_buf.reserve(num_children);
562 for (nibble, child) in branch
563 .state_mask
564 .iter()
565 .zip(self.child_stack.drain(self.child_stack.len() - num_children..))
566 {
567 let (hash_mask_bit, tree_mask_bit) = child.mask_bits();
568 masks.set_child_bits(nibble, hash_mask_bit, tree_mask_bit);
569
570 self.rlp_encode_buf.clear();
571 let (child_rlp_node, freed_buf) = child.into_rlp(&mut self.rlp_encode_buf)?;
572 if let Some(buf) = freed_buf {
573 self.rlp_nodes_bufs.push(buf);
574 }
575 rlp_nodes_buf.push(child_rlp_node);
576 }
577
578 debug_assert_eq!(
579 rlp_nodes_buf.len(),
580 num_children,
581 "children length must match number of bits set in state_mask"
582 );
583
584 let short_key = trim_nibbles_prefix(
587 &self.branch_path,
588 self.branch_path.len() - branch.ext_len as usize,
589 );
590
591 let new_path_len =
594 self.branch_path.len() - branch.ext_len as usize - self.maybe_parent_nibble();
595
596 let branch_as_child = ProofTrieBranchChild::Branch {
598 node: BranchNode::new(rlp_nodes_buf, branch.state_mask),
599 short_key,
600 masks: (!masks.is_empty()).then_some(masks),
601 };
602
603 debug_assert!(self.branch_path.len() >= new_path_len);
604 self.branch_path = self.branch_path.slice_unchecked(0, new_path_len);
605
606 self.child_stack.push(branch_as_child);
607
608 Ok(())
609 }
610
611 #[instrument(
618 target = TRACE_TARGET,
619 level = "trace",
620 skip_all,
621 fields(?lower_bound, ?upper_bound),
622 )]
623 fn calculate_key_range<'a>(
624 &mut self,
625 value_encoder: &mut VE,
626 targets: &mut Option<TargetsCursor<'a>>,
627 hashed_cursor_state: &mut HashedCursorState<VE::DeferredEncoder>,
628 lower_bound: Nibbles,
629 upper_bound: Option<Nibbles>,
630 ) -> Result<(), StateProofError> {
631 let mut map_hashed_cursor_entry = |(key_b256, val): (B256, _)| {
635 debug_assert_eq!(key_b256.len(), 32);
636 let key = Nibbles::unpack_array(key_b256.as_ref());
637 let val = value_encoder.deferred_encoder(key_b256, val);
638 (key, val)
639 };
640
641 if hashed_cursor_state.needs_seek_to(&lower_bound) {
644 trace!(
645 target: TRACE_TARGET,
646 current=?hashed_cursor_state.path(),
647 "Seeking hashed cursor to meet lower bound",
648 );
649
650 let lower_key = B256::right_padding_from(&lower_bound.pack());
651 *hashed_cursor_state = HashedCursorState::seeked(
652 lower_bound,
653 self.hashed_cursor.seek(lower_key)?.map(&mut map_hashed_cursor_entry),
654 );
655 }
656
657 while hashed_cursor_state
659 .path()
660 .is_some_and(|key| upper_bound.is_none_or(|upper_bound| key < &upper_bound))
661 {
662 let (key, val) = hashed_cursor_state.take();
663 self.push_child(targets, ProofTrieBranchChild::Leaf { short_key: key, value: val })?;
664 *hashed_cursor_state = HashedCursorState::seeked(
665 key,
666 self.hashed_cursor.next()?.map(&mut map_hashed_cursor_entry),
667 );
668 }
669
670 trace!(target: TRACE_TARGET, "No further keys within range");
671 Ok(())
672 }
673
674 fn take_cached_branch(
676 &mut self,
677 trie_cursor_state: &mut TrieCursorState,
678 ) -> (Nibbles, BranchNodeCompact) {
679 let (cached_path, mut cached_branch) = trie_cursor_state.take();
680
681 if self.prefix_set.contains(&cached_path) {
682 let mut unchanged_children = 0;
683 let mut child_path = cached_path;
684 for nibble in cached_branch.state_mask.iter() {
685 child_path.truncate(cached_path.len());
686 child_path.push_unchecked(nibble);
687 if !self.prefix_set.contains(&child_path) {
688 unchanged_children += 1;
689 if unchanged_children > 1 {
690 break
691 }
692 }
693 }
694
695 if unchanged_children <= 1 {
699 Arc::make_mut(&mut cached_branch.hashes).fill(B256::ZERO);
700 trace!(
701 target: TRACE_TARGET,
702 ?cached_path,
703 ?unchanged_children,
704 "Invalidated cached hashes because branch may collapse",
705 );
706 }
707 }
708
709 (cached_path, cached_branch)
710 }
711
712 #[inline]
719 fn try_pop_cached_branch(
720 &mut self,
721 trie_cursor_state: &mut TrieCursorState,
722 traversal_upper_bound: Option<&Nibbles>,
723 uncalculated_lower_bound: &Option<Nibbles>,
724 ) -> Result<PopCachedBranchOutcome, StateProofError> {
725 let Some(uncalculated_lower_bound) = uncalculated_lower_bound else {
728 return Ok(PopCachedBranchOutcome::Exhausted)
729 };
730
731 while let Some(cached) = self.cached_branch_stack.pop() {
734 if cached
735 .0
736 .next_without_prefix()
737 .is_some_and(|upper_bound| upper_bound <= *uncalculated_lower_bound)
738 {
739 trace!(target: TRACE_TARGET, cached_path=?cached.0, ?uncalculated_lower_bound, "Skipping covered cached branch");
740 continue
741 }
742 return Ok(PopCachedBranchOutcome::Popped(cached));
743 }
744
745 let Some(mut trie_cursor_path) = trie_cursor_state.path() else {
752 return Ok(PopCachedBranchOutcome::Exhausted)
753 };
754
755 if trie_cursor_path < uncalculated_lower_bound {
758 *trie_cursor_state = TrieCursorState::seeked(
759 *uncalculated_lower_bound,
760 self.trie_cursor.seek(*uncalculated_lower_bound)?,
761 );
762
763 if let Some(new_trie_cursor_path) = trie_cursor_state.path() {
766 trie_cursor_path = new_trie_cursor_path
767 } else {
768 return Ok(PopCachedBranchOutcome::Exhausted)
769 };
770 }
771
772 if traversal_upper_bound.is_some_and(|upper_bound| trie_cursor_path >= upper_bound) {
775 return Ok(PopCachedBranchOutcome::Exhausted)
776 }
777
778 let cached = self.take_cached_branch(trie_cursor_state);
785 trace!(target: TRACE_TARGET, cached=?cached, "Pushed next trie node onto cached_branch_stack");
786
787 let cached_path = &cached.0;
794 if uncalculated_lower_bound < cached_path && !cached_path.is_zeroes() {
795 let range = (*uncalculated_lower_bound, Some(*cached_path));
796 trace!(target: TRACE_TARGET, ?range, "Returning key range to calculate in order to catch up to cached branch");
797
798 self.cached_branch_stack.push(cached);
801
802 return Ok(PopCachedBranchOutcome::CalculateLeaves(range));
803 }
804
805 Ok(PopCachedBranchOutcome::Popped(cached))
806 }
807
808 fn commit_branches<'a>(
817 &mut self,
818 targets: &mut Option<TargetsCursor<'a>>,
819 next_path: &Nibbles,
820 uncalculated_lower_bound: Option<&Nibbles>,
821 ) -> Result<Option<(Nibbles, Option<Nibbles>)>, StateProofError> {
822 let dirty_range = |prefix_set: &mut PrefixSet, upper_bound: Option<Nibbles>| {
823 let uncalculated_lower_bound = uncalculated_lower_bound?;
824
825 if upper_bound.as_ref().is_some_and(|upper| uncalculated_lower_bound >= upper) {
826 return None
827 }
828
829 match upper_bound {
830 Some(upper_bound) => prefix_set
831 .contains_range(uncalculated_lower_bound..&upper_bound)
832 .then_some((*uncalculated_lower_bound, Some(upper_bound))),
833 None => prefix_set
834 .contains_from(uncalculated_lower_bound)
835 .then_some((*uncalculated_lower_bound, None)),
836 }
837 };
838
839 let mut popped_child_path_upper = None;
840 while !next_path.starts_with(&self.branch_path) {
841 if uncalculated_lower_bound.is_some_and(|lower| lower.starts_with(&self.branch_path)) &&
844 let Some(range) =
845 dirty_range(&mut self.prefix_set, self.branch_path.next_without_prefix())
846 {
847 return Ok(Some(range))
848 }
849
850 let branch = self.branch_stack.last().expect("branch_stack cannot be empty");
851 popped_child_path_upper = Some(
854 self.branch_path
855 .slice_unchecked(0, self.branch_path.len() - branch.ext_len as usize)
856 .next_without_prefix(),
857 );
858
859 self.pop_branch(targets)?;
860 }
861
862 if !self.branch_stack.is_empty() &&
869 let Some(upper_bound) = popped_child_path_upper &&
870 let Some(range) = dirty_range(
871 &mut self.prefix_set,
872 Some(upper_bound.unwrap_or(*next_path).min(*next_path)),
873 )
874 {
875 return Ok(Some(range))
876 }
877
878 Ok(None)
879 }
880
881 fn next_uncached_child_nibble(
884 prefix_set: &mut PrefixSet,
885 branch_path: &Nibbles,
886 uncalculated_lower_bound_ref: &Nibbles,
887 cached_state_mask: TrieMask,
888 ) -> Option<u8> {
889 let mut next_child_nibbles = cached_state_mask;
890
891 if prefix_set.contains(branch_path) {
895 let branch_path_len = branch_path.len();
896 let mut child_path = *branch_path;
897 for nibble in 0u8..16 {
898 child_path.truncate(branch_path_len);
899 child_path.push_unchecked(nibble);
900 if prefix_set.contains(&child_path) {
901 next_child_nibbles.set_bit(nibble);
902 }
903 }
904 }
905
906 let _orig_next_child_nibbles = next_child_nibbles;
907
908 if uncalculated_lower_bound_ref.starts_with(branch_path) &&
913 uncalculated_lower_bound_ref.len() > branch_path.len()
914 {
915 let lower_nibble = uncalculated_lower_bound_ref.get_unchecked(branch_path.len());
916 let already_processed_mask = TrieMask::new((1u16 << lower_nibble) - 1);
919 next_child_nibbles &= !already_processed_mask;
920 trace!(
921 target: TRACE_TARGET,
922 ?branch_path,
923 ?_orig_next_child_nibbles,
924 ?already_processed_mask,
925 ?next_child_nibbles,
926 "Unset already processed key nibbles from next_child_nibbles",
927 );
928 } else if !uncalculated_lower_bound_ref.starts_with(branch_path) &&
929 uncalculated_lower_bound_ref > branch_path
930 {
931 next_child_nibbles = TrieMask::default();
934 trace!(
935 target: TRACE_TARGET,
936 ?branch_path,
937 ?_orig_next_child_nibbles,
938 ?next_child_nibbles,
939 "Unset all nibbles from next_child_nibbles due to branch_path being outside this subtrie",
940 );
941 }
942
943 next_child_nibbles.first_set_bit_index()
944 }
945
946 #[instrument(target = TRACE_TARGET, level = "trace", skip_all)]
965 fn next_uncached_key_range<'a>(
966 &mut self,
967 targets: &mut Option<TargetsCursor<'a>>,
968 trie_cursor_state: &mut TrieCursorState,
969 traversal_upper_bound: Option<&Nibbles>,
970 mut uncalculated_lower_bound: Option<Nibbles>,
971 ) -> Result<Option<(Nibbles, Option<Nibbles>)>, StateProofError> {
972 loop {
973 if let (Some(lower_bound), Some(upper_bound)) =
974 (uncalculated_lower_bound.as_ref(), traversal_upper_bound) &&
975 lower_bound >= upper_bound
976 {
977 return Ok(None)
978 }
979
980 let (cached_path, cached_branch) = match self.try_pop_cached_branch(
986 trie_cursor_state,
987 traversal_upper_bound,
988 &uncalculated_lower_bound,
989 )? {
990 PopCachedBranchOutcome::Popped(cached) => cached,
991 PopCachedBranchOutcome::Exhausted => {
992 trace!(target: TRACE_TARGET, ?uncalculated_lower_bound, "Exhausted cached trie nodes");
996 if let Some(lower) = uncalculated_lower_bound {
997 self.commit_branches(targets, &lower, None)?;
998 return Ok(Some((lower, traversal_upper_bound.copied())));
999 }
1000 return Ok(None)
1001 }
1002 PopCachedBranchOutcome::CalculateLeaves(range) => {
1003 self.commit_branches(targets, &range.0, None)?;
1004 return Ok(Some(range));
1005 }
1006 };
1007
1008 let uncalculated_lower_bound_ref = uncalculated_lower_bound
1009 .as_ref()
1010 .expect("try_pop_cached_branch would return Exhausted if this were None");
1011
1012 trace!(
1013 target: TRACE_TARGET,
1014 branch_path = ?self.branch_path,
1015 branch_state_mask = ?self.branch_stack.last().map(|b| b.state_mask),
1016 ?cached_path,
1017 cached_branch_state_mask = ?cached_branch.state_mask,
1018 cached_branch_hash_mask = ?cached_branch.hash_mask,
1019 "loop",
1020 );
1021
1022 if let Some(range) =
1023 self.commit_branches(targets, &cached_path, Some(uncalculated_lower_bound_ref))?
1024 {
1025 self.cached_branch_stack.push((cached_path, cached_branch));
1026 return Ok(Some(range))
1027 }
1028
1029 debug_assert!(
1032 self.branch_path.len() < cached_path.len() || self.branch_path == cached_path,
1033 "branch_path {:?} is different-or-longer-than cached_path {cached_path:?}",
1034 self.branch_path
1035 );
1036
1037 if uncalculated_lower_bound_ref < &cached_path &&
1040 self.prefix_set.contains_range(uncalculated_lower_bound_ref..&cached_path)
1041 {
1042 self.cached_branch_stack.push((cached_path, cached_branch));
1043 return Ok(Some((*uncalculated_lower_bound_ref, Some(cached_path))))
1044 }
1045
1046 let child_nibble = Self::next_uncached_child_nibble(
1047 &mut self.prefix_set,
1048 &cached_path,
1049 uncalculated_lower_bound_ref,
1050 cached_branch.state_mask,
1051 );
1052
1053 let Some(child_nibble) = child_nibble else {
1054 trace!(
1055 target: TRACE_TARGET,
1056 path=?cached_path,
1057 ?cached_branch,
1058 "No further cached children",
1059 );
1060
1061 uncalculated_lower_bound = cached_path.next_without_prefix();
1067
1068 continue
1069 };
1070
1071 let mut child_path = cached_path;
1072 child_path.push_unchecked(child_nibble);
1073 let child_lower_bound = (*uncalculated_lower_bound_ref).max(child_path);
1074
1075 if cached_branch.hash_mask.is_bit_set(child_nibble) &&
1085 child_lower_bound == child_path &&
1086 !self.prefix_set.contains(&child_path)
1087 {
1088 let lower_bits = TrieMask::new((1u16 << child_nibble) - 1);
1091 let hash_idx = (cached_branch.hash_mask & lower_bits).count_ones() as usize;
1092 let hash = cached_branch.hashes[hash_idx];
1093
1094 if !hash.is_zero() {
1097 let mut probed_targets = targets.clone();
1098 if !self.should_retain(&mut probed_targets, &child_path, false) {
1099 trace!(
1100 target: TRACE_TARGET,
1101 ?child_path,
1102 ?hash_idx,
1103 ?hash,
1104 "Using cached hash for child",
1105 );
1106
1107 let tree_mask_bit = cached_branch.tree_mask.is_bit_set(child_nibble);
1110 self.cached_branch_stack.push((cached_path, cached_branch));
1111 self.push_child(
1112 targets,
1113 ProofTrieBranchChild::RlpNode {
1114 node: RlpNode::word_rlp(&hash),
1115 short_key: child_path,
1116 hash_mask_bit: true,
1117 tree_mask_bit,
1118 },
1119 )?;
1120
1121 if let (Some(targets), Some(probed_targets)) =
1122 (targets.as_mut(), probed_targets)
1123 {
1124 targets.i = targets.i.max(probed_targets.i);
1125 }
1126
1127 uncalculated_lower_bound = child_path.next_without_prefix();
1130
1131 continue
1132 }
1133 }
1134 }
1135
1136 if trie_cursor_state.path().is_some_and(|path| path < &child_lower_bound) {
1143 trace!(target: TRACE_TARGET, ?child_lower_bound, "Seeking trie cursor to child lower bound");
1144 *trie_cursor_state = TrieCursorState::seeked(
1145 child_lower_bound,
1146 self.trie_cursor.seek(child_lower_bound)?,
1147 );
1148 }
1149
1150 if let TrieCursorState::Available(next_cached_path, next_cached_branch) =
1154 &trie_cursor_state &&
1155 next_cached_path.starts_with(&child_path)
1156 {
1157 self.cached_branch_stack.push((cached_path, cached_branch));
1159
1160 trace!(
1161 target: TRACE_TARGET,
1162 ?child_path,
1163 ?next_cached_path,
1164 ?next_cached_branch,
1165 "Pushing cached branch for child",
1166 );
1167 let cached = self.take_cached_branch(trie_cursor_state);
1168 self.cached_branch_stack.push(cached);
1169 continue;
1170 }
1171
1172 let child_upper_bound = child_path.next_without_prefix();
1176 trace!(
1177 target: TRACE_TARGET,
1178 lower=?child_lower_bound,
1179 upper=?child_upper_bound,
1180 "Returning sub-trie's key range to calculate",
1181 );
1182
1183 self.cached_branch_stack.push((cached_path, cached_branch));
1185
1186 return Ok(Some((child_lower_bound, child_upper_bound)));
1187 }
1188 }
1189
1190 #[instrument(
1194 target = TRACE_TARGET,
1195 level = "trace",
1196 skip_all,
1197 fields(
1198 parent_prefix=?sub_trie_targets.parent_prefix,
1199 lower_bound=?sub_trie_targets.lower_bound,
1200 upper_bound=?sub_trie_targets.upper_bound,
1201 ),
1202 )]
1203 fn proof_subtrie<'a>(
1204 &mut self,
1205 value_encoder: &mut VE,
1206 trie_cursor_state: &mut TrieCursorState,
1207 hashed_cursor_state: &mut HashedCursorState<VE::DeferredEncoder>,
1208 sub_trie_targets: SubTrieTargets<'a>,
1209 ) -> Result<(), StateProofError> {
1210 let traversal_lower_bound = sub_trie_targets.lower_bound;
1211 let traversal_upper_bound = sub_trie_targets.upper_bound;
1212
1213 let mut targets = if sub_trie_targets.targets.is_empty() {
1216 None
1217 } else {
1218 Some(TargetsCursor::new(sub_trie_targets.targets))
1219 };
1220
1221 debug_assert!(self.cached_branch_stack.is_empty());
1224 debug_assert!(self.branch_stack.is_empty());
1225 debug_assert!(self.branch_path.is_empty());
1226 debug_assert!(self.child_stack.is_empty());
1227
1228 if trie_cursor_state.needs_seek_to(&traversal_lower_bound) {
1233 trace!(target: TRACE_TARGET, "Doing initial seek of trie cursor");
1234 *trie_cursor_state = TrieCursorState::seeked(
1235 traversal_lower_bound,
1236 self.trie_cursor.seek(traversal_lower_bound)?,
1237 );
1238 }
1239
1240 let mut uncalculated_lower_bound = Some(traversal_lower_bound);
1245
1246 trace!(target: TRACE_TARGET, "Starting loop");
1247 loop {
1248 let prev_uncalculated_lower_bound = uncalculated_lower_bound;
1250
1251 let Some((calc_lower_bound, calc_upper_bound)) = self.next_uncached_key_range(
1253 &mut targets,
1254 trie_cursor_state,
1255 traversal_upper_bound.as_ref(),
1256 prev_uncalculated_lower_bound,
1257 )?
1258 else {
1259 break;
1262 };
1263
1264 if let Some(prev_lower) = prev_uncalculated_lower_bound.as_ref() &&
1271 calc_lower_bound < *prev_lower
1272 {
1273 let msg = format!(
1274 "next_uncached_key_range went backwards: calc_lower={calc_lower_bound:?} < \
1275 prev_lower={prev_lower:?}, calc_upper={calc_upper_bound:?}, \
1276 lower_bound={traversal_lower_bound:?}, \
1277 upper_bound={traversal_upper_bound:?}",
1278 );
1279 error!(target: TRACE_TARGET, "{msg}");
1280 return Err(StateProofError::TrieInconsistency(msg));
1281 }
1282
1283 self.calculate_key_range(
1285 value_encoder,
1286 &mut targets,
1287 hashed_cursor_state,
1288 calc_lower_bound,
1289 calc_upper_bound,
1290 )?;
1291
1292 if hashed_cursor_state.path().is_none_or(|key| {
1298 traversal_upper_bound.is_some_and(|upper_bound| key >= &upper_bound)
1299 }) {
1300 break;
1301 }
1302
1303 uncalculated_lower_bound = calc_upper_bound;
1306 }
1307
1308 trace!(target: TRACE_TARGET, "Exited loop, popping remaining branches");
1310 while !self.branch_stack.is_empty() {
1311 self.pop_branch(&mut targets)?;
1312 }
1313
1314 debug_assert!(self.branch_stack.is_empty());
1318 debug_assert!(self.branch_path.is_empty());
1319 debug_assert!(self.child_stack.len() < 2);
1320
1321 self.cached_branch_stack.clear();
1324
1325 trace!(
1329 target: TRACE_TARGET,
1330 parent_prefix = ?sub_trie_targets.parent_prefix,
1331 child_stack_empty = self.child_stack.is_empty(),
1332 "Maybe retaining local root",
1333 );
1334 let root_node = self.child_stack.pop();
1335
1336 if sub_trie_targets.parent_prefix.is_none() {
1339 let (mut root_node, branch_node) = if let Some(root_node) = root_node {
1340 self.rlp_encode_buf.clear();
1341 root_node.into_proof_trie_node(Nibbles::new(), &mut self.rlp_encode_buf)?
1342 } else {
1343 (ProofTrieNode::empty(), None)
1344 };
1345
1346 if matches!(&root_node.node, TrieNode::Branch(_)) {
1349 root_node.masks = None;
1350 }
1351
1352 self.retained_proofs.extend(branch_node);
1353 self.retained_proofs.push(root_node);
1354 return Ok(())
1355 };
1356
1357 let Some(mut root_node) = root_node else { return Ok(()) };
1359
1360 let root_full_path = *root_node.short_key();
1361 let child_path = sub_trie_targets.lower_bound;
1362
1363 if !root_full_path.starts_with(&child_path) {
1365 return Err(StateProofError::TrieInconsistency(format!(
1366 "local root path {root_full_path:?} does not start with child path \
1367 {child_path:?}",
1368 )))
1369 }
1370
1371 let child_path_len = child_path.len();
1374
1375 root_node.trim_short_key_prefix(child_path_len);
1377 self.rlp_encode_buf.clear();
1378 let (root_node, branch_node) =
1379 root_node.into_proof_trie_node(child_path, &mut self.rlp_encode_buf)?;
1380 self.retained_proofs.extend(branch_node);
1381 self.retained_proofs.push(root_node);
1382
1383 Ok(())
1384 }
1385
1386 fn clear_computation_state(&mut self) {
1389 self.branch_stack.clear();
1390 self.branch_path = Nibbles::new();
1391 self.child_stack.clear();
1392 self.cached_branch_stack.clear();
1393 self.retained_proofs.clear();
1394 }
1395
1396 fn proof_inner(
1399 &mut self,
1400 value_encoder: &mut VE,
1401 targets: &mut [ProofV2Target],
1402 ) -> Result<Vec<ProofTrieNode>, StateProofError> {
1403 if targets.is_empty() {
1405 trace!(target: TRACE_TARGET, "Empty targets, returning");
1406 return Ok(Vec::new())
1407 }
1408
1409 let mut trie_cursor_state = TrieCursorState::unseeked();
1412 let mut hashed_cursor_state = HashedCursorState::unseeked();
1413 let mut previous_traversal_bounds: Option<(Nibbles, Option<Nibbles>)> = None;
1414
1415 for sub_trie_targets in iter_sub_trie_targets(targets) {
1418 let traversal_lower_bound = sub_trie_targets.lower_bound;
1419 let traversal_upper_bound = sub_trie_targets.upper_bound;
1420 if previous_traversal_bounds.is_some_and(|(_, previous_upper_bound)| {
1421 previous_upper_bound.is_none_or(|upper_bound| upper_bound > traversal_lower_bound)
1422 }) {
1423 if trie_cursor_state.needs_reset_before_seek(&traversal_lower_bound) {
1424 trace!(
1425 target: TRACE_TARGET,
1426 ?previous_traversal_bounds,
1427 ?traversal_lower_bound,
1428 ?traversal_upper_bound,
1429 "Resetting trie cursor before overlapping or backward traversal range",
1430 );
1431 self.trie_cursor.reset();
1432 trie_cursor_state = TrieCursorState::unseeked();
1433 }
1434 if hashed_cursor_state.needs_reset_before_seek(&traversal_lower_bound) {
1435 trace!(
1436 target: TRACE_TARGET,
1437 ?previous_traversal_bounds,
1438 ?traversal_lower_bound,
1439 ?traversal_upper_bound,
1440 "Resetting hashed cursor before overlapping or backward traversal range",
1441 );
1442 self.hashed_cursor.reset();
1443 hashed_cursor_state = HashedCursorState::unseeked();
1444 }
1445 }
1446
1447 if let Err(err) = self.proof_subtrie(
1448 value_encoder,
1449 &mut trie_cursor_state,
1450 &mut hashed_cursor_state,
1451 sub_trie_targets,
1452 ) {
1453 self.clear_computation_state();
1454 return Err(err);
1455 }
1456
1457 previous_traversal_bounds = Some((traversal_lower_bound, traversal_upper_bound));
1458 }
1459
1460 trace!(
1461 target: TRACE_TARGET,
1462 retained_proofs_len = ?self.retained_proofs.len(),
1463 "proof_inner: returning",
1464 );
1465 self.retained_proofs.sort_unstable_by(|a, b| depth_first::cmp(&a.path, &b.path));
1466 self.retained_proofs.dedup_by(|a, b| a.path == b.path);
1467 Ok(core::mem::take(&mut self.retained_proofs))
1468 }
1469
1470 #[instrument(target = TRACE_TARGET, level = "trace", skip_all)]
1480 pub fn proof(
1481 &mut self,
1482 value_encoder: &mut VE,
1483 targets: &mut [ProofV2Target],
1484 ) -> Result<Vec<ProofTrieNode>, StateProofError> {
1485 self.trie_cursor.reset();
1486 self.hashed_cursor.reset();
1487 self.proof_inner(value_encoder, targets)
1488 }
1489
1490 pub fn compute_root_hash(
1497 &mut self,
1498 proof_nodes: &[ProofTrieNode],
1499 ) -> Result<Option<B256>, StateProofError> {
1500 let root_node = proof_nodes.iter().find(|node| node.path.is_empty());
1502
1503 let Some(root) = root_node else {
1504 return Ok(None);
1505 };
1506
1507 self.rlp_encode_buf.clear();
1509 root.node.encode(&mut self.rlp_encode_buf);
1510 let root_hash = keccak256(&self.rlp_encode_buf);
1511
1512 Ok(Some(root_hash))
1513 }
1514
1515 #[instrument(target = TRACE_TARGET, level = "trace", skip(self, value_encoder))]
1521 pub fn root_node(&mut self, value_encoder: &mut VE) -> Result<ProofTrieNode, StateProofError> {
1522 self.root_nodes(value_encoder)?.pop().ok_or_else(|| {
1523 StateProofError::TrieInconsistency("root calculation returned no root node".to_string())
1524 })
1525 }
1526
1527 pub fn root_nodes(
1531 &mut self,
1532 value_encoder: &mut VE,
1533 ) -> Result<Vec<ProofTrieNode>, StateProofError> {
1534 self.trie_cursor.reset();
1535 self.hashed_cursor.reset();
1536
1537 let mut trie_cursor_state = TrieCursorState::unseeked();
1540 let mut hashed_cursor_state = HashedCursorState::unseeked();
1541
1542 static EMPTY_TARGETS: [ProofV2Target; 0] = [];
1543 let sub_trie_targets = SubTrieTargets {
1544 lower_bound: Nibbles::new(),
1545 upper_bound: None,
1546 parent_prefix: None,
1547 targets: &EMPTY_TARGETS,
1548 };
1549
1550 if let Err(err) = self.proof_subtrie(
1551 value_encoder,
1552 &mut trie_cursor_state,
1553 &mut hashed_cursor_state,
1554 sub_trie_targets,
1555 ) {
1556 self.clear_computation_state();
1557 return Err(err);
1558 }
1559
1560 Ok(core::mem::take(&mut self.retained_proofs))
1561 }
1562}
1563
1564pub type StorageProofCalculator<TC, HC> = ProofCalculator<TC, HC, StorageValueEncoder>;
1566
1567impl<TC, HC> StorageProofCalculator<TC, HC>
1568where
1569 TC: TrieStorageCursor,
1570 HC: HashedStorageCursor<Value = U256>,
1571{
1572 pub fn new_storage(trie_cursor: TC, hashed_cursor: HC) -> Self {
1574 Self::new(trie_cursor, hashed_cursor)
1575 }
1576
1577 #[instrument(target = TRACE_TARGET, level = "trace", skip(self, targets))]
1587 pub fn storage_proof(
1588 &mut self,
1589 hashed_address: B256,
1590 targets: &mut [ProofV2Target],
1591 ) -> Result<Vec<ProofTrieNode>, StateProofError> {
1592 self.hashed_cursor.set_hashed_address(hashed_address);
1593
1594 if self.hashed_cursor.is_storage_empty()? {
1596 return Ok(if targets.iter().any(|target| !target.parent.is_known()) {
1597 vec![ProofTrieNode {
1598 path: Nibbles::default(),
1599 node: TrieNode::EmptyRoot,
1600 masks: None,
1601 }]
1602 } else {
1603 Vec::new()
1604 })
1605 }
1606
1607 self.trie_cursor.set_hashed_address(hashed_address);
1610
1611 let mut storage_value_encoder = StorageValueEncoder;
1613 self.proof_inner(&mut storage_value_encoder, targets)
1614 }
1615
1616 #[instrument(target = TRACE_TARGET, level = "trace", skip(self))]
1622 pub fn storage_root_node(
1623 &mut self,
1624 hashed_address: B256,
1625 ) -> Result<ProofTrieNode, StateProofError> {
1626 self.storage_root_nodes(hashed_address)?.pop().ok_or_else(|| {
1627 StateProofError::TrieInconsistency(
1628 "storage root calculation returned no root node".to_string(),
1629 )
1630 })
1631 }
1632
1633 pub fn storage_root_nodes(
1637 &mut self,
1638 hashed_address: B256,
1639 ) -> Result<Vec<ProofTrieNode>, StateProofError> {
1640 self.hashed_cursor.set_hashed_address(hashed_address);
1641
1642 if self.hashed_cursor.is_storage_empty()? {
1643 return Ok(vec![ProofTrieNode::empty()]);
1644 }
1645
1646 self.trie_cursor.set_hashed_address(hashed_address);
1649
1650 let mut storage_value_encoder = StorageValueEncoder;
1652 self.root_nodes(&mut storage_value_encoder)
1653 }
1654
1655 pub fn storage_root(&mut self, hashed_address: B256) -> Result<B256, StateProofError> {
1657 let root_node = self.storage_root_node(hashed_address)?;
1658 Ok(self
1659 .compute_root_hash(core::slice::from_ref(&root_node))?
1660 .expect("storage_root_node returns a node at empty path"))
1661 }
1662}
1663
1664#[derive(Clone)]
1670struct TargetsCursor<'a> {
1671 targets: &'a [ProofV2Target],
1672 i: usize,
1673}
1674
1675impl<'a> TargetsCursor<'a> {
1676 fn new(targets: &'a [ProofV2Target]) -> Self {
1682 debug_assert!(!targets.is_empty());
1683 Self { targets, i: 0 }
1684 }
1685
1686 fn current(&self) -> (&'a ProofV2Target, Option<&'a ProofV2Target>) {
1688 (&self.targets[self.i], self.targets.get(self.i + 1))
1689 }
1690
1691 fn next(&mut self) -> (&'a ProofV2Target, Option<&'a ProofV2Target>) {
1697 self.i += 1;
1698 debug_assert!(self.i < self.targets.len());
1699 self.current()
1700 }
1701
1702 fn skip_iter(&self) -> impl Iterator<Item = &'a ProofV2Target> {
1704 self.targets[self.i + 1..].iter()
1705 }
1706
1707 fn rev_iter(&self) -> impl Iterator<Item = &'a ProofV2Target> {
1710 self.targets[..self.i].iter().rev()
1711 }
1712}
1713
1714#[derive(Debug)]
1717enum TrieCursorState {
1718 Unseeked,
1720 Available(Nibbles, BranchNodeCompact),
1722 Taken(Nibbles),
1724 Exhausted(Nibbles),
1726}
1727
1728impl TrieCursorState {
1729 const fn unseeked() -> Self {
1731 Self::Unseeked
1732 }
1733
1734 fn seeked(key: Nibbles, entry: Option<(Nibbles, BranchNodeCompact)>) -> Self {
1736 entry.map_or(Self::Exhausted(key), |(path, node)| Self::Available(path, node))
1737 }
1738
1739 const fn path(&self) -> Option<&Nibbles> {
1745 match self {
1746 Self::Unseeked => panic!("cursor is unseeked"),
1747 Self::Available(path, _) | Self::Taken(path) => Some(path),
1748 Self::Exhausted(_) => None,
1749 }
1750 }
1751
1752 fn needs_seek_to(&self, path: &Nibbles) -> bool {
1754 match self {
1755 Self::Unseeked | Self::Taken(_) => true,
1756 Self::Available(current_path, _) => current_path < path,
1757 Self::Exhausted(_) => false,
1758 }
1759 }
1760
1761 fn needs_reset_before_seek(&self, key: &Nibbles) -> bool {
1763 match self {
1764 Self::Unseeked => false,
1765 Self::Available(path, _) | Self::Taken(path) => path > key,
1766 Self::Exhausted(exhausted_at) => exhausted_at > key,
1767 }
1768 }
1769
1770 fn take(&mut self) -> (Nibbles, BranchNodeCompact) {
1772 let Self::Available(path, _) = self else {
1773 panic!("take called on non-Available: {self:?}")
1774 };
1775
1776 let path = *path;
1777 let Self::Available(path, node) = core::mem::replace(self, Self::Taken(path)) else {
1778 unreachable!("already checked that self is Self::Available");
1779 };
1780
1781 (path, node)
1782 }
1783}
1784
1785enum HashedCursorState<V> {
1787 Unseeked,
1789 Available(Nibbles, V),
1791 Exhausted(Nibbles),
1793}
1794
1795impl<V> HashedCursorState<V> {
1796 const fn unseeked() -> Self {
1798 Self::Unseeked
1799 }
1800
1801 fn seeked(key: Nibbles, entry: Option<(Nibbles, V)>) -> Self {
1803 entry.map_or(Self::Exhausted(key), |(path, value)| Self::Available(path, value))
1804 }
1805
1806 const fn path(&self) -> Option<&Nibbles> {
1808 match self {
1809 Self::Available(path, _) => Some(path),
1810 Self::Unseeked | Self::Exhausted(_) => None,
1811 }
1812 }
1813
1814 fn needs_seek_to(&self, key: &Nibbles) -> bool {
1816 match self {
1817 Self::Unseeked => true,
1818 Self::Available(path, _) => path < key,
1819 Self::Exhausted(exhausted_at) => exhausted_at > key,
1820 }
1821 }
1822
1823 fn needs_reset_before_seek(&self, key: &Nibbles) -> bool {
1825 match self {
1826 Self::Unseeked => false,
1827 Self::Available(path, _) => path > key,
1828 Self::Exhausted(exhausted_at) => exhausted_at >= key,
1829 }
1830 }
1831
1832 fn take(&mut self) -> (Nibbles, V) {
1834 match core::mem::replace(self, Self::Unseeked) {
1835 Self::Available(path, value) => (path, value),
1836 _ => panic!("take called on non-Available hashed cursor state"),
1837 }
1838 }
1839}
1840
1841enum PopCachedBranchOutcome {
1843 Popped((Nibbles, BranchNodeCompact)),
1845 Exhausted,
1847 CalculateLeaves((Nibbles, Option<Nibbles>)),
1850}
1851
1852#[cfg(test)]
1853mod tests {
1854 use super::*;
1855 use crate::{
1856 hashed_cursor::{
1857 mock::MockHashedCursorFactory, noop::NoopHashedCursor, HashedCursorFactory,
1858 HashedPostStateCursor,
1859 },
1860 proof::StorageProof as LegacyStorageProof,
1861 test_utils::TrieTestHarness,
1862 trie_cursor::{
1863 depth_first, noop::NoopStorageTrieCursor, InMemoryTrieCursor, TrieCursorFactory,
1864 },
1865 };
1866 use alloy_primitives::map::B256Set;
1867 use alloy_rlp::Decodable;
1868 use alloy_trie::proof::AddedRemovedKeys;
1869 use itertools::Itertools;
1870 use rand::prelude::*;
1871 use reth_trie_common::{
1872 prefix_set::{PrefixSet, PrefixSetMut},
1873 updates::TrieUpdatesSorted,
1874 HashedPostState, HashedStorage, ProofV2TargetParent, EMPTY_ROOT_HASH,
1875 };
1876 use std::collections::BTreeMap;
1877
1878 fn project_legacy_proof_node(
1880 node: &ProofTrieNode,
1881 target: &ProofV2Target,
1882 ) -> Option<ProofTrieNode> {
1883 let Some(parent_path_len) = target.parent.path_len() else {
1884 return target.key_nibbles.starts_with(&node.path).then(|| node.clone())
1885 };
1886
1887 if node.path.len() > parent_path_len {
1888 return target.key_nibbles.starts_with(&node.path).then(|| node.clone())
1889 }
1890
1891 let logical_path = match &node.node {
1892 TrieNode::Leaf(leaf) => node.path.join(&leaf.key),
1893 TrieNode::Extension(ext) => node.path.join(&ext.key),
1894 TrieNode::EmptyRoot | TrieNode::Branch(_) => return None,
1895 };
1896 let child_path_len = parent_path_len + 1;
1897 if logical_path.len() < child_path_len {
1898 return None
1899 }
1900
1901 let child_path = logical_path.slice(0..child_path_len);
1902 if !target.key_nibbles.starts_with(&child_path) {
1903 return None
1904 }
1905
1906 let trim_len = child_path_len - node.path.len();
1907 let mut projected = node.clone();
1908 projected.path = child_path;
1909 match &mut projected.node {
1910 TrieNode::Leaf(leaf) => leaf.key = leaf.key.slice(trim_len..),
1911 TrieNode::Extension(ext) => {
1912 if ext.key.len() == trim_len {
1914 return None;
1915 }
1916 ext.key = ext.key.slice(trim_len..);
1917 }
1918 TrieNode::EmptyRoot | TrieNode::Branch(_) => unreachable!(),
1919 }
1920 Some(projected)
1921 }
1922
1923 fn project_legacy_proof(
1925 legacy_nodes: &[ProofTrieNode],
1926 targets: &[ProofV2Target],
1927 ) -> Vec<ProofTrieNode> {
1928 let mut projected = targets
1929 .iter()
1930 .flat_map(|target| {
1931 legacy_nodes.iter().filter_map(move |node| project_legacy_proof_node(node, target))
1932 })
1933 .collect::<Vec<_>>();
1934 let branches = projected
1937 .iter()
1938 .filter_map(|node| {
1939 let TrieNode::Extension(extension) = &node.node else { return None };
1940 let branch_path = node.path.join(&extension.key);
1941 legacy_nodes.iter().find(|node| node.path == branch_path).cloned()
1942 })
1943 .collect::<Vec<_>>();
1944 projected.extend(branches);
1945 projected.sort_unstable_by(|a, b| depth_first::cmp(&a.path, &b.path));
1946 projected.dedup_by(|a, b| {
1947 if a.path != b.path {
1948 return false
1949 }
1950 assert_eq!(a, b, "target projections disagree at path {:?}", a.path);
1951 true
1952 });
1953 projected
1954 }
1955
1956 struct ProofTestHarness {
1962 inner: TrieTestHarness,
1963 }
1964
1965 impl std::ops::Deref for ProofTestHarness {
1966 type Target = TrieTestHarness;
1967 fn deref(&self) -> &Self::Target {
1968 &self.inner
1969 }
1970 }
1971
1972 impl ProofTestHarness {
1973 fn new(storage: BTreeMap<B256, U256>) -> Self {
1975 Self { inner: TrieTestHarness::new(storage) }
1976 }
1977
1978 fn root_with_prefix_set(&self, prefix_set: PrefixSet) -> Option<B256> {
1980 let trie_cursor =
1981 self.trie_cursor_factory().storage_trie_cursor(self.hashed_address()).unwrap();
1982 let hashed_cursor =
1983 self.hashed_cursor_factory().hashed_storage_cursor(self.hashed_address()).unwrap();
1984 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
1985 .with_prefix_set(prefix_set);
1986
1987 let mut targets = [ProofV2Target::new(B256::ZERO)];
1988 let proof = calculator.storage_proof(self.hashed_address(), &mut targets).unwrap();
1989 calculator.compute_root_hash(&proof).unwrap()
1990 }
1991
1992 fn assert_proof(
1995 &self,
1996 targets: impl IntoIterator<Item = ProofV2Target>,
1997 ) -> Result<(), StateProofError> {
1998 let mut targets_vec = targets.into_iter().collect::<Vec<_>>();
1999
2000 let (proof_v2_result, root_hash) = self.proof_v2(&mut targets_vec);
2002
2003 if let Some(root_hash) = root_hash {
2006 pretty_assertions::assert_eq!(self.original_root(), root_hash);
2007 }
2008
2009 let legacy_targets = targets_vec
2012 .iter()
2013 .map(|target| B256::from_slice(&target.key_nibbles.pack()))
2014 .chain(self.storage().keys().copied())
2015 .collect::<B256Set>();
2016
2017 let proof_legacy_result = LegacyStorageProof::new_hashed(
2019 self.trie_cursor_factory(),
2020 self.hashed_cursor_factory(),
2021 self.hashed_address(),
2022 )
2023 .with_branch_node_masks(true)
2024 .with_added_removed_keys(Some(AddedRemovedKeys::default().with_assume_added(true)))
2025 .storage_multiproof(legacy_targets)?;
2026
2027 let proof_legacy_nodes = proof_legacy_result
2029 .subtree
2030 .iter()
2031 .map(|(path, node_enc)| {
2032 let mut buf = node_enc.as_ref();
2033 let node = TrieNode::decode(&mut buf)
2034 .expect("legacy implementation should not produce malformed proof nodes");
2035
2036 let masks = if path.is_empty() {
2037 None
2038 } else {
2039 proof_legacy_result.branch_node_masks.get(path).copied()
2040 };
2041
2042 ProofTrieNode { path: *path, node, masks }
2043 })
2044 .sorted_by(|a, b| depth_first::cmp(&a.path, &b.path))
2045 .collect::<Vec<_>>();
2046
2047 let expected_v2 = project_legacy_proof(&proof_legacy_nodes, &targets_vec);
2048 pretty_assertions::assert_eq!(expected_v2, proof_v2_result);
2049
2050 Ok(())
2051 }
2052 }
2053
2054 #[reth_concurrency::test]
2059 fn test_proof_calculator_reuse_after_error() {
2060 reth_tracing::init_test_tracing();
2061
2062 let slots = [
2063 B256::right_padding_from(&[0x10]),
2064 B256::right_padding_from(&[0x20]),
2065 B256::right_padding_from(&[0x30]),
2066 B256::right_padding_from(&[0x40]),
2067 ];
2068 let storage: BTreeMap<B256, U256> =
2069 slots.iter().map(|&s| (s, U256::from(100u64))).collect();
2070
2071 let harness = ProofTestHarness::new(storage);
2072
2073 let trie_cursor_factory = harness.trie_cursor_factory();
2074 let hashed_cursor_factory = harness.hashed_cursor_factory();
2075
2076 let hashed_address = harness.hashed_address();
2077 let trie_cursor = trie_cursor_factory.storage_trie_cursor(hashed_address).unwrap();
2078 let hashed_cursor = hashed_cursor_factory.hashed_storage_cursor(hashed_address).unwrap();
2079 let mut proof_calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor);
2080
2081 proof_calculator
2084 .branch_stack
2085 .push(ProofTrieBranch { ext_len: 2, state_mask: TrieMask::new(0b1111) });
2086 proof_calculator
2087 .branch_stack
2088 .push(ProofTrieBranch { ext_len: 0, state_mask: TrieMask::new(0b11) });
2089 proof_calculator.child_stack.push(ProofTrieBranchChild::RlpNode {
2090 node: RlpNode::word_rlp(&B256::ZERO),
2091 short_key: Nibbles::new(),
2092 hash_mask_bit: false,
2093 tree_mask_bit: false,
2094 });
2095 proof_calculator.branch_path = Nibbles::from_nibbles([0x1, 0x2, 0x3]);
2096
2097 proof_calculator.clear_computation_state();
2099
2100 let mut sorted_slots = slots.to_vec();
2101 sorted_slots.sort();
2102 let mut targets: Vec<ProofV2Target> =
2103 sorted_slots.iter().copied().map(ProofV2Target::new).collect();
2104
2105 let result = proof_calculator.storage_proof(hashed_address, &mut targets).unwrap();
2106
2107 let trie_cursor = trie_cursor_factory.storage_trie_cursor(hashed_address).unwrap();
2109 let hashed_cursor = hashed_cursor_factory.hashed_storage_cursor(hashed_address).unwrap();
2110 let mut fresh_calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor);
2111 let fresh_result = fresh_calculator.storage_proof(hashed_address, &mut targets).unwrap();
2112
2113 pretty_assertions::assert_eq!(fresh_result, result);
2114 }
2115
2116 #[reth_concurrency::test]
2117 fn test_root_node_reuse_with_overlay() {
2118 let storage = BTreeMap::from([
2119 (B256::right_padding_from(&[0x10]), U256::ONE),
2120 (B256::right_padding_from(&[0x20]), U256::from(2)),
2121 ]);
2122 let harness = ProofTestHarness::new(storage.clone());
2123 let hashed_address = harness.hashed_address();
2124 let post_state =
2125 HashedPostState::from_hashed_storage(hashed_address, HashedStorage::from_iter(storage))
2126 .into_sorted();
2127 let trie_updates = TrieUpdatesSorted::default();
2128 let trie_cursor = InMemoryTrieCursor::new_storage(
2129 NoopStorageTrieCursor::default(),
2130 &trie_updates,
2131 hashed_address,
2132 );
2133 let hashed_cursor = HashedPostStateCursor::new_storage(
2134 NoopHashedCursor::default(),
2135 &post_state,
2136 hashed_address,
2137 );
2138 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor);
2139
2140 let first_root = calculator.root_node(&mut StorageValueEncoder).unwrap();
2141 assert!(matches!(first_root.node, TrieNode::Branch(_)));
2142 assert_eq!(
2143 calculator.compute_root_hash(core::slice::from_ref(&first_root)).unwrap(),
2144 Some(harness.original_root())
2145 );
2146
2147 let second_root = calculator.root_node(&mut StorageValueEncoder).unwrap();
2148 pretty_assertions::assert_eq!(first_root, second_root);
2149 }
2150
2151 #[reth_concurrency::test]
2152 fn test_partial_storage_proof_after_root_calculation() {
2153 let slot_a = B256::right_padding_from(&[0xae, 0xd4, 0x00]);
2154 let slot_b = B256::right_padding_from(&[0xae, 0xd4, 0x10]);
2155 let harness =
2156 ProofTestHarness::new(BTreeMap::from([(slot_a, U256::ONE), (slot_b, U256::from(2))]));
2157 let hashed_address = harness.hashed_address();
2158 let trie_cursor =
2159 harness.trie_cursor_factory().storage_trie_cursor(hashed_address).unwrap();
2160 let hashed_cursor =
2161 harness.hashed_cursor_factory().hashed_storage_cursor(hashed_address).unwrap();
2162 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor);
2163
2164 let root_node = calculator.storage_root_node(hashed_address).unwrap();
2165 assert_eq!(
2166 calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap(),
2167 Some(harness.original_root())
2168 );
2169
2170 let target = ProofV2Target::new(slot_a).with_parent(ProofV2TargetParent::new(3));
2171 let mut actual_targets = [target];
2172 let actual = calculator.storage_proof(hashed_address, &mut actual_targets).unwrap();
2173 let mut expected_targets = [target];
2174 let (expected, root) = harness.proof_v2(&mut expected_targets);
2175
2176 assert!(root.is_none());
2177 pretty_assertions::assert_eq!(expected, actual);
2178 }
2179
2180 mod proptest_tests {
2181 use super::*;
2182 use proptest::prelude::*;
2183
2184 fn storage_strategy() -> impl Strategy<Value = BTreeMap<B256, U256>> {
2186 prop::collection::vec((any::<[u8; 32]>(), any::<u64>()), 0..=100).prop_map(|slots| {
2187 slots
2188 .into_iter()
2189 .map(|(slot_bytes, value)| (B256::from(slot_bytes), U256::from(value)))
2190 .filter(|(_, v)| !v.is_zero())
2191 .collect()
2192 })
2193 }
2194
2195 fn proof_targets_strategy(
2198 slot_keys: Vec<B256>,
2199 ) -> impl Strategy<Value = Vec<ProofV2Target>> {
2200 let num_slots = slot_keys.len();
2201
2202 let target_count = 0..=(num_slots + 5);
2203
2204 target_count.prop_flat_map(move |count| {
2205 let slot_keys = slot_keys.clone();
2206 prop::collection::vec(
2207 (
2208 prop::bool::weighted(0.8).prop_flat_map(move |from_slots| {
2209 if from_slots && !slot_keys.is_empty() {
2210 prop::sample::select(slot_keys.clone()).boxed()
2211 } else {
2212 any::<[u8; 32]>().prop_map(B256::from).boxed()
2213 }
2214 }),
2215 0u8..16u8,
2216 )
2217 .prop_map(|(key, encoded_parent_path_len)| {
2218 let parent = encoded_parent_path_len.checked_sub(1).map_or(
2219 ProofV2TargetParent::NONE,
2220 |parent_path_len| {
2221 ProofV2TargetParent::new(usize::from(parent_path_len))
2222 },
2223 );
2224 ProofV2Target::new(key).with_parent(parent)
2225 }),
2226 count,
2227 )
2228 })
2229 }
2230
2231 fn dirty_key_strategy() -> impl Strategy<Value = B256> {
2232 prop::array::uniform8(0u8..4).prop_map(|nibbles| {
2234 B256::right_padding_from(&Nibbles::from_nibbles(nibbles).pack())
2235 })
2236 }
2237
2238 proptest! {
2239 #![proptest_config(ProptestConfig::with_cases(4000))]
2240 #[reth_concurrency::test]
2241 fn proptest_proof_with_targets(
2244 (storage, targets) in storage_strategy()
2245 .prop_flat_map(|storage| {
2246 let mut slot_keys: Vec<B256> = storage.keys().copied().collect();
2247 slot_keys.sort_unstable();
2248 let targets_strategy = proof_targets_strategy(slot_keys);
2249 (Just(storage), targets_strategy)
2250 })
2251 ) {
2252 reth_tracing::init_test_tracing();
2253 let harness = ProofTestHarness::new(storage);
2254
2255 harness.assert_proof(targets).expect("Proof generation failed");
2256 }
2257
2258 #[reth_concurrency::test]
2259 fn proptest_proof_with_dirty_prefixes(
2260 before in prop::collection::btree_map(dirty_key_strategy(), 1u64..100, 0..80),
2261 changes in prop::collection::btree_map(dirty_key_strategy(), 0u64..100, 0..8),
2262 retain_unchanged in any::<bool>(),
2263 target_indices in prop::collection::vec((0usize..100, 0usize..9), 0..10),
2264 ) {
2265 let before = before.into_iter()
2266 .map(|(key, value)| (key, U256::from(value)))
2267 .collect::<BTreeMap<_, _>>();
2268 let mut after = if retain_unchanged { before.clone() } else { BTreeMap::new() };
2269 for (key, value) in changes {
2270 if value == 0 {
2271 after.remove(&key);
2272 } else {
2273 after.insert(key, U256::from(value));
2274 }
2275 }
2276 let prefix_set = PrefixSetMut::from(
2277 before.keys().chain(after.keys())
2278 .filter(|key| before.get(*key) != after.get(*key))
2279 .map(Nibbles::unpack),
2280 ).freeze();
2281 let expected_root = crate::test_utils::storage_root_prehashed(
2282 after.iter().map(|(key, value)| (*key, *value)),
2283 );
2284 let mut targets = vec![ProofV2Target::new(B256::ZERO)];
2285 let keys = before.keys().chain(after.keys()).copied().collect::<Vec<_>>();
2286 if !keys.is_empty() {
2287 for (index, len) in target_indices {
2288 targets.push(ProofV2Target::new(keys[index % keys.len()])
2289 .with_parent(ProofV2TargetParent::new(len)));
2290 }
2291 }
2292 let harness = TrieTestHarness::new(before);
2293 let hashed_factory = MockHashedCursorFactory::new(
2294 BTreeMap::new(),
2295 std::iter::once((harness.hashed_address(), after)).collect(),
2296 );
2297 let trie_cursor = harness.trie_cursor_factory()
2298 .storage_trie_cursor(harness.hashed_address()).unwrap();
2299 let hashed_cursor = hashed_factory
2300 .hashed_storage_cursor(harness.hashed_address()).unwrap();
2301 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
2302 .with_prefix_set(prefix_set);
2303 let proof = calculator.storage_proof(harness.hashed_address(), &mut targets).unwrap();
2304
2305 prop_assert_eq!(calculator.compute_root_hash(&proof).unwrap(), Some(expected_root));
2306 }
2307 }
2308 }
2309
2310 #[reth_concurrency::test]
2311 fn test_exact_subtrie_targets_with_root_target() {
2312 reth_tracing::init_test_tracing();
2313
2314 let slot_80 = B256::right_padding_from(&[0x80]);
2315 let slot_82 = B256::right_padding_from(&[0x82]);
2316 let slot_f0 = B256::right_padding_from(&[0xf0]);
2317 let storage = BTreeMap::from([
2318 (slot_80, U256::ONE),
2319 (slot_82, U256::from(2)),
2320 (slot_f0, U256::from(3)),
2321 ]);
2322 let targets = [
2323 ProofV2Target::new(B256::ZERO),
2324 ProofV2Target::new(slot_80).with_parent(ProofV2TargetParent::new(1)),
2325 ];
2326
2327 let harness = ProofTestHarness::new(storage);
2328 harness.assert_proof(targets).expect("Proof generation failed");
2329 }
2330
2331 #[reth_concurrency::test]
2332 fn test_rebases_singleton_subtrie_root_below_known_parent() {
2333 let slot = B256::right_padding_from(&[0xae, 0xd4, 0x09]);
2334 let slot_nibbles = Nibbles::unpack(slot);
2335 let harness = ProofTestHarness::new(BTreeMap::from([(slot, U256::ONE)]));
2336 let mut targets = [ProofV2Target::new(slot).with_parent(ProofV2TargetParent::new(3))];
2337
2338 let (proof, root) = harness.proof_v2(&mut targets);
2339
2340 assert!(root.is_none());
2341 assert_eq!(proof.len(), 1);
2342 assert_eq!(proof[0].path, slot_nibbles.slice(0..4));
2343 let TrieNode::Leaf(leaf) = &proof[0].node else {
2344 panic!("singleton subtrie root should remain a leaf")
2345 };
2346 assert_eq!(leaf.key, slot_nibbles.slice(4..));
2347 }
2348
2349 #[reth_concurrency::test]
2350 fn test_rebases_singleton_leaf_at_max_parent_depth() {
2351 let slot = B256::repeat_byte(0xae);
2352 let slot_nibbles = Nibbles::unpack(slot);
2353 let harness = ProofTestHarness::new(BTreeMap::from([(slot, U256::ONE)]));
2354 let mut targets = [ProofV2Target::new(slot).with_parent(ProofV2TargetParent::new(63))];
2355
2356 let (proof, root) = harness.proof_v2(&mut targets);
2357
2358 assert!(root.is_none());
2359 assert_eq!(proof.len(), 1);
2360 assert_eq!(proof[0].path, slot_nibbles);
2361 let TrieNode::Leaf(leaf) = &proof[0].node else {
2362 panic!("singleton subtrie root should remain a leaf")
2363 };
2364 assert!(leaf.key.is_empty());
2365 }
2366
2367 #[reth_concurrency::test]
2368 fn test_root_and_root_parent_targets_retain_both_singleton_representations() {
2369 let slot = B256::right_padding_from(&[0x20]);
2370 let slot_nibbles = Nibbles::unpack(slot);
2371 let harness = ProofTestHarness::new(BTreeMap::from([(slot, U256::ONE)]));
2372 let mut targets = [
2373 ProofV2Target::new(slot),
2374 ProofV2Target::new(slot).with_parent(ProofV2TargetParent::new(0)),
2375 ];
2376
2377 let (proof, root) = harness.proof_v2(&mut targets);
2378
2379 assert_eq!(root, Some(harness.original_root()));
2380 let root_node = proof.iter().find(|node| node.path.is_empty()).expect("root proof");
2381 let TrieNode::Leaf(root_leaf) = &root_node.node else { panic!("root should be a leaf") };
2382 assert_eq!(root_leaf.key, slot_nibbles);
2383
2384 let child_path = slot_nibbles.slice(0..1);
2385 let child_node =
2386 proof.iter().find(|node| node.path == child_path).expect("rebased root child proof");
2387 let TrieNode::Leaf(child_leaf) = &child_node.node else {
2388 panic!("root child should be a leaf")
2389 };
2390 assert_eq!(child_leaf.key, slot_nibbles.slice(1..));
2391 }
2392
2393 #[reth_concurrency::test]
2394 fn test_exhausted_cursor_resets_at_equal_target_boundary() {
2395 let first = B256::ZERO;
2396 let last = B256::with_last_byte(1);
2397 let last_nibbles = Nibbles::unpack(last);
2398 let harness =
2399 ProofTestHarness::new(BTreeMap::from([(first, U256::ONE), (last, U256::from(2))]));
2400 let mut targets = [
2401 ProofV2Target::new(first),
2402 ProofV2Target::new(last).with_parent(ProofV2TargetParent::new(63)),
2403 ];
2404
2405 let (proof, root) = harness.proof_v2(&mut targets);
2406
2407 assert_eq!(root, Some(harness.original_root()));
2408 let child = proof
2409 .iter()
2410 .find(|node| node.path == last_nibbles)
2411 .expect("depth-63 target child proof");
2412 let TrieNode::Leaf(leaf) = &child.node else { panic!("target child should be a leaf") };
2413 assert!(leaf.key.is_empty());
2414 }
2415
2416 #[reth_concurrency::test]
2417 fn test_rebases_compressed_branch_subtrie_root() {
2418 let slot_a = B256::right_padding_from(&[0xae, 0xd4, 0x00]);
2419 let slot_b = B256::right_padding_from(&[0xae, 0xd4, 0x10]);
2420 let slot_nibbles = Nibbles::unpack(slot_a);
2421 let harness =
2422 ProofTestHarness::new(BTreeMap::from([(slot_a, U256::ONE), (slot_b, U256::from(2))]));
2423 let mut targets = [ProofV2Target::new(slot_a).with_parent(ProofV2TargetParent::new(3))];
2424
2425 let (proof, root) = harness.proof_v2(&mut targets);
2426
2427 assert!(root.is_none());
2428 let branch_path = slot_nibbles.slice(0..4);
2429 let branch_node =
2430 proof.iter().find(|node| node.path == branch_path).expect("rebased compressed branch");
2431 let TrieNode::Branch(_) = &branch_node.node else {
2432 panic!("rebased node should be a branch")
2433 };
2434 }
2435
2436 #[reth_concurrency::test]
2437 fn test_known_parent_retains_child() {
2438 let slot_a = B256::right_padding_from(&[0xae, 0xd2]);
2439 let slot_b = B256::right_padding_from(&[0xae, 0xd4]);
2440 let slot_nibbles = Nibbles::unpack(slot_a);
2441 let harness =
2442 ProofTestHarness::new(BTreeMap::from([(slot_a, U256::ONE), (slot_b, U256::from(2))]));
2443 let mut targets = [ProofV2Target::new(slot_a).with_parent(ProofV2TargetParent::new(3))];
2444
2445 let (proof, root) = harness.proof_v2(&mut targets);
2446
2447 assert!(root.is_none());
2448 assert!(!proof.iter().any(|node| node.path == slot_nibbles.slice(0..3)));
2449 assert!(proof.iter().any(|node| node.path == slot_nibbles.slice(0..4)));
2450 }
2451
2452 #[reth_concurrency::test]
2453 fn test_rebased_root_matches_direct_child_not_full_short_key() {
2454 let stored_slot = B256::right_padding_from(&[0xae, 0xd4, 0x09]);
2455 let same_child_target = B256::right_padding_from(&[0xae, 0xd4, 0xff]);
2456 let other_child_target = B256::right_padding_from(&[0xae, 0xd5]);
2457 let harness = ProofTestHarness::new(BTreeMap::from([(stored_slot, U256::ONE)]));
2458
2459 let mut same_child =
2460 [ProofV2Target::new(same_child_target).with_parent(ProofV2TargetParent::new(3))];
2461 let (proof, _) = harness.proof_v2(&mut same_child);
2462 assert_eq!(proof.len(), 1, "divergent leaf proves absence below the same child");
2463
2464 let mut other_child =
2465 [ProofV2Target::new(other_child_target).with_parent(ProofV2TargetParent::new(3))];
2466 let (proof, _) = harness.proof_v2(&mut other_child);
2467 assert!(proof.is_empty(), "a different direct child is unrelated to the target");
2468 }
2469
2470 #[reth_concurrency::test]
2471 fn test_known_parent_separate_child_ranges() {
2472 let stored_slot_a = B256::right_padding_from(&[0xea, 0x53]);
2473 let stored_slot_b = B256::right_padding_from(&[0xeb, 0x53]);
2474 let stored_slot_c = B256::right_padding_from(&[0xec, 0x53]);
2475 let target_a = B256::right_padding_from(&[0xea, 0x1f]);
2476 let target_c = B256::right_padding_from(&[0xec, 0x1f]);
2477 let harness = ProofTestHarness::new(BTreeMap::from([
2478 (stored_slot_a, U256::ONE),
2479 (stored_slot_b, U256::from(2)),
2480 (stored_slot_c, U256::from(3)),
2481 ]));
2482 let mut targets = [target_a, target_c]
2483 .map(|target| ProofV2Target::new(target).with_parent(ProofV2TargetParent::new(1)));
2484
2485 let (proof, root) = harness.proof_v2(&mut targets);
2486
2487 assert!(root.is_none());
2488 assert_eq!(
2489 proof.iter().map(|node| node.path).collect::<Vec<_>>(),
2490 [Nibbles::from_nibbles([0xe, 0xa]), Nibbles::from_nibbles([0xe, 0xc])]
2491 );
2492 }
2493
2494 #[reth_concurrency::test]
2495 fn test_known_parent_does_not_use_stale_parent_mask() {
2496 let stored_slot_a = B256::right_padding_from(&[0xea, 0x53]);
2497 let stored_slot = B256::right_padding_from(&[0xeb, 0x53]);
2498 let stored_slot_c = B256::right_padding_from(&[0xec, 0x53]);
2499 let target = B256::right_padding_from(&[0xeb, 0x1f]);
2500 let stored_slot_nibbles = Nibbles::unpack(stored_slot);
2501
2502 let stale_parent_mask = TrieMask::new((1 << 0xa) | (1 << 0xc));
2506 let stale_parent = BranchNodeCompact::new(
2507 stale_parent_mask,
2508 TrieMask::new(0),
2509 TrieMask::new(0),
2510 Vec::new(),
2511 None,
2512 );
2513 let storage_nodes = BTreeMap::from([(Nibbles::from_nibbles([0xe]), stale_parent)]);
2514
2515 let mut harness = TrieTestHarness::new(BTreeMap::from([
2516 (stored_slot_a, U256::ONE),
2517 (stored_slot, U256::from(2)),
2518 (stored_slot_c, U256::from(3)),
2519 ]));
2520 harness.set_trie_nodes(storage_nodes);
2521
2522 let mut targets = [ProofV2Target::new(target).with_parent(ProofV2TargetParent::new(1))];
2523 let (proof, root) = harness.proof_v2(&mut targets);
2524
2525 assert!(root.is_none());
2526 assert_eq!(proof.len(), 1);
2527 assert_eq!(proof[0].path, stored_slot_nibbles.slice(0..2));
2528 let TrieNode::Leaf(leaf) = &proof[0].node else {
2529 panic!("live direct child should be reconstructed as a leaf")
2530 };
2531 assert_eq!(leaf.key, stored_slot_nibbles.slice(2..));
2532 }
2533
2534 #[reth_concurrency::test]
2535 fn test_empty_storage_respects_parent_context() {
2536 let harness = ProofTestHarness::new(BTreeMap::new());
2537 let slot = B256::ZERO;
2538
2539 let mut partial_target =
2540 [ProofV2Target::new(slot).with_parent(ProofV2TargetParent::new(0))];
2541 let (partial_proof, partial_root) = harness.proof_v2(&mut partial_target);
2542 assert!(partial_proof.is_empty());
2543 assert!(partial_root.is_none());
2544
2545 let mut root_target = [ProofV2Target::new(slot)];
2546 let (root_proof, root) = harness.proof_v2(&mut root_target);
2547 assert_eq!(root_proof.len(), 1);
2548 assert!(matches!(root_proof[0].node, TrieNode::EmptyRoot));
2549 assert_eq!(root, Some(EMPTY_ROOT_HASH));
2550 }
2551
2552 #[reth_concurrency::test]
2553 fn test_big_trie() {
2554 reth_tracing::init_test_tracing();
2555
2556 let mut rng = rand::rngs::SmallRng::seed_from_u64(1);
2557
2558 let mut rand_b256 = || {
2559 let mut buf: [u8; 32] = [0; 32];
2560 rng.fill_bytes(&mut buf);
2561 B256::from_slice(&buf)
2562 };
2563
2564 let mut storage = BTreeMap::new();
2566 for _ in 0..10240 {
2567 let hashed_slot = rand_b256();
2568 storage.insert(hashed_slot, U256::ONE);
2569 }
2570
2571 let mut targets = storage.keys().copied().collect::<Vec<_>>();
2574 for _ in 0..storage.len() / 5 {
2575 targets.push(rand_b256());
2576 }
2577 targets.sort();
2578
2579 let harness = ProofTestHarness::new(storage);
2581
2582 harness
2583 .assert_proof(targets.into_iter().map(ProofV2Target::new))
2584 .expect("Proof generation failed");
2585 }
2586
2587 #[reth_concurrency::test]
2588 fn test_node_with_masked_empty_child() {
2589 reth_tracing::init_test_tracing();
2590
2591 let val = U256::from(42u64);
2592
2593 let slot_60 = B256::right_padding_from(&[0x60]);
2596 let slot_61 = B256::right_padding_from(&[0x61]);
2597 let slot_65 = B256::right_padding_from(&[0x65]);
2598 let slot_67 = B256::right_padding_from(&[0x67]);
2599
2600 let state_mask = TrieMask::new(0b10101011); let hash_mask = TrieMask::new(0b10100011); let hashes = vec![B256::repeat_byte(0xaa); hash_mask.count_ones() as usize];
2606 let branch = BranchNodeCompact::new(state_mask, TrieMask::new(0), hash_mask, hashes, None);
2607
2608 let storage_nodes: BTreeMap<Nibbles, BranchNodeCompact> =
2609 std::iter::once((Nibbles::from_nibbles([0x6]), branch)).collect();
2610
2611 let mut harness = TrieTestHarness::new(
2614 [slot_60, slot_61, slot_65, slot_67].iter().map(|s| (*s, val)).collect(),
2615 );
2616 harness.set_trie_nodes(storage_nodes);
2617
2618 let storage_trie_cursor =
2619 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2620 let hashed_storage_cursor = harness
2621 .hashed_cursor_factory()
2622 .hashed_storage_cursor(harness.hashed_address())
2623 .unwrap();
2624 let mut calculator =
2625 StorageProofCalculator::new_storage(storage_trie_cursor, hashed_storage_cursor);
2626 let root_node = calculator
2627 .storage_root_node(harness.hashed_address())
2628 .expect("storage_root_node should succeed with masked empty child");
2629
2630 let root_hash = calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap();
2631 assert!(root_hash.is_some(), "should produce a root hash");
2632 }
2633
2634 #[reth_concurrency::test]
2644 fn test_node_with_masked_empty_child_lower_bound_past_branch() {
2645 reth_tracing::init_test_tracing();
2646
2647 let val = U256::from(42u64);
2648
2649 let slot_60 = B256::right_padding_from(&[0x60]);
2651 let slot_61 = B256::right_padding_from(&[0x61]);
2652 let slot_6f = B256::right_padding_from(&[0x6f]);
2653 let slot_70 = B256::right_padding_from(&[0x70]);
2654
2655 let state_mask = TrieMask::new(0b1000_0000_0010_0011); let hash_mask = TrieMask::new(0b0000_0000_0000_0011); let hashes = vec![B256::repeat_byte(0xaa); hash_mask.count_ones() as usize];
2661 let branch = BranchNodeCompact::new(state_mask, TrieMask::new(0), hash_mask, hashes, None);
2662
2663 let storage_nodes: BTreeMap<Nibbles, BranchNodeCompact> =
2664 std::iter::once((Nibbles::from_nibbles([0x6]), branch)).collect();
2665
2666 let mut harness = TrieTestHarness::new(
2668 [slot_60, slot_61, slot_6f, slot_70].iter().map(|s| (*s, val)).collect(),
2669 );
2670 harness.set_trie_nodes(storage_nodes);
2671
2672 let storage_trie_cursor =
2673 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2674 let hashed_storage_cursor = harness
2675 .hashed_cursor_factory()
2676 .hashed_storage_cursor(harness.hashed_address())
2677 .unwrap();
2678 let mut calculator =
2679 StorageProofCalculator::new_storage(storage_trie_cursor, hashed_storage_cursor);
2680 let root_node = calculator
2681 .storage_root_node(harness.hashed_address())
2682 .expect("storage_root_node should succeed when lower bound advances past branch");
2683
2684 let root_hash = calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap();
2685 assert!(root_hash.is_some(), "should produce a root hash");
2686 }
2687
2688 #[reth_concurrency::test]
2698 fn test_prefix_set_adds_child_nibbles() {
2699 reth_tracing::init_test_tracing();
2700
2701 let val = U256::from(42u64);
2702 let slot_60 = B256::right_padding_from(&[0x60]);
2703 let slot_61 = B256::right_padding_from(&[0x61]);
2704 let slot_63 = B256::right_padding_from(&[0x63]);
2705
2706 let harness = TrieTestHarness::new([(slot_60, val), (slot_61, val)].into_iter().collect());
2707
2708 let changeset: BTreeMap<B256, U256> = std::iter::once((slot_63, val)).collect();
2709 let (expected_root, _) = harness.get_root_with_updates(&changeset);
2710
2711 let mut updated_storage = harness.storage().clone();
2712 updated_storage.insert(slot_63, val);
2713
2714 let updated_hashed = MockHashedCursorFactory::new(
2715 BTreeMap::new(),
2716 std::iter::once((harness.hashed_address(), updated_storage)).collect(),
2717 );
2718
2719 let mut prefix_set = PrefixSetMut::default();
2720 prefix_set.insert(Nibbles::unpack(slot_63));
2721
2722 let trie_cursor =
2723 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2724 let hashed_cursor = updated_hashed.hashed_storage_cursor(harness.hashed_address()).unwrap();
2725 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
2726 .with_prefix_set(prefix_set.freeze());
2727 let root_node = calculator
2728 .storage_root_node(harness.hashed_address())
2729 .expect("storage_root_node should succeed with prefix set adding child nibbles");
2730 let got_root =
2731 calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap().unwrap();
2732
2733 pretty_assertions::assert_eq!(
2734 expected_root,
2735 got_root,
2736 "Root hash with prefix set should match fresh computation"
2737 );
2738 }
2739
2740 #[reth_concurrency::test]
2749 fn test_prefix_set_invalidates_cached_hash() {
2750 reth_tracing::init_test_tracing();
2751
2752 let original_val = U256::from(42u64);
2753 let updated_val = U256::from(9999u64);
2754 let slot_60 = B256::right_padding_from(&[0x60]);
2755 let slot_61 = B256::right_padding_from(&[0x61]);
2756 let slot_65 = B256::right_padding_from(&[0x65]);
2757
2758 let harness = TrieTestHarness::new(
2759 [(slot_60, original_val), (slot_61, original_val), (slot_65, original_val)]
2760 .into_iter()
2761 .collect(),
2762 );
2763
2764 let changeset: BTreeMap<B256, U256> = std::iter::once((slot_65, updated_val)).collect();
2765 let (expected_root, _) = harness.get_root_with_updates(&changeset);
2766
2767 let mut updated_storage = harness.storage().clone();
2768 updated_storage.insert(slot_65, updated_val);
2769
2770 let updated_hashed = MockHashedCursorFactory::new(
2771 BTreeMap::new(),
2772 std::iter::once((harness.hashed_address(), updated_storage)).collect(),
2773 );
2774
2775 let mut prefix_set = PrefixSetMut::default();
2776 prefix_set.insert(Nibbles::unpack(slot_65));
2777
2778 let trie_cursor =
2779 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2780 let hashed_cursor = updated_hashed.hashed_storage_cursor(harness.hashed_address()).unwrap();
2781 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
2782 .with_prefix_set(prefix_set.freeze());
2783 let root_node = calculator
2784 .storage_root_node(harness.hashed_address())
2785 .expect("storage_root_node should succeed with prefix set invalidating cached hash");
2786 let got_root =
2787 calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap().unwrap();
2788
2789 pretty_assertions::assert_eq!(
2790 expected_root,
2791 got_root,
2792 "Root hash with prefix set invalidation should match fresh computation"
2793 );
2794 }
2795
2796 fn b256(s: &str) -> B256 {
2797 B256::from_slice(&alloy_primitives::hex::decode(s).expect("valid hex string"))
2798 }
2799
2800 #[reth_concurrency::test]
2801 fn test_prefix_set_root_proof_processes_sibling_after_cached_descendant() {
2802 reth_tracing::init_test_tracing();
2803
2804 let storage = [
2805 ("1022c69e9d900e40775cd387c134899f465f291dbc3c97899ff6bfb8dc972b37", 45u64),
2806 ("1111ad8083c8a3a398b2b781217b989ff4d1ed182f46cc765eda49a7b316139d", 60),
2807 ("12012d20943649899b2fc0f87b9840b70ef68e93613aac17c269bf8c5a78a712", 17),
2808 ("12014b57b9a162c03d072eb6acd4e936f1c4bc23b803a054347c5ee9a9bcfb9a", 49),
2809 ("1203f800840af3f898ab4572f2750106a7c4bd2b3e844b6e7fa72704673cc2c6", 76),
2810 ("12208f18fbcd6971c92808721392acbf11d5af58e9143a374cc86e70bdd1f097", 10),
2811 ]
2812 .into_iter()
2813 .map(|(key, value)| (b256(key), U256::from(value)))
2814 .collect();
2815
2816 let dirty = b256("12208f18fbcd6971c92808721392acbf11d5af58e9143a374cc86e70bdd1f097");
2817 let harness = ProofTestHarness::new(storage);
2818 let expected_root = harness.original_root();
2819
2820 let mut prefix_set = PrefixSetMut::default();
2821 prefix_set.insert(Nibbles::unpack(dirty));
2822
2823 pretty_assertions::assert_eq!(
2824 Some(expected_root),
2825 harness.root_with_prefix_set(prefix_set.freeze()),
2826 "root proof must process a prefix-set sibling after a cached descendant",
2827 );
2828 }
2829
2830 #[reth_concurrency::test]
2831 fn test_prefix_set_root_proof_processes_trailing_dirty_sibling() {
2832 reth_tracing::init_test_tracing();
2833
2834 let keys = [
2835 "0022001020000000000000000000000000000000000000000000000000000000",
2836 "0110212112000000000000000000000000000000000000000000000000000000",
2837 "0202210210000000000000000000000000000000000000000000000000000000",
2838 "0211020211000000000000000000000000000000000000000000000000000000",
2839 "0211211002000000000000000000000000000000000000000000000000000000",
2840 "0212221010000000000000000000000000000000000000000000000000000000",
2841 "0222011102000000000000000000000000000000000000000000000000000000",
2842 ];
2843 let storage =
2844 keys.iter().enumerate().map(|(i, key)| (b256(key), U256::from(i as u64 + 1))).collect();
2845 let harness = ProofTestHarness::new(storage);
2846 let expected_root = harness.original_root();
2847
2848 let mut prefix_set = PrefixSetMut::default();
2851 prefix_set.insert(Nibbles::unpack(b256(keys[2])));
2852 prefix_set.insert(Nibbles::unpack(b256(keys[6])));
2853
2854 pretty_assertions::assert_eq!(
2855 Some(expected_root),
2856 harness.root_with_prefix_set(prefix_set.freeze()),
2857 );
2858 }
2859
2860 #[reth_concurrency::test]
2861 fn test_prefix_set_preserves_cached_siblings() {
2862 let storage = (0..4096u16)
2863 .map(|key| (B256::right_padding_from(&key.to_be_bytes()), U256::from(1)))
2864 .collect();
2865 let harness = TrieTestHarness::new(storage);
2866 let changes = BTreeMap::from([
2867 (B256::right_padding_from(&[0x04, 0x00]), U256::from(2)),
2868 (B256::right_padding_from(&[0x04, 0xf0]), U256::from(2)),
2869 ]);
2870 let (expected_root, _) = harness.get_root_with_updates(&changes);
2871 let mut updated_storage = harness.storage().clone();
2872 updated_storage.extend(changes.clone());
2873 let hashed_factory = MockHashedCursorFactory::new(
2874 BTreeMap::new(),
2875 std::iter::once((harness.hashed_address(), updated_storage)).collect(),
2876 );
2877 let prefix_set = PrefixSetMut::from(changes.keys().map(Nibbles::unpack)).freeze();
2878 let trie_cursor =
2879 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2880 let hashed_cursor = hashed_factory.hashed_storage_cursor(harness.hashed_address()).unwrap();
2881 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
2882 .with_prefix_set(prefix_set);
2883 let mut targets = [ProofV2Target::new(B256::ZERO)];
2884 let proof = calculator.storage_proof(harness.hashed_address(), &mut targets).unwrap();
2885
2886 assert_eq!(calculator.compute_root_hash(&proof).unwrap(), Some(expected_root));
2887
2888 let clean_key = B256::right_padding_from(&[0x04, 0x88]);
2890 assert!(!hashed_factory
2891 .visited_storage_keys(harness.hashed_address())
2892 .iter()
2893 .any(|visit| visit.visited_key == Some(clean_key)));
2894 }
2895
2896 #[reth_concurrency::test]
2897 fn test_prefix_set_finishes_branch_before_returning_to_ancestor() {
2898 let storage =
2899 [[0x10, 0x00, 0x00], [0x12, 0x10, 0x00], [0x12, 0x10, 0x20], [0x12, 0x11, 0x00]]
2900 .into_iter()
2901 .map(|key| (B256::right_padding_from(&key), U256::from(1)))
2902 .collect();
2903 let harness = TrieTestHarness::new(storage);
2904 let changes = BTreeMap::from([
2905 (B256::right_padding_from(&[0x12, 0x00]), U256::from(1)),
2906 (B256::right_padding_from(&[0x12, 0x20]), U256::from(1)),
2907 ]);
2908 let mut after = harness.storage().clone();
2909 after.extend(changes.clone());
2910 let expected_root = crate::test_utils::storage_root_prehashed(
2911 after.iter().map(|(key, value)| (*key, *value)),
2912 );
2913 let hashed_factory = MockHashedCursorFactory::new(
2914 BTreeMap::new(),
2915 std::iter::once((harness.hashed_address(), after)).collect(),
2916 );
2917 let trie_cursor =
2918 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2919 let hashed_cursor = hashed_factory.hashed_storage_cursor(harness.hashed_address()).unwrap();
2920 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
2921 .with_prefix_set(PrefixSetMut::from(changes.keys().map(Nibbles::unpack)).freeze());
2922 let mut targets = [
2923 ProofV2Target::new(B256::ZERO),
2924 ProofV2Target::new(B256::right_padding_from(&[0x10]))
2925 .with_parent(ProofV2TargetParent::new(0)),
2926 ];
2927
2928 let proof = calculator.storage_proof(harness.hashed_address(), &mut targets).unwrap();
2930 assert_eq!(calculator.compute_root_hash(&proof).unwrap(), Some(expected_root));
2931 }
2932
2933 fn storage_leaf_hash(short_key: &Nibbles, value: &U256) -> B256 {
2936 let mut buf = Vec::new();
2937 alloy_trie::nodes::LeafNodeRef::new(short_key, &alloy_rlp::encode_fixed_size(value))
2938 .encode(&mut buf);
2939 keccak256(&buf)
2940 }
2941
2942 fn assert_branch_collapse(remaining_nibble: u8, removed_nibble: u8) {
2944 reth_tracing::init_test_tracing();
2945
2946 let val = U256::ONE;
2947 let child_keys = |nibble| {
2948 [
2949 B256::right_padding_from(&[0x20 | nibble, 0x00]),
2950 B256::right_padding_from(&[0x20 | nibble, 0x10]),
2951 ]
2952 };
2953 let [remaining_a, remaining_b] = child_keys(remaining_nibble);
2954 let [removed_a, removed_b] = child_keys(removed_nibble);
2955
2956 let initial_storage = BTreeMap::from([
2959 (remaining_a, val),
2960 (remaining_b, val),
2961 (removed_a, val),
2962 (removed_b, val),
2963 ]);
2964 let harness = TrieTestHarness::new(initial_storage);
2965
2966 let cached_branch = &harness
2967 .storage_trie_updates()
2968 .storage_nodes
2969 .get(&Nibbles::from_nibbles([0x2]))
2970 .expect("branch at 0x2");
2971 let child_mask =
2972 TrieMask::from_nibble(remaining_nibble) | TrieMask::from_nibble(removed_nibble);
2973 assert_eq!(cached_branch.state_mask, child_mask);
2974 assert_eq!(cached_branch.hash_mask, child_mask);
2975 assert!(cached_branch.tree_mask.is_empty());
2976
2977 let final_storage = BTreeMap::from([(remaining_a, val), (remaining_b, val)]);
2978 let expected_root = TrieTestHarness::new(final_storage.clone()).original_root();
2979 let updated_hashed = MockHashedCursorFactory::new(
2980 BTreeMap::new(),
2981 std::iter::once((harness.hashed_address(), final_storage)).collect(),
2982 );
2983
2984 let mut prefix_set = PrefixSetMut::default();
2986 prefix_set.insert(Nibbles::unpack(removed_a));
2987 prefix_set.insert(Nibbles::unpack(removed_b));
2988
2989 let trie_cursor =
2990 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2991 let hashed_cursor = updated_hashed.hashed_storage_cursor(harness.hashed_address()).unwrap();
2992 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
2993 .with_prefix_set(prefix_set.freeze());
2994 let root_node = calculator
2995 .storage_root_node(harness.hashed_address())
2996 .expect("storage_root_node should succeed after branch collapse");
2997 let root =
2998 calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap().unwrap();
2999
3000 pretty_assertions::assert_eq!(expected_root, root);
3001 }
3002
3003 #[reth_concurrency::test]
3004 fn test_branch_collapse_removed_child_before_remaining() {
3005 assert_branch_collapse(1, 0);
3006 }
3007
3008 #[reth_concurrency::test]
3009 fn test_branch_collapse_removed_child_after_remaining() {
3010 assert_branch_collapse(4, 9);
3011 }
3012
3013 #[reth_concurrency::test]
3014 fn test_prefix_set_root_proof_preserves_clean_sibling_after_cached_branch_collapse() {
3015 reth_tracing::init_test_tracing();
3016
3017 let dirty = B256::right_padding_from(&[0x10, 0x00, 0x10]);
3018 let clean_sibling = B256::right_padding_from(&[0x10, 0x10]);
3019 let storage = [
3020 B256::right_padding_from(&[0x10]),
3021 dirty,
3022 B256::right_padding_from(&[0x10, 0x01]),
3023 B256::right_padding_from(&[0x10, 0x02]),
3024 clean_sibling,
3025 B256::right_padding_from(&[0x11]),
3026 B256::right_padding_from(&[0x12]),
3027 ]
3028 .into_iter()
3029 .map(|key| (key, U256::ONE))
3030 .collect();
3031
3032 let harness = ProofTestHarness::new(storage);
3033 let expected_root = harness.original_root();
3034
3035 let mut prefix_set = PrefixSetMut::default();
3036 prefix_set.insert(Nibbles::unpack(dirty));
3037
3038 let mut prefix_set_with_sibling = PrefixSetMut::default();
3039 prefix_set_with_sibling.insert(Nibbles::unpack(dirty));
3040 prefix_set_with_sibling.insert(Nibbles::unpack(clean_sibling));
3041
3042 pretty_assertions::assert_eq!(
3043 Some(expected_root),
3044 harness.root_with_prefix_set(prefix_set_with_sibling.freeze()),
3045 );
3046 pretty_assertions::assert_eq!(
3047 Some(expected_root),
3048 harness.root_with_prefix_set(prefix_set.freeze()),
3049 "a dirty prefix must not omit a clean sibling after collapsing a cached branch",
3050 );
3051 }
3052
3053 #[reth_concurrency::test]
3054 fn test_prefix_set_range_skips_covered_cached_branch() {
3055 reth_tracing::init_test_tracing();
3056
3057 let before = B256::right_padding_from(&[0x30]);
3058 let cached_a = B256::right_padding_from(&[0x80, 0x10]);
3059 let cached_b = B256::right_padding_from(&[0x80, 0x15]);
3060 let dirty = B256::right_padding_from(&[0x80, 0xc0]);
3061 let after = B256::right_padding_from(&[0x90]);
3062
3063 let storage = [before, cached_a, cached_b, dirty, after]
3066 .into_iter()
3067 .enumerate()
3068 .map(|(i, key)| (key, U256::from(i + 1)))
3069 .collect();
3070
3071 let harness = ProofTestHarness::new(storage);
3072 let expected_root = harness.original_root();
3073 let mut prefix_set = PrefixSetMut::default();
3074 prefix_set.insert(Nibbles::unpack(dirty));
3075
3076 pretty_assertions::assert_eq!(
3077 Some(expected_root),
3078 harness.root_with_prefix_set(prefix_set.freeze()),
3079 );
3080 }
3081
3082 #[reth_concurrency::test]
3083 fn test_cached_branch_extension_skips_diverging_target() {
3084 reth_tracing::init_test_tracing();
3085
3086 let val = U256::from(100u64);
3087
3088 let key_a0 = B256::right_padding_from(&[0x6a, 0x30]); let key_a1 = B256::right_padding_from(&[0x6a, 0x31]); let key_c = B256::right_padding_from(&[0x6a, 0x80]); let key_d = B256::right_padding_from(&[0x6b, 0x00]); let key_e = B256::right_padding_from(&[0x6c, 0x00]); let all_storage: BTreeMap<B256, U256> =
3097 [(key_a0, val), (key_a1, val), (key_c, val), (key_d, val), (key_e, val)]
3098 .into_iter()
3099 .collect();
3100 let correct_harness = TrieTestHarness::new(all_storage.clone());
3101 let expected_root = correct_harness.original_root();
3102
3103 let leaf_hash_a0 = storage_leaf_hash(&Nibbles::unpack(key_a0).slice(4..), &val);
3105 let leaf_hash_a1 = storage_leaf_hash(&Nibbles::unpack(key_a1).slice(4..), &val);
3106 let leaf_hash_d = storage_leaf_hash(&Nibbles::unpack(key_d).slice(2..), &val);
3107 let leaf_hash_e = storage_leaf_hash(&Nibbles::unpack(key_e).slice(2..), &val);
3108
3109 let branch_6_state_mask = TrieMask::new((1 << 0xa) | (1 << 0xb) | (1 << 0xc));
3116 let branch_6_hash_mask = TrieMask::new((1 << 0xb) | (1 << 0xc));
3117 let branch_6 = BranchNodeCompact::new(
3118 branch_6_state_mask,
3119 TrieMask::new(0),
3120 branch_6_hash_mask,
3121 vec![leaf_hash_d, leaf_hash_e],
3122 None,
3123 );
3124
3125 let branch_6a3_state_mask = TrieMask::new((1 << 0) | (1 << 1));
3129 let branch_6a3 = BranchNodeCompact::new(
3130 branch_6a3_state_mask,
3131 TrieMask::new(0),
3132 branch_6a3_state_mask,
3133 vec![leaf_hash_a0, leaf_hash_a1],
3134 None,
3135 );
3136
3137 let inconsistent_nodes: BTreeMap<Nibbles, BranchNodeCompact> = [
3139 (Nibbles::from_nibbles([0x6]), branch_6),
3140 (Nibbles::from_nibbles([0x6, 0xa, 0x3]), branch_6a3),
3141 ]
3142 .into_iter()
3143 .collect();
3144
3145 let mut harness = TrieTestHarness::new(all_storage);
3147 harness.set_trie_nodes(inconsistent_nodes);
3148
3149 let mut prefix_set = PrefixSetMut::default();
3152 prefix_set.insert(Nibbles::unpack(key_c));
3153
3154 let trie_cursor =
3156 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
3157 let hashed_cursor = harness
3158 .hashed_cursor_factory()
3159 .hashed_storage_cursor(harness.hashed_address())
3160 .unwrap();
3161 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
3162 .with_prefix_set(prefix_set.freeze());
3163
3164 let root_node = calculator
3165 .storage_root_node(harness.hashed_address())
3166 .expect("storage_root_node should succeed");
3167 let got_root = calculator
3168 .compute_root_hash(core::slice::from_ref(&root_node))
3169 .unwrap()
3170 .expect("should produce a root hash");
3171
3172 pretty_assertions::assert_eq!(
3174 expected_root,
3175 got_root,
3176 "Root hash should match correct trie; cached extension must not skip diverging leaves"
3177 );
3178
3179 let mut targets = vec![ProofV2Target::new(key_c)];
3181 let proofs = calculator
3182 .storage_proof(harness.hashed_address(), &mut targets)
3183 .expect("storage_proof should succeed");
3184
3185 let key_c_nibbles = Nibbles::unpack(key_c);
3186 let has_matching_node = proofs.iter().any(|node| key_c_nibbles.starts_with(&node.path));
3187 assert!(
3188 has_matching_node,
3189 "Proof for key_c should contain at least one node on key_c's path, got: {proofs:?}"
3190 );
3191 }
3192
3193 #[reth_concurrency::test]
3194 fn test_cached_branch_extension_skips_diverging_target_before() {
3195 reth_tracing::init_test_tracing();
3196
3197 let val = U256::from(100u64);
3198
3199 let key_a0 = B256::right_padding_from(&[0x6a, 0x80]); let key_a1 = B256::right_padding_from(&[0x6a, 0x81]); let key_c = B256::right_padding_from(&[0x6a, 0x30]); let key_d = B256::right_padding_from(&[0x6b, 0x00]); let key_e = B256::right_padding_from(&[0x6c, 0x00]); let all_storage: BTreeMap<B256, U256> =
3209 [(key_a0, val), (key_a1, val), (key_c, val), (key_d, val), (key_e, val)]
3210 .into_iter()
3211 .collect();
3212 let correct_harness = TrieTestHarness::new(all_storage.clone());
3213 let expected_root = correct_harness.original_root();
3214
3215 let leaf_hash_a0 = storage_leaf_hash(&Nibbles::unpack(key_a0).slice(4..), &val);
3217 let leaf_hash_a1 = storage_leaf_hash(&Nibbles::unpack(key_a1).slice(4..), &val);
3218 let leaf_hash_d = storage_leaf_hash(&Nibbles::unpack(key_d).slice(2..), &val);
3219 let leaf_hash_e = storage_leaf_hash(&Nibbles::unpack(key_e).slice(2..), &val);
3220
3221 let branch_6_state_mask = TrieMask::new((1 << 0xa) | (1 << 0xb) | (1 << 0xc));
3228 let branch_6_hash_mask = TrieMask::new((1 << 0xb) | (1 << 0xc));
3229 let branch_6 = BranchNodeCompact::new(
3230 branch_6_state_mask,
3231 TrieMask::new(0),
3232 branch_6_hash_mask,
3233 vec![leaf_hash_d, leaf_hash_e],
3234 None,
3235 );
3236
3237 let branch_6a8_state_mask = TrieMask::new((1 << 0) | (1 << 1));
3241 let branch_6a8 = BranchNodeCompact::new(
3242 branch_6a8_state_mask,
3243 TrieMask::new(0),
3244 branch_6a8_state_mask,
3245 vec![leaf_hash_a0, leaf_hash_a1],
3246 None,
3247 );
3248
3249 let inconsistent_nodes: BTreeMap<Nibbles, BranchNodeCompact> = [
3251 (Nibbles::from_nibbles([0x6]), branch_6),
3252 (Nibbles::from_nibbles([0x6, 0xa, 0x8]), branch_6a8),
3253 ]
3254 .into_iter()
3255 .collect();
3256
3257 let mut harness = TrieTestHarness::new(all_storage);
3259 harness.set_trie_nodes(inconsistent_nodes);
3260
3261 let mut prefix_set = PrefixSetMut::default();
3263 prefix_set.insert(Nibbles::unpack(key_c));
3264
3265 let trie_cursor =
3267 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
3268 let hashed_cursor = harness
3269 .hashed_cursor_factory()
3270 .hashed_storage_cursor(harness.hashed_address())
3271 .unwrap();
3272 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
3273 .with_prefix_set(prefix_set.freeze());
3274
3275 let root_node = calculator
3276 .storage_root_node(harness.hashed_address())
3277 .expect("storage_root_node should succeed");
3278 let got_root = calculator
3279 .compute_root_hash(core::slice::from_ref(&root_node))
3280 .unwrap()
3281 .expect("should produce a root hash");
3282
3283 pretty_assertions::assert_eq!(
3285 expected_root,
3286 got_root,
3287 "Root hash should match correct trie; cached extension must not skip diverging leaves before cached branch"
3288 );
3289
3290 let mut targets = vec![ProofV2Target::new(key_c)];
3292 let proofs = calculator
3293 .storage_proof(harness.hashed_address(), &mut targets)
3294 .expect("storage_proof should succeed");
3295
3296 let key_c_nibbles = Nibbles::unpack(key_c);
3297 let has_matching_node = proofs.iter().any(|node| key_c_nibbles.starts_with(&node.path));
3298 assert!(
3299 has_matching_node,
3300 "Proof for key_c should contain at least one node on key_c's path, got: {proofs:?}"
3301 );
3302 }
3303
3304 #[reth_concurrency::test]
3305 fn test_skipped_parent_branch_with_unskipped_child() {
3306 reth_tracing::init_test_tracing();
3307
3308 let val = U256::ONE;
3309 let updated_val = U256::from(2u64);
3310
3311 let key_2 = B256::right_padding_from(&[0x20]);
3313 let key_2f00 = B256::right_padding_from(&[0x2f, 0x00]);
3314 let key_2f01 = B256::right_padding_from(&[0x2f, 0x01]);
3315 let key_2f10 = B256::right_padding_from(&[0x2f, 0x10]);
3316 let key_2f11 = B256::right_padding_from(&[0x2f, 0x11]);
3317 let key_300 = B256::right_padding_from(&[0x30, 0x00]);
3318 let key_301 = B256::right_padding_from(&[0x30, 0x10]);
3319 let key_310 = B256::right_padding_from(&[0x31, 0x00]);
3320 let key_311 = B256::right_padding_from(&[0x31, 0x10]);
3321 let key_500 = B256::right_padding_from(&[0x50, 0x00]);
3322 let key_501 = B256::right_padding_from(&[0x50, 0x10]);
3323 let key_510 = B256::right_padding_from(&[0x51, 0x00]);
3324 let key_511 = B256::right_padding_from(&[0x51, 0x10]);
3325
3326 let all_keys = [
3327 key_2, key_2f00, key_2f01, key_2f10, key_2f11, key_300, key_301, key_310, key_311,
3328 key_500, key_501, key_510, key_511,
3329 ];
3330
3331 let original_storage: BTreeMap<B256, U256> = all_keys.iter().map(|k| (*k, val)).collect();
3332 let harness = TrieTestHarness::new(original_storage);
3333
3334 let trie_updates = harness.storage_trie_updates();
3336 assert!(trie_updates.storage_nodes.contains_key(&Nibbles::from_nibbles([0x2])));
3337 assert!(trie_updates.storage_nodes.contains_key(&Nibbles::from_nibbles([0x2, 0xf])));
3338 assert!(trie_updates.storage_nodes.contains_key(&Nibbles::from_nibbles([0x3])));
3339
3340 let changeset: BTreeMap<B256, U256> = std::iter::once((key_2, updated_val)).collect();
3343 let (expected_root, _) = harness.get_root_with_updates(&changeset);
3344
3345 let mut updated_storage = harness.storage().clone();
3346 updated_storage.insert(key_2, updated_val);
3347
3348 let updated_hashed = MockHashedCursorFactory::new(
3349 BTreeMap::new(),
3350 std::iter::once((harness.hashed_address(), updated_storage)).collect(),
3351 );
3352
3353 let mut prefix_set = PrefixSetMut::default();
3354 prefix_set.insert(Nibbles::unpack(key_2));
3355
3356 let trie_cursor =
3357 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
3358 let hashed_cursor = updated_hashed.hashed_storage_cursor(harness.hashed_address()).unwrap();
3359 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
3360 .with_prefix_set(prefix_set.freeze());
3361 let root_node = calculator
3362 .storage_root_node(harness.hashed_address())
3363 .expect("storage_root_node should succeed");
3364
3365 let got_root = calculator
3366 .compute_root_hash(&[root_node])
3367 .expect("root hash should succeed")
3368 .expect("root should get hashed");
3369 pretty_assertions::assert_eq!(expected_root, got_root);
3370 }
3371
3372 #[reth_concurrency::test]
3373 fn test_blinded_local_root_returns_trie_inconsistency() {
3374 let key = B256::right_padding_from(&[0x63, 0xaa]);
3375 let value = U256::ONE;
3376 let hash = storage_leaf_hash(&Nibbles::unpack(key).slice(2..), &value);
3377 let mask = TrieMask::from_nibble(3);
3378 let cached_branch =
3379 BranchNodeCompact::new(mask, TrieMask::default(), mask, vec![hash], None);
3380
3381 let mut harness = TrieTestHarness::new(BTreeMap::from([(key, value)]));
3382 harness.set_trie_nodes(BTreeMap::from([(Nibbles::from_nibbles([6]), cached_branch)]));
3383
3384 let trie_cursor =
3385 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
3386 let hashed_cursor = harness
3387 .hashed_cursor_factory()
3388 .hashed_storage_cursor(harness.hashed_address())
3389 .unwrap();
3390 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor);
3391
3392 assert!(matches!(
3393 calculator.storage_root_node(harness.hashed_address()),
3394 Err(StateProofError::TrieInconsistency(_))
3395 ));
3396 }
3397
3398 #[reth_concurrency::test]
3399 fn test_cached_hash_with_deleted_leaf() {
3400 reth_tracing::init_test_tracing();
3401
3402 let val_3 = U256::from(111u64);
3404 let val_5 = U256::from(222u64);
3405 let val_8 = U256::from(333u64);
3406
3407 let key_63 = B256::right_padding_from(&[0x63, 0xaa]); let key_65 = B256::right_padding_from(&[0x65, 0xbb]); let key_68 = B256::right_padding_from(&[0x68, 0xcc]); let leaf_hash_3 = storage_leaf_hash(&Nibbles::unpack(key_63).slice(2..), &val_3);
3416 let leaf_hash_5 = storage_leaf_hash(&Nibbles::unpack(key_65).slice(2..), &val_5);
3417 let leaf_hash_8 = storage_leaf_hash(&Nibbles::unpack(key_68).slice(2..), &val_8);
3418
3419 let state_mask = TrieMask::new((1 << 3) | (1 << 5) | (1 << 8));
3421 let cached_branch = BranchNodeCompact::new(
3422 state_mask,
3423 TrieMask::new(0),
3424 state_mask, vec![leaf_hash_3, leaf_hash_5, leaf_hash_8],
3426 None,
3427 );
3428
3429 let storage_nodes: BTreeMap<Nibbles, BranchNodeCompact> =
3430 std::iter::once((Nibbles::from_nibbles([0x6]), cached_branch)).collect();
3431
3432 let mut harness =
3434 TrieTestHarness::new([(key_65, val_5), (key_68, val_8)].into_iter().collect());
3435 let expected_root = harness.original_root();
3436
3437 harness.set_trie_nodes(storage_nodes);
3439
3440 let mut prefix_set = PrefixSetMut::default();
3443 prefix_set.insert(Nibbles::unpack(key_63));
3444
3445 let mut targets = vec![ProofV2Target::new(key_63)];
3449
3450 let trie_cursor =
3451 harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
3452 let hashed_cursor = harness
3453 .hashed_cursor_factory()
3454 .hashed_storage_cursor(harness.hashed_address())
3455 .unwrap();
3456 let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
3457 .with_prefix_set(prefix_set.freeze());
3458
3459 let proofs = calculator
3460 .storage_proof(harness.hashed_address(), &mut targets)
3461 .expect("storage_proof should succeed");
3462 assert_eq!(2, proofs.len());
3463 assert_eq!(proofs[0].path, Nibbles::from_nibbles([6]));
3464 assert!(matches!(proofs[0].node, TrieNode::Branch(_)));
3465 assert!(matches!(proofs[1].node, TrieNode::Extension(_)));
3466 assert!(proofs[1].masks.is_none());
3467 let got_root = calculator
3468 .compute_root_hash(&proofs)
3469 .expect("compute_root_hash should succeed")
3470 .expect("should produce a root hash (proof contains root node)");
3471
3472 pretty_assertions::assert_eq!(
3475 expected_root,
3476 got_root,
3477 "Root hash should match trie without key_63; cached hash index is off when \
3478 an earlier hashed child has no leaves (absence proof target)"
3479 );
3480 }
3481}