Skip to main content

reth_trie/
walker.rs

1use crate::{
2    prefix_set::PrefixSet,
3    trie_cursor::{subnode::SubNodePosition, CursorSubNode, TrieCursor},
4    BranchNodeCompact, Nibbles,
5};
6use alloy_primitives::{map::HashSet, B256};
7use alloy_trie::{proof::AddedRemovedKeys, TrieMask};
8use reth_storage_errors::db::DatabaseError;
9use tracing::{instrument, trace};
10
11#[cfg(feature = "metrics")]
12use crate::metrics::WalkerMetrics;
13
14/// Traverses the trie in lexicographic order.
15///
16/// This iterator depends on the ordering guarantees of [`TrieCursor`].
17#[derive(Debug)]
18pub struct TrieWalker<C, K = AddedRemovedKeys> {
19    /// A mutable reference to a trie cursor instance used for navigating the trie.
20    pub cursor: C,
21    /// A vector containing the trie nodes that have been visited.
22    pub stack: Vec<CursorSubNode>,
23    /// A flag indicating whether the current node can be skipped when traversing the trie. This
24    /// is determined by whether the current key's prefix is included in the prefix set and if the
25    /// hash flag is set.
26    pub can_skip_current_node: bool,
27    /// A `PrefixSet` representing the changes to be applied to the trie.
28    pub changes: PrefixSet,
29    /// When enabled, all children of a branch become unskippable if the branch path itself
30    /// matches the prefix set, even if a given child path does not.
31    walk_all_changed_branch_children: bool,
32    /// The retained trie node keys that need to be removed.
33    removed_keys: Option<HashSet<Nibbles>>,
34    /// Provided when it's necessary not to skip certain nodes during proof generation.
35    /// Specifically we don't skip certain branch nodes even when they are not in the `PrefixSet`,
36    /// when they might be required to support leaf removal.
37    added_removed_keys: Option<K>,
38    #[cfg(feature = "metrics")]
39    /// Walker metrics.
40    metrics: WalkerMetrics,
41}
42
43impl<C: TrieCursor, K: AsRef<AddedRemovedKeys>> TrieWalker<C, K> {
44    /// Constructs a new `TrieWalker` for the state trie from existing stack and a cursor.
45    pub fn state_trie_from_stack(cursor: C, stack: Vec<CursorSubNode>, changes: PrefixSet) -> Self {
46        Self::from_stack(
47            cursor,
48            stack,
49            changes,
50            #[cfg(feature = "metrics")]
51            crate::TrieType::State,
52        )
53    }
54
55    /// Constructs a new `TrieWalker` for the storage trie from existing stack and a cursor.
56    pub fn storage_trie_from_stack(
57        cursor: C,
58        stack: Vec<CursorSubNode>,
59        changes: PrefixSet,
60    ) -> Self {
61        Self::from_stack(
62            cursor,
63            stack,
64            changes,
65            #[cfg(feature = "metrics")]
66            crate::TrieType::Storage,
67        )
68    }
69
70    /// Constructs a new `TrieWalker` from existing stack and a cursor.
71    fn from_stack(
72        cursor: C,
73        stack: Vec<CursorSubNode>,
74        changes: PrefixSet,
75        #[cfg(feature = "metrics")] trie_type: crate::TrieType,
76    ) -> Self {
77        let mut this = Self {
78            cursor,
79            changes,
80            stack,
81            can_skip_current_node: false,
82            walk_all_changed_branch_children: false,
83            removed_keys: None,
84            added_removed_keys: None,
85            #[cfg(feature = "metrics")]
86            metrics: WalkerMetrics::new(trie_type),
87        };
88        this.update_skip_node();
89        this
90    }
91
92    /// Sets the flag whether the trie updates should be stored.
93    pub fn with_deletions_retained(mut self, retained: bool) -> Self {
94        if retained {
95            self.removed_keys = Some(HashSet::default());
96        }
97        self
98    }
99
100    /// Configures the walker to not skip certain branch nodes, even when they are not in the
101    /// `PrefixSet`, when they might be needed to support leaf removal.
102    pub fn with_added_removed_keys<K2>(self, added_removed_keys: Option<K2>) -> TrieWalker<C, K2> {
103        TrieWalker {
104            cursor: self.cursor,
105            stack: self.stack,
106            can_skip_current_node: self.can_skip_current_node,
107            changes: self.changes,
108            walk_all_changed_branch_children: self.walk_all_changed_branch_children,
109            removed_keys: self.removed_keys,
110            added_removed_keys,
111            #[cfg(feature = "metrics")]
112            metrics: self.metrics,
113        }
114    }
115
116    /// Configures the walker to treat every child of a matching branch path as unskippable.
117    ///
118    /// When deletions are retained, also collects stored descendants hidden by a matching
119    /// branch's tree mask or left beside an extension's child. These keys appear in the deletion
120    /// set even if traversal never visits them. Root calculations can replace these deletions with
121    /// regenerated branch updates.
122    pub fn with_walk_all_changed_branch_children(mut self, enabled: bool) -> Self {
123        self.walk_all_changed_branch_children = enabled;
124        // Restored stacks already have a current node whose skip state depends on this flag.
125        self.update_skip_node();
126        self
127    }
128
129    /// Split the walker into stack and trie updates.
130    pub fn split(mut self) -> (Vec<CursorSubNode>, HashSet<Nibbles>) {
131        let keys = self.take_removed_keys();
132        (self.stack, keys)
133    }
134
135    /// Take removed keys from the walker.
136    pub fn take_removed_keys(&mut self) -> HashSet<Nibbles> {
137        self.removed_keys.take().unwrap_or_default()
138    }
139
140    /// Prints the current stack of trie nodes.
141    pub fn print_stack(&self) {
142        println!("====================== STACK ======================");
143        for node in &self.stack {
144            println!("{node:?}");
145        }
146        println!("====================== END STACK ======================\n");
147    }
148
149    /// The current length of the removed keys.
150    pub fn removed_keys_len(&self) -> usize {
151        self.removed_keys.as_ref().map_or(0, |u| u.len())
152    }
153
154    /// Returns the current key in the trie.
155    pub fn key(&self) -> Option<&Nibbles> {
156        self.stack.last().map(|n| n.full_key())
157    }
158
159    /// Returns the current hash in the trie, if any.
160    pub fn hash(&self) -> Option<B256> {
161        self.stack.last().and_then(|n| n.hash())
162    }
163
164    /// Returns the current hash in the trie, if any.
165    ///
166    /// Differs from [`Self::hash`] in that it returns `None` if the subnode is positioned at the
167    /// child without a hash mask bit set. [`Self::hash`] panics in that case.
168    pub fn maybe_hash(&self) -> Option<B256> {
169        self.stack.last().and_then(|n| n.maybe_hash())
170    }
171
172    /// Indicates whether the children of the current node are present in the trie.
173    pub fn children_are_in_trie(&self) -> bool {
174        self.stack.last().is_some_and(|n| n.tree_flag())
175    }
176
177    /// Returns the next unprocessed key in the trie along with its raw [`Nibbles`] representation.
178    #[instrument(level = "trace", skip(self), ret)]
179    pub fn next_unprocessed_key(&self) -> Option<(B256, Nibbles)> {
180        self.key()
181            .and_then(|key| if self.can_skip_current_node { key.increment() } else { Some(*key) })
182            .map(|key| (B256::right_padding_from(&key.pack()), key))
183    }
184
185    /// Updates the skip node flag based on the walker's current state.
186    fn update_skip_node(&mut self) {
187        let old = self.can_skip_current_node;
188        self.can_skip_current_node = self.stack.last().is_some_and(|node| {
189            // If the current key is not removed according to the [`AddedRemovedKeys`], and all of
190            // its siblings are removed, then we don't want to skip it. This allows the
191            // `ProofRetainer` to include this node in the returned proofs. Required to support
192            // leaf removal.
193            let key_is_only_nonremoved_child =
194                self.added_removed_keys.as_ref().is_some_and(|added_removed_keys| {
195                    node.full_key_is_only_nonremoved_child(added_removed_keys.as_ref())
196                });
197
198            trace!(
199                target: "trie::walker",
200                ?key_is_only_nonremoved_child,
201                full_key=?node.full_key(),
202                "Checked for only non-removed child",
203            );
204
205            let branch_path_matches_prefix_set = self.walk_all_changed_branch_children &&
206                node.position().is_child() &&
207                self.changes.contains(&node.key);
208
209            !self.changes.contains(node.full_key()) &&
210                !branch_path_matches_prefix_set &&
211                node.hash_flag() &&
212                !key_is_only_nonremoved_child
213        });
214        trace!(
215            target: "trie::walker",
216            old,
217            new = self.can_skip_current_node,
218            last = ?self.stack.last(),
219            "updated skip node flag"
220        );
221    }
222
223    /// Constructs a new [`TrieWalker`] for the state trie.
224    pub fn state_trie(cursor: C, changes: PrefixSet) -> Result<Self, DatabaseError> {
225        Self::new(
226            cursor,
227            changes,
228            #[cfg(feature = "metrics")]
229            crate::TrieType::State,
230        )
231    }
232
233    /// Constructs a new [`TrieWalker`] for the storage trie.
234    pub fn storage_trie(cursor: C, changes: PrefixSet) -> Result<Self, DatabaseError> {
235        Self::new(
236            cursor,
237            changes,
238            #[cfg(feature = "metrics")]
239            crate::TrieType::Storage,
240        )
241    }
242
243    /// Constructs a new `TrieWalker`, setting up the initial state of the stack and cursor.
244    fn new(
245        cursor: C,
246        changes: PrefixSet,
247        #[cfg(feature = "metrics")] trie_type: crate::TrieType,
248    ) -> Result<Self, DatabaseError> {
249        // Initialize the walker with a single empty stack element.
250        let mut this = Self {
251            cursor,
252            changes,
253            stack: vec![CursorSubNode::default()],
254            can_skip_current_node: false,
255            walk_all_changed_branch_children: false,
256            removed_keys: None,
257            added_removed_keys: Default::default(),
258            #[cfg(feature = "metrics")]
259            metrics: WalkerMetrics::new(trie_type),
260        };
261
262        // Set up the root node of the trie in the stack, if it exists.
263        if let Some((key, value)) = this.node(true)? {
264            this.stack[0] = CursorSubNode::new(key, Some(value));
265        }
266
267        // Update the skip state for the root node.
268        this.update_skip_node();
269        Ok(this)
270    }
271
272    /// Advances the walker to the next trie node and updates the skip node flag.
273    /// The new key can then be obtained via `key()`.
274    ///
275    /// # Returns
276    ///
277    /// * `Result<(), Error>` - Unit on success or an error.
278    pub fn advance(&mut self) -> Result<(), DatabaseError> {
279        if let Some(last) = self.stack.last() {
280            if !self.can_skip_current_node && self.children_are_in_trie() {
281                trace!(
282                    target: "trie::walker",
283                    position = ?last.position(),
284                    "cannot skip current node and children are in the trie"
285                );
286                // If we can't skip the current node and the children are in the trie,
287                // either consume the next node or move to the next sibling.
288                match last.position() {
289                    SubNodePosition::ParentBranch => self.move_to_next_sibling(true)?,
290                    SubNodePosition::Child(_) => self.consume_node()?,
291                }
292            } else {
293                trace!(target: "trie::walker", "can skip current node");
294                // If we can skip the current node, move to the next sibling.
295                self.move_to_next_sibling(false)?;
296            }
297
298            // Update the skip node flag based on the new position in the trie.
299            self.update_skip_node();
300        }
301
302        Ok(())
303    }
304
305    /// Retrieves the current root node from the DB, seeking either the exact node or the next one.
306    fn node(&mut self, exact: bool) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> {
307        let key = self.key().expect("key must exist");
308        let entry = if exact { self.cursor.seek_exact(*key)? } else { self.cursor.seek(*key)? };
309        #[cfg(feature = "metrics")]
310        self.metrics.inc_branch_nodes_seeked();
311
312        if let Some((_, node)) = &entry {
313            assert!(!node.state_mask.is_empty());
314        }
315
316        Ok(entry)
317    }
318
319    /// Consumes the next node in the trie, updating the stack.
320    #[instrument(level = "trace", skip(self), ret)]
321    fn consume_node(&mut self) -> Result<(), DatabaseError> {
322        let Some((key, node)) = self.node(false)? else {
323            // If no next node is found, clear the stack.
324            self.stack.clear();
325            return Ok(())
326        };
327
328        // Only the top-level cursor follows the first nibble of a newly consumed branch.
329        // A deeper seek can leave its child interval when a cached tree bit is stale; changing
330        // an ancestor here would skip the subtree containing the seek result.
331        if !key.is_empty() && self.stack.len() == 1 {
332            self.stack[0].set_nibble(key.get_unchecked(0));
333        }
334
335        // The current tree mask might have been set incorrectly.
336        // Sanity check that the newly retrieved trie node key is the child of the last item
337        // on the stack. If not, advance to the next sibling instead of adding the node to the
338        // stack.
339        if let Some(subnode) = self.stack.last() &&
340            !key.starts_with(subnode.full_key())
341        {
342            #[cfg(feature = "metrics")]
343            self.metrics.inc_out_of_order_subnode(1);
344            self.move_to_next_sibling(false)?;
345            return Ok(())
346        }
347
348        self.remove_orphaned_descendants(
349            self.stack.last().map_or(key, |node| *node.full_key()),
350            key,
351            node.tree_mask,
352        )?;
353
354        // Create a new CursorSubNode and push it to the stack.
355        let subnode = CursorSubNode::new(key, Some(node));
356        let position = subnode.position();
357        self.stack.push(subnode);
358        self.update_skip_node();
359
360        // Delete the current node if it's included in the prefix set or it doesn't contain the root
361        // hash.
362        if (!self.can_skip_current_node || position.is_child()) &&
363            let Some((keys, key)) = self.removed_keys.as_mut().zip(self.cursor.current()?)
364        {
365            keys.insert(key);
366        }
367
368        Ok(())
369    }
370
371    /// Moves to the next sibling node in the trie, updating the stack.
372    #[instrument(level = "trace", skip(self), ret)]
373    fn move_to_next_sibling(
374        &mut self,
375        allow_root_to_child_nibble: bool,
376    ) -> Result<(), DatabaseError> {
377        let Some(subnode) = self.stack.last_mut() else { return Ok(()) };
378
379        // Check if the walker needs to backtrack to the previous level in the trie during its
380        // traversal.
381        if subnode.position().is_last_child() ||
382            (subnode.position().is_parent() && !allow_root_to_child_nibble)
383        {
384            self.stack.pop();
385            self.move_to_next_sibling(false)?;
386            return Ok(())
387        }
388
389        subnode.inc_nibble();
390
391        if subnode.node.is_none() {
392            return self.consume_node()
393        }
394
395        // Find the next sibling with state.
396        loop {
397            let position = subnode.position();
398            if subnode.state_flag() {
399                trace!(target: "trie::walker", ?position, "found next sibling with state");
400                return Ok(())
401            }
402            if position.is_last_child() {
403                trace!(target: "trie::walker", ?position, "checked all siblings");
404                break
405            }
406            subnode.inc_nibble();
407        }
408
409        // Pop the current node and move to the next sibling.
410        self.stack.pop();
411        self.move_to_next_sibling(false)?;
412
413        Ok(())
414    }
415
416    /// Removes stored nodes skipped by masks or extensions during recovery.
417    ///
418    /// When the first stored branch below a changed child is reached through an extension,
419    /// traversal will skip from that branch's subtree to the end of the logical child. Collect
420    /// any stale siblings in that gap before advancing, just as missing tree bits require
421    /// collecting hidden descendants. Bound each scan so live subtrees remain reusable.
422    ///
423    /// Regenerated branch updates take precedence over these deletions. Restore the cursor to
424    /// the consumed node afterwards so traversal and checkpoint resumption remain unchanged.
425    fn remove_orphaned_descendants(
426        &mut self,
427        child_path: Nibbles,
428        key: Nibbles,
429        tree_mask: TrieMask,
430    ) -> Result<(), DatabaseError> {
431        if self.walk_all_changed_branch_children && self.removed_keys.is_some() {
432            let mut cursor_moved = if key.len() > child_path.len() &&
433                self.changes.contains(&child_path) &&
434                let Some(start) = key.next_without_prefix()
435            {
436                self.remove_nodes_in_range(start, child_path.next_without_prefix())?;
437                true
438            } else {
439                false
440            };
441
442            let missing_children = !tree_mask;
443            if !missing_children.is_empty() && self.changes.contains(&key) {
444                for nibble in missing_children.iter() {
445                    let mut prefix = key;
446                    prefix.push(nibble);
447                    self.remove_nodes_in_range(prefix, prefix.next_without_prefix())?;
448                }
449                cursor_moved = true;
450            }
451
452            if cursor_moved {
453                self.cursor.seek_exact(key)?;
454                #[cfg(feature = "metrics")]
455                self.metrics.inc_branch_nodes_seeked();
456            }
457        }
458        Ok(())
459    }
460
461    /// Collects stored paths in `[start, end)` for deletion without trusting their hashes.
462    /// A missing end covers the remainder of the trie. Leaves the cursor at the range boundary.
463    fn remove_nodes_in_range(
464        &mut self,
465        start: Nibbles,
466        end: Option<Nibbles>,
467    ) -> Result<(), DatabaseError> {
468        if let Some(removed_keys) = &mut self.removed_keys {
469            let mut entry = self.cursor.seek(start)?;
470            #[cfg(feature = "metrics")]
471            self.metrics.inc_branch_nodes_seeked();
472            while let Some((path, _)) = entry &&
473                end.is_none_or(|end| path < end)
474            {
475                removed_keys.insert(path);
476                entry = self.cursor.next()?;
477            }
478        }
479        Ok(())
480    }
481}
482
483#[cfg(test)]
484mod tests {
485    use super::*;
486    use crate::{
487        hashed_cursor::HashedCursorFactory,
488        mock::KeyVisitType,
489        prefix_set::PrefixSetMut,
490        progress::StorageRootProgress,
491        proof_v2::StorageProofCalculator,
492        test_utils::{storage_root_prehashed, TrieTestHarness},
493        trie_cursor::{mock::MockTrieCursorFactory, TrieCursorFactory},
494        updates::StorageTrieUpdates,
495        ProofV2Target, StorageRoot,
496    };
497    use alloy_primitives::{map::B256Map, B256, U256};
498    use proptest::prelude::*;
499    use reth_storage_errors::db::DatabaseErrorInfo;
500    use std::collections::BTreeMap;
501
502    fn branch_node(state_mask: u16, tree_mask: u16, hash_mask: u16) -> BranchNodeCompact {
503        let hash_count = hash_mask.count_ones() as usize;
504        BranchNodeCompact::new(
505            TrieMask::new(state_mask),
506            TrieMask::new(tree_mask),
507            TrieMask::new(hash_mask),
508            vec![B256::ZERO; hash_count],
509            None,
510        )
511    }
512
513    fn root_branch_node(state_mask: u16, tree_mask: u16, hash_mask: u16) -> BranchNodeCompact {
514        let hash_count = hash_mask.count_ones() as usize;
515        BranchNodeCompact::new(
516            TrieMask::new(state_mask),
517            TrieMask::new(tree_mask),
518            TrieMask::new(hash_mask),
519            vec![B256::ZERO; hash_count],
520            Some(B256::ZERO),
521        )
522    }
523
524    fn walker_for_matching_branch_children_test(
525        walk_all_changed_branch_children: bool,
526    ) -> TrieWalker<crate::trie_cursor::mock::MockTrieCursor> {
527        let trie_nodes = BTreeMap::from([
528            (Nibbles::default(), root_branch_node(1 << 2, 1 << 2, 1 << 2)),
529            (
530                Nibbles::from_nibbles([0x2]),
531                branch_node((1 << 3) | (1 << 4), 0, (1 << 3) | (1 << 4)),
532            ),
533        ]);
534        let factory = MockTrieCursorFactory::new(trie_nodes, B256Map::default());
535
536        let mut prefix_set = PrefixSetMut::default();
537        prefix_set.insert(Nibbles::from_nibbles([0x2, 0x3, 0x1]));
538
539        TrieWalker::state_trie(factory.account_trie_cursor().unwrap(), prefix_set.freeze())
540            .unwrap()
541            .with_walk_all_changed_branch_children(walk_all_changed_branch_children)
542    }
543
544    #[reth_concurrency::test]
545    fn branch_siblings_remain_skippable_by_default() {
546        let mut walker = walker_for_matching_branch_children_test(false);
547
548        assert_eq!(walker.key().copied(), Some(Nibbles::default()));
549        assert!(!walker.can_skip_current_node);
550
551        walker.advance().unwrap();
552        assert_eq!(walker.key().copied(), Some(Nibbles::from_nibbles([0x2])));
553        assert!(!walker.can_skip_current_node);
554
555        walker.advance().unwrap();
556        assert_eq!(walker.key().copied(), Some(Nibbles::from_nibbles([0x2, 0x3])));
557        assert_eq!(walker.stack.last().unwrap().position(), SubNodePosition::Child(0x3));
558        assert!(!walker.can_skip_current_node);
559
560        walker.advance().unwrap();
561        assert_eq!(walker.key().copied(), Some(Nibbles::from_nibbles([0x2, 0x4])));
562        assert!(walker.can_skip_current_node);
563    }
564
565    #[reth_concurrency::test]
566    fn matching_branch_path_can_make_all_children_unskippable() {
567        let mut walker = walker_for_matching_branch_children_test(true);
568
569        walker.advance().unwrap();
570        walker.advance().unwrap();
571        walker.advance().unwrap();
572        assert_eq!(walker.key().copied(), Some(Nibbles::from_nibbles([0x2, 0x4])));
573        assert!(!walker.can_skip_current_node);
574    }
575
576    #[reth_concurrency::test]
577    fn changed_branch_children_remove_orphans() {
578        for regenerate_branch in [false, true] {
579            let mut storage = BTreeMap::from([
580                (B256::right_padding_from(&[0x3a]), U256::ONE),
581                (B256::right_padding_from(&[0x3a, 0x01]), U256::from(10)),
582                (B256::right_padding_from(&[0x3a, 0x10]), U256::from(7)),
583                (B256::right_padding_from(&[0x3b]), U256::from(2)),
584                (B256::right_padding_from(&[0x3c, 0x47]), U256::from(3)),
585                (B256::right_padding_from(&[0x80]), U256::from(4)),
586                (B256::right_padding_from(&[0x81]), U256::from(5)),
587                (B256::right_padding_from(&[0x80, 0x10]), U256::from(8)),
588            ]);
589            if regenerate_branch {
590                storage.insert(B256::right_padding_from(&[0x3c, 0x48]), U256::from(6));
591                storage.insert(B256::right_padding_from(&[0x3c, 0x47, 0x10]), U256::from(9));
592            }
593            let mut harness = TrieTestHarness::new(storage.clone());
594            let expected_nodes = harness
595                .storage_trie_updates()
596                .storage_nodes
597                .iter()
598                .map(|(key, node)| (*key, node.clone()))
599                .collect::<BTreeMap<_, _>>();
600            let mut stored_nodes = expected_nodes.clone();
601            let parent = Nibbles::from_nibbles([0x3]);
602            stored_nodes.get_mut(&parent).unwrap().tree_mask &=
603                !TrieMask::new((1 << 0xa) | (1 << 0xc));
604
605            // The cached branch at 0x3c and its descendants are unreachable through 0x3's mask.
606            // Include a descendant which should be regenerated and one which should disappear.
607            let orphan_paths = [
608                Nibbles::from_nibbles([0x3, 0xc]),
609                Nibbles::from_nibbles([0x3, 0xc, 0x4]),
610                Nibbles::from_nibbles([0x3, 0xc, 0x4, 0xf]),
611                Nibbles::from_nibbles([0x3, 0xf, 0x1]),
612                Nibbles::from_nibbles([0x3, 0x1, 0x4]),
613            ];
614            // The valid branch under 0x3a is also hidden by the mask. Its regenerated update can
615            // be split off before the walker finishes 0x3, so resumption must not delete it again.
616            assert!(expected_nodes.contains_key(&Nibbles::from_nibbles([0x3, 0xa])));
617            for path in orphan_paths {
618                let mut stale_node = branch_node(0b11, 0, 0b11);
619                stale_node.hashes = vec![B256::repeat_byte(0xee); 2].into();
620                stored_nodes.insert(path, stale_node);
621            }
622            harness.set_trie_nodes(stored_nodes.clone());
623
624            // A change under sibling 0x3a must also clean up 0x3c and state-mask gaps.
625            let prefix_set =
626                PrefixSetMut::from([Nibbles::unpack(B256::right_padding_from(&[0x3a]))]).freeze();
627            for (enabled, threshold) in [(false, u64::MAX), (true, u64::MAX), (true, 1)] {
628                // Also rebuild the neighboring branch in checkpointed runs. Resuming a skipped
629                // branch after a leaf checkpoint currently fails even without orphan cleanup.
630                let changes = if threshold == 1 {
631                    PrefixSetMut::from([
632                        Nibbles::unpack(B256::right_padding_from(&[0x3a])),
633                        Nibbles::unpack(B256::right_padding_from(&[0x80])),
634                    ])
635                    .freeze()
636                } else {
637                    prefix_set.clone()
638                };
639                let (root, updates) =
640                    storage_root_with_progress(&harness, changes, enabled, threshold);
641
642                let mut resulting_nodes = stored_nodes.clone();
643                for (path, node) in updates.into_sorted().storage_nodes {
644                    if let Some(node) = node {
645                        resulting_nodes.insert(path, node);
646                    } else {
647                        resulting_nodes.remove(&path);
648                    }
649                }
650                assert_eq!(root, storage_root_prehashed(storage.clone()));
651                if enabled {
652                    assert_eq!(resulting_nodes, expected_nodes);
653                } else {
654                    // Normal traversal ignores hidden descendants, but leaves them in the cache.
655                    assert_ne!(resulting_nodes, expected_nodes);
656                }
657            }
658        }
659    }
660
661    fn storage_root_with_progress(
662        harness: &TrieTestHarness,
663        changes: PrefixSet,
664        enabled: bool,
665        threshold: u64,
666    ) -> (B256, StorageTrieUpdates) {
667        let mut previous_state = None;
668        let mut updates = StorageTrieUpdates::default();
669        let mut checkpoints = 0;
670        loop {
671            let progress = StorageRoot::new_hashed(
672                harness.trie_cursor_factory(),
673                harness.hashed_cursor_factory(),
674                harness.hashed_address(),
675                changes.clone(),
676                #[cfg(feature = "metrics")]
677                crate::metrics::TrieRootMetrics::new(crate::TrieType::Storage),
678            )
679            .with_walk_all_changed_branch_children(enabled)
680            .with_threshold(threshold)
681            .with_intermediate_state(previous_state)
682            .root_with_progress()
683            .unwrap();
684            match progress {
685                StorageRootProgress::Progress(state, _, new_updates) => {
686                    updates.extend(new_updates);
687                    previous_state = Some(*state);
688                    checkpoints += 1;
689                }
690                StorageRootProgress::Complete(root, _, new_updates) => {
691                    updates.extend(new_updates);
692                    if threshold == 1 {
693                        assert!(checkpoints > 1);
694                    }
695                    return (root, updates)
696                }
697            }
698        }
699    }
700
701    #[reth_concurrency::test]
702    fn orphan_cleanup_skips_live_subtrees() {
703        let parent = Nibbles::from_nibbles([0x3]);
704        let tree_mask = TrieMask::from_nibble(0xa);
705        let orphans = [
706            Nibbles::from_nibbles([0x3, 0xb]),
707            Nibbles::from_nibbles([0x3, 0xb, 0x5]),
708            Nibbles::from_nibbles([0x3, 0xb, 0x5, 0xf]),
709        ];
710        let mut nodes = BTreeMap::from([
711            (parent, branch_node((1 << 0xa) | (1 << 0xb), tree_mask.get(), 0)),
712            (Nibbles::from_nibbles([0x3, 0xa]), branch_node(0b11, 0, 0)),
713            (Nibbles::from_nibbles([0x4]), branch_node(0b11, 0, 0)),
714        ]);
715        for index in 0..128 {
716            nodes.insert(
717                Nibbles::from_nibbles([0x3, 0xa, index / 16, index % 16]),
718                branch_node(0b11, 0, 0),
719            );
720        }
721        nodes.extend(orphans.into_iter().map(|path| (path, branch_node(0b11, 0, 0))));
722        let factory = MockTrieCursorFactory::new(nodes, B256Map::default());
723        let changes = PrefixSetMut::from([Nibbles::from_nibbles([0x3, 0xa])]).freeze();
724        let mut walker =
725            TrieWalker::<_>::state_trie(factory.account_trie_cursor().unwrap(), changes)
726                .unwrap()
727                .with_walk_all_changed_branch_children(true)
728                .with_deletions_retained(true);
729        walker.cursor.seek_exact(parent).unwrap();
730        factory.visited_account_keys().clear();
731        walker.remove_orphaned_descendants(parent, parent, tree_mask).unwrap();
732
733        assert_eq!(walker.take_removed_keys(), HashSet::from_iter(orphans));
734        assert_eq!(walker.cursor.current().unwrap(), Some(parent));
735        let next_count = factory
736            .visited_account_keys()
737            .iter()
738            .filter(|visit| matches!(visit.visit_type, KeyVisitType::Next))
739            .count();
740        assert!(next_count <= 4, "cleanup walked {next_count} entries for 3 orphan nodes");
741    }
742
743    #[reth_concurrency::test]
744    fn resumed_walk_all_recomputes_cached_children() {
745        let storage = BTreeMap::from([
746            (B256::right_padding_from(&[0x3a, 0x00]), U256::from(1)),
747            (B256::right_padding_from(&[0x3a, 0x10]), U256::from(2)),
748            (B256::right_padding_from(&[0x3b]), U256::from(3)),
749            (B256::right_padding_from(&[0x3c, 0x00]), U256::from(4)),
750            (B256::right_padding_from(&[0x3c, 0x10]), U256::from(5)),
751            (B256::right_padding_from(&[0x80]), U256::from(6)),
752            (B256::right_padding_from(&[0x81]), U256::from(7)),
753        ]);
754        let expected = storage_root_prehashed(storage.clone());
755        let mut harness = TrieTestHarness::new(storage);
756        let mut nodes = harness
757            .storage_trie_updates()
758            .storage_nodes
759            .iter()
760            .map(|(key, node)| (*key, node.clone()))
761            .collect::<BTreeMap<_, _>>();
762        let branch = nodes.get_mut(&Nibbles::from_nibbles([0x3])).unwrap();
763        assert!(branch.hash_mask.is_bit_set(0xc));
764        branch.hashes = vec![B256::repeat_byte(0xee); branch.hashes.len()].into();
765        harness.set_trie_nodes(nodes);
766        let changes =
767            PrefixSetMut::from([Nibbles::unpack(B256::right_padding_from(&[0x3a, 0x00]))]).freeze();
768
769        // Normal traversal trusts the stale sibling hash; walk-all must recompute it.
770        assert_ne!(
771            storage_root_with_progress(&harness, changes.clone(), false, u64::MAX).0,
772            expected
773        );
774        for threshold in [u64::MAX, 0, 1] {
775            assert_eq!(
776                storage_root_with_progress(&harness, changes.clone(), true, threshold).0,
777                expected,
778                "walk-all root with threshold {threshold}"
779            );
780        }
781    }
782
783    #[test]
784    fn state_trie_initial_read_timeout_returns_error() {
785        let error =
786            TrieWalker::<_>::state_trie(TimedOutTrieCursor, PrefixSet::default()).unwrap_err();
787        assert_matches::assert_matches!(error, DatabaseError::Read(info) if info == timeout_error());
788    }
789
790    #[test]
791    fn storage_trie_initial_read_timeout_returns_error() {
792        let error =
793            TrieWalker::<_>::storage_trie(TimedOutTrieCursor, PrefixSet::default()).unwrap_err();
794        assert_matches::assert_matches!(error, DatabaseError::Read(info) if info == timeout_error());
795    }
796
797    fn timeout_error() -> DatabaseErrorInfo {
798        DatabaseErrorInfo { message: "read transaction has been timed out".into(), code: -96000 }
799    }
800
801    #[derive(Debug)]
802    struct TimedOutTrieCursor;
803
804    impl TrieCursor for TimedOutTrieCursor {
805        fn seek_exact(
806            &mut self,
807            key: Nibbles,
808        ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> {
809            assert_eq!(key, Nibbles::default());
810            Err(DatabaseError::Read(timeout_error()))
811        }
812
813        fn seek(
814            &mut self,
815            _key: Nibbles,
816        ) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> {
817            unreachable!("initialization only seeks the root exactly")
818        }
819
820        fn next(&mut self) -> Result<Option<(Nibbles, BranchNodeCompact)>, DatabaseError> {
821            unreachable!("initialization only seeks the root exactly")
822        }
823
824        fn current(&mut self) -> Result<Option<Nibbles>, DatabaseError> {
825            unreachable!("initialization only seeks the root exactly")
826        }
827
828        fn reset(&mut self) {
829            unreachable!("initialization only seeks the root exactly")
830        }
831    }
832
833    /// A stale `tree_mask` bit on a changed branch (here `0xa`, bit `e`, with no `0xae` stored)
834    /// makes `consume_node` seek past the branch into the next first-nibble subtree. The root
835    /// nibble is overwritten with that subtree's nibble before the out-of-order check rejects the
836    /// node, so the walker never visits the stale branch at `0xb` and recovery leaves it in the
837    /// table. Later roots computed without a change under `0xb` then hash the stale node.
838    #[reth_concurrency::test]
839    fn dangling_tree_bit_does_not_skip_next_root_child() {
840        let key = |nibbles: &[u8]| B256::right_padding_from(&Nibbles::from_nibbles(nibbles).pack());
841        let storage = BTreeMap::from([
842            (key(&[0xa, 0x1, 0x0]), U256::from(1)),
843            (key(&[0xa, 0x1, 0x1]), U256::from(2)),
844            (key(&[0xa, 0xe]), U256::from(3)),
845            (key(&[0xb, 0x2]), U256::from(4)),
846            (key(&[0xb, 0x7]), U256::from(5)),
847            (key(&[0xc, 0x0]), U256::from(6)),
848        ]);
849        let mut harness = TrieTestHarness::new(storage.clone());
850        let expected_root = storage_root_prehashed(storage);
851        let expected_nodes = harness
852            .storage_trie_updates()
853            .storage_nodes
854            .iter()
855            .map(|(key, node)| (*key, node.clone()))
856            .collect::<BTreeMap<_, _>>();
857        let branch_a = Nibbles::from_nibbles([0xa]);
858        let branch_b = Nibbles::from_nibbles([0xb]);
859        assert!(expected_nodes.contains_key(&branch_a));
860        assert!(!expected_nodes.contains_key(&branch_b));
861
862        // What a masked write or an unwind inside the masking window can leave on disk: the
863        // parent still claims child `e` is stored, and a branch for `0xb` that no longer exists.
864        let mut stored_nodes = expected_nodes.clone();
865        stored_nodes.get_mut(&branch_a).unwrap().tree_mask |= TrieMask::from_nibble(0xe);
866        let mut stale_b = branch_node((1 << 0x2) | (1 << 0x7), 0, (1 << 0x2) | (1 << 0x7));
867        stale_b.hashes = vec![B256::repeat_byte(0xee); 2].into();
868        stored_nodes.insert(branch_b, stale_b);
869        harness.set_trie_nodes(stored_nodes.clone());
870
871        // Partial state trie recovery: both subtrees changed in the unwound range.
872        let changes = PrefixSetMut::from([
873            Nibbles::unpack(key(&[0xa, 0xe])),
874            Nibbles::unpack(key(&[0xb, 0x2])),
875        ])
876        .freeze();
877        let (root, updates) = storage_root_with_progress(&harness, changes, true, u64::MAX);
878        assert_eq!(root, expected_root);
879
880        let mut recovered_nodes = stored_nodes;
881        for (path, node) in updates.into_sorted().storage_nodes {
882            if let Some(node) = node {
883                recovered_nodes.insert(path, node);
884            } else {
885                recovered_nodes.remove(&path);
886            }
887        }
888        let stale_b_left = recovered_nodes.contains_key(&branch_b);
889
890        // The next root without changes reuses the table.
891        harness.set_trie_nodes(recovered_nodes.clone());
892        let (next_root, _) =
893            storage_root_with_progress(&harness, PrefixSet::default(), false, u64::MAX);
894
895        assert!(
896            !stale_b_left && next_root == expected_root,
897            "recovery left the stale branch at 0xb: {stale_b_left}; next root {next_root} vs \
898             expected {expected_root}"
899        );
900        assert_eq!(recovered_nodes, expected_nodes);
901    }
902
903    /// Masked partial persistence can leave a stale branch beside the live child under the same
904    /// child nibble: here `0x5a7` (pre-batch, re-touched by the masking suffix) next to `0x5a2`
905    /// (written by the batch), with no branch at `0x5a`. Recovery's `consume_node` takes the first
906    /// stored node under `0x5a` as that child (an extension), and the walker never looks for other
907    /// stored nodes under `0x5a`, so `0x5a7` is never removed. Proof V2 later adopts it as the next
908    /// cached branch under `0x5a` and splices its stale hashes into the proof.
909    #[reth_concurrency::test]
910    fn stale_sibling_beside_extension_child_is_removed() {
911        let key = |nibbles: &[u8]| B256::right_padding_from(&Nibbles::from_nibbles(nibbles).pack());
912        for regenerate_sibling in [false, true] {
913            let mut storage = BTreeMap::from([
914                (key(&[0x5, 0x3]), U256::from(1)),
915                (key(&[0x5, 0xa, 0x2, 0x1, 0x0]), U256::from(2)),
916                (key(&[0x5, 0xa, 0x2, 0x1, 0x1]), U256::from(3)),
917                (key(&[0x5, 0xa, 0x2, 0x2]), U256::from(4)),
918                (key(&[0xc, 0x0]), U256::from(5)),
919            ]);
920            if regenerate_sibling {
921                storage.extend([
922                    (key(&[0x5, 0xa, 0x7, 0x1, 0x0]), U256::from(6)),
923                    (key(&[0x5, 0xa, 0x7, 0x1, 0x1]), U256::from(7)),
924                    (key(&[0x5, 0xa, 0x7, 0x2]), U256::from(8)),
925                ]);
926            }
927            let mut harness = TrieTestHarness::new(storage.clone());
928            let expected_root = storage_root_prehashed(storage);
929            let expected_nodes = harness
930                .storage_trie_updates()
931                .storage_nodes
932                .iter()
933                .map(|(key, node)| (*key, node.clone()))
934                .collect::<BTreeMap<_, _>>();
935            let live = Nibbles::from_nibbles([0x5, 0xa, 0x2]);
936            let stale = Nibbles::from_nibbles([0x5, 0xa, 0x7]);
937            assert!(expected_nodes.contains_key(&Nibbles::from_nibbles([0x5])));
938            assert!(expected_nodes.contains_key(&live));
939            assert_eq!(
940                expected_nodes.contains_key(&Nibbles::from_nibbles([0x5, 0xa])),
941                regenerate_sibling,
942            );
943
944            let mut stored_nodes = expected_nodes.clone();
945            stored_nodes.remove(&Nibbles::from_nibbles([0x5, 0xa]));
946            let mut stale_node = branch_node((1 << 0x1) | (1 << 0x2), 0, 1 << 0x1);
947            stale_node.hashes = vec![B256::repeat_byte(0xee)].into();
948            stored_nodes.insert(stale, stale_node);
949            for threshold in [u64::MAX, 1] {
950                harness.set_trie_nodes(stored_nodes.clone());
951
952                // Partial state trie recovery: the masking suffix recreated keys under the stale
953                // branch.
954                let changes = PrefixSetMut::from([
955                    Nibbles::unpack(key(&[0x5, 0xa, 0x7, 0x1, 0x0])),
956                    Nibbles::unpack(key(&[0x5, 0xa, 0x7, 0x1, 0x1])),
957                    Nibbles::unpack(key(&[0x5, 0xa, 0x7, 0x2])),
958                ])
959                .freeze();
960                let (root, updates) =
961                    storage_root_with_progress(&harness, changes, true, threshold);
962                assert_eq!(root, expected_root);
963
964                let mut recovered_nodes = stored_nodes.clone();
965                for (path, node) in updates.into_sorted().storage_nodes {
966                    if let Some(node) = node {
967                        recovered_nodes.insert(path, node);
968                    } else {
969                        recovered_nodes.remove(&path);
970                    }
971                }
972
973                // Proof V2 over the recovered table, no prefix set, one target under the live
974                // child.
975                harness.set_trie_nodes(recovered_nodes.clone());
976                let tcf = harness.trie_cursor_factory();
977                let hcf = harness.hashed_cursor_factory();
978                let mut calc = StorageProofCalculator::new_storage(
979                    tcf.storage_trie_cursor(harness.hashed_address()).unwrap(),
980                    hcf.hashed_storage_cursor(harness.hashed_address()).unwrap(),
981                );
982                let mut targets = vec![ProofV2Target::new(key(&[0x5, 0xa, 0x2, 0x2]))];
983                let nodes = calc.storage_proof(harness.hashed_address(), &mut targets).unwrap();
984                let v2_root = calc.compute_root_hash(&nodes).unwrap();
985
986                assert_eq!(recovered_nodes.contains_key(&stale), regenerate_sibling);
987                assert_eq!(v2_root, Some(expected_root));
988                assert_eq!(recovered_nodes, expected_nodes);
989            }
990        }
991    }
992
993    #[reth_concurrency::test]
994    fn extension_cleanup_skips_live_subtrees() {
995        for child in [[0x5, 0xa], [0xf, 0xf]] {
996            let child = Nibbles::from_nibbles(child);
997            let mut live = child;
998            live.push(2);
999            let mut stale = child;
1000            stale.push(7);
1001            let mut descendant = stale;
1002            descendant.push(1);
1003            let mut nodes = BTreeMap::from([
1004                (live, branch_node(0b11, 0, 0)),
1005                (stale, branch_node(0b11, 0, 0)),
1006                (descendant, branch_node(0b11, 0, 0)),
1007            ]);
1008            if let Some(next_child) = child.next_without_prefix() {
1009                nodes.insert(next_child, branch_node(0b11, 0, 0));
1010            }
1011            for index in 0..128 {
1012                let mut path = live;
1013                path.push(index / 16);
1014                path.push(index % 16);
1015                nodes.insert(path, branch_node(0b11, 0, 0));
1016            }
1017            let factory = MockTrieCursorFactory::new(nodes, B256Map::default());
1018            let changes = PrefixSetMut::from([stale]).freeze();
1019            let mut walker =
1020                TrieWalker::<_>::state_trie(factory.account_trie_cursor().unwrap(), changes)
1021                    .unwrap()
1022                    .with_walk_all_changed_branch_children(true)
1023                    .with_deletions_retained(true);
1024            walker.cursor.seek_exact(live).unwrap();
1025            factory.visited_account_keys().clear();
1026            walker.remove_orphaned_descendants(child, live, TrieMask::new(u16::MAX)).unwrap();
1027
1028            assert_eq!(walker.take_removed_keys(), HashSet::from_iter([stale, descendant]));
1029            assert_eq!(walker.cursor.current().unwrap(), Some(live));
1030            let next_count = factory
1031                .visited_account_keys()
1032                .iter()
1033                .filter(|visit| matches!(visit.visit_type, KeyVisitType::Next))
1034                .count();
1035            assert_eq!(next_count, 2, "cleanup must not traverse live descendants");
1036        }
1037    }
1038
1039    proptest! {
1040        #[reth_concurrency::test]
1041        fn extension_cleanup_respects_bounds_and_recovery_mode(
1042            prefix in prop::collection::vec(0u8..16, 1..16),
1043            live_nibble in 0u8..15,
1044            enabled in any::<bool>(),
1045            retained in any::<bool>(),
1046            changed in any::<bool>(),
1047        ) {
1048            let child = Nibbles::from_nibbles(&prefix);
1049            let mut live = child;
1050            live.push(live_nibble);
1051            let mut stale = child;
1052            stale.push(live_nibble + 1);
1053            let mut live_descendant = live;
1054            live_descendant.push(0);
1055            let mut nodes = BTreeMap::from([
1056                (live, branch_node(0b11, 0, 0)),
1057                (live_descendant, branch_node(0b11, 0, 0)),
1058                (stale, branch_node(0b11, 0, 0)),
1059            ]);
1060            if let Some(next_child) = child.next_without_prefix() {
1061                nodes.insert(next_child, branch_node(0b11, 0, 0));
1062            }
1063            let factory = MockTrieCursorFactory::new(nodes, B256Map::default());
1064            let changes = if changed {
1065                PrefixSetMut::from([stale]).freeze()
1066            } else {
1067                PrefixSet::default()
1068            };
1069            let mut walker =
1070                TrieWalker::<_>::state_trie(factory.account_trie_cursor().unwrap(), changes)
1071                    .unwrap()
1072                    .with_walk_all_changed_branch_children(enabled)
1073                    .with_deletions_retained(retained);
1074            walker.cursor.seek_exact(live).unwrap();
1075            walker.remove_orphaned_descendants(child, live, TrieMask::new(u16::MAX)).unwrap();
1076            let expected = if enabled && retained && changed {
1077                HashSet::from_iter([stale])
1078            } else {
1079                HashSet::default()
1080            };
1081            prop_assert_eq!(walker.take_removed_keys(), expected);
1082            prop_assert_eq!(walker.cursor.current().unwrap(), Some(live));
1083        }
1084    }
1085}