Skip to main content

reth_trie/
node_iter.rs

1use crate::{
2    hashed_cursor::HashedCursor, trie_cursor::TrieCursor, walker::TrieWalker, Nibbles, TrieType,
3};
4use alloy_primitives::B256;
5use alloy_trie::proof::AddedRemovedKeys;
6use reth_storage_errors::db::DatabaseError;
7use tracing::{instrument, trace};
8
9/// Represents a branch node in the trie.
10#[derive(Debug)]
11pub struct TrieBranchNode {
12    /// The key associated with the node.
13    pub key: Nibbles,
14    /// The value associated with the node.
15    pub value: B256,
16    /// Indicates whether children are in the trie.
17    pub children_are_in_trie: bool,
18}
19
20impl TrieBranchNode {
21    /// Creates a new `TrieBranchNode`.
22    pub const fn new(key: Nibbles, value: B256, children_are_in_trie: bool) -> Self {
23        Self { key, value, children_are_in_trie }
24    }
25}
26
27/// Represents variants of trie nodes returned by the iteration.
28#[derive(Debug)]
29pub enum TrieElement<Value> {
30    /// Branch node.
31    Branch(TrieBranchNode),
32    /// Leaf node.
33    Leaf(B256, Value),
34}
35
36/// Result of calling [`HashedCursor::seek`].
37#[derive(Debug)]
38struct SeekedHashedEntry<V> {
39    /// The key that was seeked.
40    seeked_key: B256,
41    /// The result of the seek.
42
43    /// If no entry was found for the provided key, this will be [`None`].
44    result: Option<(B256, V)>,
45}
46
47/// Iterates over trie nodes for hash building.
48///
49/// This iterator depends on the ordering guarantees of [`TrieCursor`],
50/// and additionally uses hashed cursor lookups when operating on storage tries.
51#[derive(Debug)]
52pub struct TrieNodeIter<C, H: HashedCursor, K> {
53    /// The walker over intermediate nodes.
54    pub walker: TrieWalker<C, K>,
55    /// The cursor for the hashed entries.
56    pub hashed_cursor: H,
57    /// The type of the trie.
58    trie_type: TrieType,
59    /// The previous hashed key. If the iteration was previously interrupted, this value can be
60    /// used to resume iterating from the last returned leaf node.
61    previous_hashed_key: Option<B256>,
62
63    /// Current hashed  entry.
64    current_hashed_entry: Option<(B256, H::Value)>,
65    /// Flag indicating whether we should check the current walker key.
66    should_check_walker_key: bool,
67
68    /// The last seeked hashed entry.
69    ///
70    /// We use it to not seek the same hashed entry twice, and instead reuse it.
71    last_seeked_hashed_entry: Option<SeekedHashedEntry<H::Value>>,
72
73    #[cfg(feature = "metrics")]
74    metrics: crate::metrics::TrieNodeIterMetrics,
75    /// Stores the result of the last successful [`Self::next_hashed_entry`], used to avoid a
76    /// redundant [`Self::seek_hashed_entry`] call if the walker points to the same key that
77    /// was just returned by `next()`.
78    last_next_result: Option<(B256, H::Value)>,
79}
80
81impl<C, H: HashedCursor, K> TrieNodeIter<C, H, K>
82where
83    H::Value: Clone,
84    K: AsRef<AddedRemovedKeys>,
85{
86    /// Creates a new [`TrieNodeIter`] for the state trie.
87    pub fn state_trie(walker: TrieWalker<C, K>, hashed_cursor: H) -> Self {
88        Self::new(walker, hashed_cursor, TrieType::State)
89    }
90
91    /// Creates a new [`TrieNodeIter`] for the storage trie.
92    pub fn storage_trie(walker: TrieWalker<C, K>, hashed_cursor: H) -> Self {
93        Self::new(walker, hashed_cursor, TrieType::Storage)
94    }
95
96    /// Creates a new [`TrieNodeIter`].
97    #[allow(clippy::missing_const_for_fn)]
98    fn new(walker: TrieWalker<C, K>, hashed_cursor: H, trie_type: TrieType) -> Self {
99        Self {
100            walker,
101            hashed_cursor,
102            trie_type,
103            previous_hashed_key: None,
104            current_hashed_entry: None,
105            should_check_walker_key: false,
106            last_seeked_hashed_entry: None,
107            #[cfg(feature = "metrics")]
108            metrics: crate::metrics::TrieNodeIterMetrics::new(trie_type),
109            last_next_result: None,
110        }
111    }
112
113    /// Sets the last iterated hashed key and returns the modified [`TrieNodeIter`].
114    /// This is used to resume iteration from the last checkpoint.
115    pub const fn with_last_hashed_key(mut self, previous_hashed_key: B256) -> Self {
116        self.previous_hashed_key = Some(previous_hashed_key);
117        // Pending leaves may sort before the restored walker's skippable branch.
118        self.should_check_walker_key = true;
119        self
120    }
121
122    /// Seeks the hashed cursor to the given key.
123    ///
124    /// If the key is the same as the last seeked key, the result of the last seek is returned.
125    ///
126    /// If `metrics` feature is enabled, it also updates the metrics.
127    fn seek_hashed_entry(&mut self, key: B256) -> Result<Option<(B256, H::Value)>, DatabaseError> {
128        if let Some((last_key, _)) = self.last_next_result.as_ref() &&
129            *last_key == key
130        {
131            trace!(target: "trie::node_iter", seek_key = ?key, "reusing result from last next() call instead of seeking");
132            let result = self.last_next_result.take();
133            self.last_seeked_hashed_entry =
134                Some(SeekedHashedEntry { seeked_key: key, result: result.clone() });
135
136            return Ok(result);
137        }
138
139        if let Some(entry) = self
140            .last_seeked_hashed_entry
141            .as_ref()
142            .filter(|entry| entry.seeked_key == key)
143            .map(|entry| entry.result.clone())
144        {
145            #[cfg(feature = "metrics")]
146            self.metrics.inc_leaf_nodes_same_seeked();
147            return Ok(entry);
148        }
149
150        trace!(target: "trie::node_iter", ?key, "performing hashed cursor seek");
151        let result = self.hashed_cursor.seek(key)?;
152        self.last_seeked_hashed_entry =
153            Some(SeekedHashedEntry { seeked_key: key, result: result.clone() });
154
155        #[cfg(feature = "metrics")]
156        {
157            self.metrics.inc_leaf_nodes_seeked();
158        }
159        Ok(result)
160    }
161
162    /// Advances the hashed cursor to the next entry.
163    ///
164    /// If `metrics` feature is enabled, it also updates the metrics.
165    fn next_hashed_entry(&mut self) -> Result<Option<(B256, H::Value)>, DatabaseError> {
166        let next = self.hashed_cursor.next()?;
167
168        self.last_next_result = next.clone();
169
170        #[cfg(feature = "metrics")]
171        {
172            self.metrics.inc_leaf_nodes_advanced();
173        }
174        Ok(next)
175    }
176}
177
178impl<C, H, K> TrieNodeIter<C, H, K>
179where
180    C: TrieCursor,
181    H: HashedCursor,
182    H::Value: Clone,
183    K: AsRef<AddedRemovedKeys>,
184{
185    /// Return the next trie node to be added to the hash builder.
186    ///
187    /// Returns the nodes using this algorithm:
188    /// 1. Return the current intermediate branch node if it hasn't been updated.
189    /// 2. Advance the trie walker to the next intermediate branch node and retrieve next
190    ///    unprocessed key.
191    /// 3. Reposition the hashed cursor on the next unprocessed key.
192    /// 4. Return every hashed entry up to the key of the current intermediate branch node.
193    /// 5. Repeat.
194    ///
195    /// NOTE: The iteration will start from the key of the previous hashed entry if it was supplied.
196    #[instrument(
197        level = "trace",
198        target = "trie::node_iter",
199        skip_all,
200        fields(trie_type = ?self.trie_type),
201        ret
202    )]
203    pub fn try_next(
204        &mut self,
205    ) -> Result<Option<TrieElement<<H as HashedCursor>::Value>>, DatabaseError> {
206        loop {
207            // If the walker has a key...
208            if let Some(key) = self.walker.key() {
209                // Ensure that the current walker key shouldn't be checked and there's no previous
210                // hashed key
211                if !self.should_check_walker_key && self.previous_hashed_key.is_none() {
212                    // Make sure we check the next walker key, because we only know we can skip the
213                    // current one.
214                    self.should_check_walker_key = true;
215                    // If it's possible to skip the current node in the walker, return a branch node
216                    if self.walker.can_skip_current_node {
217                        #[cfg(feature = "metrics")]
218                        self.metrics.inc_branch_nodes_returned();
219                        return Ok(Some(TrieElement::Branch(TrieBranchNode::new(
220                            *key,
221                            self.walker.hash().unwrap(),
222                            self.walker.children_are_in_trie(),
223                        ))))
224                    }
225                }
226            }
227
228            // If there's a hashed entry...
229            if let Some((hashed_key, value)) = self.current_hashed_entry.take() {
230                // Check if the walker's key is less than the key of the current hashed entry
231                if self.walker.key().is_some_and(|key| key < &Nibbles::unpack(hashed_key)) {
232                    self.should_check_walker_key = false;
233                    continue
234                }
235
236                // Set the next hashed entry as a leaf node and return
237                trace!(target: "trie::node_iter", ?hashed_key, "next hashed entry");
238                self.current_hashed_entry = self.next_hashed_entry()?;
239
240                #[cfg(feature = "metrics")]
241                self.metrics.inc_leaf_nodes_returned();
242                return Ok(Some(TrieElement::Leaf(hashed_key, value)))
243            }
244
245            // Handle seeking and advancing based on the previous hashed key
246            match self.previous_hashed_key.take() {
247                Some(hashed_key) => {
248                    trace!(target: "trie::node_iter", ?hashed_key, "seeking to the previous hashed entry");
249                    // Seek to the previous hashed key and get the next hashed entry
250                    self.seek_hashed_entry(hashed_key)?;
251                    self.current_hashed_entry = self.next_hashed_entry()?;
252                }
253                None => {
254                    // Get the seek key and set the current hashed entry based on walker's next
255                    // unprocessed key
256                    let (seek_key, seek_prefix) = match self.walker.next_unprocessed_key() {
257                        Some(key) => key,
258                        None => break, // no more keys
259                    };
260
261                    trace!(
262                        target: "trie::node_iter",
263                        ?seek_key,
264                        can_skip_current_node = self.walker.can_skip_current_node,
265                        last = ?self.walker.stack.last(),
266                        "seeking to the next unprocessed hashed entry"
267                    );
268                    let can_skip_node = self.walker.can_skip_current_node;
269                    self.walker.advance()?;
270                    trace!(
271                        target: "trie::node_iter",
272                        last = ?self.walker.stack.last(),
273                        "advanced walker"
274                    );
275
276                    // We should get the iterator to return a branch node if we can skip the
277                    // current node and the tree flag for the current node is set.
278                    //
279                    // `can_skip_node` is already set when the hash flag is set, so we don't need
280                    // to check for the hash flag explicitly.
281                    //
282                    // A deeper stored key may leave unvisited hashed entries between the seek
283                    // prefix and the walker, so only skip the seek at the exact prefix.
284                    if can_skip_node &&
285                        self.walker.key().is_some_and(|key| key == &seek_prefix) &&
286                        self.walker.children_are_in_trie()
287                    {
288                        trace!(
289                            target: "trie::node_iter",
290                            ?seek_key,
291                            walker_hash = ?self.walker.maybe_hash(),
292                            "skipping hashed seek"
293                        );
294
295                        self.should_check_walker_key = false;
296                        continue
297                    }
298
299                    self.current_hashed_entry = self.seek_hashed_entry(seek_key)?;
300                }
301            }
302        }
303
304        Ok(None)
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use super::*;
311    use crate::{
312        hashed_cursor::{
313            mock::MockHashedCursorFactory,
314            noop::{NoopHashedCursor, NoopHashedCursorFactory},
315            HashedCursorFactory, HashedPostStateCursor, HashedPostStateCursorFactory,
316        },
317        mock::{KeyVisit, KeyVisitType},
318        trie_cursor::{
319            mock::MockTrieCursorFactory,
320            noop::{NoopAccountTrieCursor, NoopTrieCursorFactory},
321            InMemoryTrieCursorFactory, TrieCursorFactory,
322        },
323        walker::TrieWalker,
324        StateRoot, StateRootProgress,
325    };
326    use alloy_primitives::{
327        b256,
328        map::{B256Map, HashMap},
329        B256, U256,
330    };
331    use alloy_trie::{
332        BranchNodeCompact, HashBuilder, Nibbles, TrieAccount, TrieMask, EMPTY_ROOT_HASH,
333    };
334    use itertools::Itertools;
335    use reth_primitives_traits::Account;
336    use reth_trie_common::{
337        prefix_set::PrefixSetMut, updates::TrieUpdates, BranchNode, HashedPostState, HashedStorage,
338        LeafNode, RlpNode,
339    };
340    use std::collections::BTreeMap;
341
342    /// Calculate the branch node stored in the database by feeding the provided state to the hash
343    /// builder and taking the trie updates.
344    fn get_hash_builder_branch_nodes(
345        state: impl IntoIterator<Item = (Nibbles, Account)> + Clone,
346    ) -> HashMap<Nibbles, BranchNodeCompact> {
347        let mut hash_builder = HashBuilder::default().with_updates(true);
348
349        let mut prefix_set = PrefixSetMut::default();
350        prefix_set.extend_keys(state.clone().into_iter().map(|(nibbles, _)| nibbles));
351        let walker =
352            TrieWalker::<_>::state_trie(NoopAccountTrieCursor, prefix_set.freeze()).unwrap();
353
354        let hashed_post_state = HashedPostState::default()
355            .with_accounts(state.into_iter().map(|(nibbles, account)| {
356                (nibbles.pack().into_inner().unwrap().into(), Some(account))
357            }))
358            .into_sorted();
359
360        let mut node_iter = TrieNodeIter::state_trie(
361            walker,
362            HashedPostStateCursor::new_account(
363                NoopHashedCursor::<Account>::default(),
364                &hashed_post_state,
365            ),
366        );
367
368        while let Some(node) = node_iter.try_next().unwrap() {
369            match node {
370                TrieElement::Branch(branch) => {
371                    hash_builder.add_branch(branch.key, branch.value, branch.children_are_in_trie);
372                }
373                TrieElement::Leaf(key, account) => {
374                    hash_builder.add_leaf(
375                        Nibbles::unpack(key),
376                        &alloy_rlp::encode(account.into_trie_account(EMPTY_ROOT_HASH)),
377                    );
378                }
379            }
380        }
381        hash_builder.root();
382
383        let mut trie_updates = TrieUpdates::default();
384        trie_updates.finalize(hash_builder, Default::default(), Default::default());
385
386        trie_updates.account_nodes
387    }
388
389    #[reth_concurrency::test]
390    fn inserted_leaf_before_deeper_stored_branch_is_included() {
391        fn slot(prefix: &[u8]) -> B256 {
392            let mut bytes = [0; 32];
393            bytes[..prefix.len()].copy_from_slice(prefix);
394            B256::from(bytes)
395        }
396
397        let address = B256::repeat_byte(0xaa);
398        let account = || Account { nonce: 1, ..Default::default() };
399        let old_slots = [
400            slot(&[0x00]),
401            slot(&[0x0f, 0x00]),
402            slot(&[0x0f, 0x10]),
403            slot(&[0x10, 0xa0, 0x00]),
404            slot(&[0x10, 0xa0, 0x01]),
405            slot(&[0x10, 0xa0, 0x10]),
406            slot(&[0x10, 0xa1]),
407        ];
408        let inserted = slot(&[0x10, 0x00]);
409        let old_state =
410            HashedPostState::default().with_accounts([(address, Some(account()))]).with_storages([
411                (address, HashedStorage::from_iter(old_slots.map(|slot| (slot, U256::from(1))))),
412            ]);
413        let old_sorted = old_state.clone().into_sorted();
414        let (old_root, old_updates) = StateRoot::new(
415            NoopTrieCursorFactory::default(),
416            HashedPostStateCursorFactory::new(NoopHashedCursorFactory::default(), &old_sorted),
417        )
418        .with_prefix_sets(old_state.construct_prefix_sets().freeze())
419        .root_with_updates()
420        .unwrap();
421
422        let new_state = HashedPostState::default()
423            .with_accounts([(address, Some(account()))])
424            .with_storages([(
425                address,
426                HashedStorage::from_iter(
427                    old_slots.into_iter().chain([inserted]).map(|slot| (slot, U256::from(1))),
428                ),
429            )]);
430        let delta = HashedPostState::default()
431            .with_accounts([(address, Some(account()))])
432            .with_storages([(address, HashedStorage::from_iter([(inserted, U256::from(1))]))]);
433        let new_sorted = new_state.clone().into_sorted();
434        let rebuilt_root = StateRoot::new(
435            NoopTrieCursorFactory::default(),
436            HashedPostStateCursorFactory::new(NoopHashedCursorFactory::default(), &new_sorted),
437        )
438        .with_prefix_sets(new_state.construct_prefix_sets().freeze())
439        .root()
440        .unwrap();
441        let old_trie = old_updates.into_sorted();
442        let incremental_root = StateRoot::new(
443            InMemoryTrieCursorFactory::new(NoopTrieCursorFactory::default(), &old_trie),
444            HashedPostStateCursorFactory::new(NoopHashedCursorFactory::default(), &new_sorted),
445        )
446        .with_prefix_sets(delta.construct_prefix_sets().freeze())
447        .root()
448        .unwrap();
449
450        assert_ne!(old_root, rebuilt_root);
451        assert_eq!(incremental_root, rebuilt_root);
452    }
453
454    #[reth_concurrency::test]
455    fn test_trie_node_iter() {
456        reth_tracing::init_test_tracing();
457
458        fn empty_leaf_rlp_for_key(key: Nibbles) -> RlpNode {
459            RlpNode::from_rlp(&alloy_rlp::encode(LeafNode::new(
460                key,
461                alloy_rlp::encode(TrieAccount::default()),
462            )))
463        }
464
465        // Extension (Key = 0x0000000000000000000000000000000000000000000000000000000000000)
466        // └── Branch (`branch_node_0`)
467        //     ├── 0 -> Branch (`branch_node_1`)
468        //     │      ├── 0 -> Leaf (`account_1`, Key = 0x0)
469        //     │      └── 1 -> Leaf (`account_2`, Key = 0x0)
470        //     ├── 1 -> Branch (`branch_node_2`)
471        //     │      ├── 0 -> Branch (`branch_node_3`)
472        //     │      │      ├── 0 -> Leaf (`account_3`, marked as changed)
473        //     │      │      └── 1 -> Leaf (`account_4`)
474        //     │      └── 1 -> Leaf (`account_5`, Key = 0x0)
475
476        let account_1 = B256::ZERO;
477        let account_2 = B256::with_last_byte(0x10);
478        let account_3 = b256!("0x0000000000000000000000000000000000000000000000000000000000000100");
479        let account_4 = b256!("0x0000000000000000000000000000000000000000000000000000000000000101");
480        let account_5 = b256!("0x0000000000000000000000000000000000000000000000000000000000000110");
481
482        let hash_builder_branch_nodes = get_hash_builder_branch_nodes(vec![
483            (Nibbles::unpack(account_1), Account::default()),
484            (Nibbles::unpack(account_2), Account::default()),
485            (Nibbles::unpack(account_3), Account::default()),
486            (Nibbles::unpack(account_4), Account::default()),
487            (Nibbles::unpack(account_5), Account::default()),
488        ]);
489
490        let branch_node_1_rlp = RlpNode::from_rlp(&alloy_rlp::encode(BranchNode::new(
491            vec![
492                empty_leaf_rlp_for_key(Nibbles::from_nibbles([0])),
493                empty_leaf_rlp_for_key(Nibbles::from_nibbles([0])),
494            ],
495            TrieMask::new(0b11),
496        )));
497
498        let branch_node_3_rlp = RlpNode::from_rlp(&alloy_rlp::encode(BranchNode::new(
499            vec![
500                empty_leaf_rlp_for_key(Nibbles::default()),
501                empty_leaf_rlp_for_key(Nibbles::default()),
502            ],
503            TrieMask::new(0b11),
504        )));
505
506        let branch_node_2 = (
507            Nibbles::from_nibbles([vec![0; 61], vec![1]].concat()),
508            BranchNodeCompact::new(
509                TrieMask::new(0b11),
510                TrieMask::new(0b00),
511                TrieMask::new(0b01),
512                vec![branch_node_3_rlp.as_hash().unwrap()],
513                None,
514            ),
515        );
516        let branch_node_2_rlp = RlpNode::from_rlp(&alloy_rlp::encode(BranchNode::new(
517            vec![branch_node_3_rlp, empty_leaf_rlp_for_key(Nibbles::from_nibbles([0]))],
518            TrieMask::new(0b11),
519        )));
520        let branch_node_0 = (
521            Nibbles::from_nibbles([0; 61]),
522            BranchNodeCompact::new(
523                TrieMask::new(0b11),
524                TrieMask::new(0b10),
525                TrieMask::new(0b11),
526                vec![branch_node_1_rlp.as_hash().unwrap(), branch_node_2_rlp.as_hash().unwrap()],
527                None,
528            ),
529        );
530
531        let mock_trie_nodes = vec![branch_node_0.clone(), branch_node_2.clone()];
532        pretty_assertions::assert_eq!(
533            hash_builder_branch_nodes.into_iter().sorted().collect::<Vec<_>>(),
534            mock_trie_nodes,
535        );
536
537        let trie_cursor_factory =
538            MockTrieCursorFactory::new(mock_trie_nodes.into_iter().collect(), B256Map::default());
539
540        // Mark the account 3 as changed.
541        let mut prefix_set = PrefixSetMut::default();
542        prefix_set.insert(Nibbles::unpack(account_3));
543        let prefix_set = prefix_set.freeze();
544
545        let walker = TrieWalker::<_>::state_trie(
546            trie_cursor_factory.account_trie_cursor().unwrap(),
547            prefix_set,
548        )
549        .unwrap();
550
551        let hashed_cursor_factory = MockHashedCursorFactory::new(
552            BTreeMap::from([
553                (account_1, Account::default()),
554                (account_2, Account::default()),
555                (account_3, Account::default()),
556                (account_4, Account::default()),
557                (account_5, Account::default()),
558            ]),
559            B256Map::default(),
560        );
561
562        let mut iter = TrieNodeIter::state_trie(
563            walker,
564            hashed_cursor_factory.hashed_account_cursor().unwrap(),
565        );
566
567        // Walk the iterator until it's exhausted.
568        while iter.try_next().unwrap().is_some() {}
569
570        pretty_assertions::assert_eq!(
571            *trie_cursor_factory.visited_account_keys(),
572            vec![
573                KeyVisit {
574                    visit_type: KeyVisitType::SeekExact(Nibbles::default()),
575                    visited_key: None
576                },
577                KeyVisit {
578                    visit_type: KeyVisitType::SeekNonExact(Nibbles::from_nibbles([0x0])),
579                    visited_key: Some(branch_node_0.0)
580                },
581                KeyVisit {
582                    visit_type: KeyVisitType::SeekNonExact(branch_node_2.0),
583                    visited_key: Some(branch_node_2.0)
584                },
585                KeyVisit {
586                    visit_type: KeyVisitType::SeekNonExact(Nibbles::from_nibbles([0x1])),
587                    visited_key: None
588                }
589            ]
590        );
591        pretty_assertions::assert_eq!(
592            *hashed_cursor_factory.visited_account_keys(),
593            vec![
594                // Why do we always seek this key first?
595                KeyVisit {
596                    visit_type: KeyVisitType::SeekNonExact(account_1),
597                    visited_key: Some(account_1)
598                },
599                // Seek to the modified account.
600                KeyVisit {
601                    visit_type: KeyVisitType::SeekNonExact(account_3),
602                    visited_key: Some(account_3)
603                },
604                // Collect the siblings of the modified account
605                KeyVisit { visit_type: KeyVisitType::Next, visited_key: Some(account_4) },
606                KeyVisit { visit_type: KeyVisitType::Next, visited_key: Some(account_5) },
607                KeyVisit { visit_type: KeyVisitType::Next, visited_key: None },
608            ],
609        );
610    }
611
612    #[reth_concurrency::test]
613    fn resumed_root_emits_pending_leaf_before_cached_branch() {
614        let first = B256::ZERO;
615        let inserted = b256!("0001000000000000000000000000000000000000000000000000000000000000");
616        let branch_first =
617            b256!("0f00000000000000000000000000000000000000000000000000000000000000");
618        let branch_second =
619            b256!("0f10000000000000000000000000000000000000000000000000000000000000");
620        let old_keys = [first, branch_first, branch_second];
621        let live_keys = [first, inserted, branch_first, branch_second];
622        let factories = |stored, keys: &[B256]| {
623            (
624                MockTrieCursorFactory::new(
625                    stored,
626                    keys.iter().map(|key| (*key, BTreeMap::new())).collect(),
627                ),
628                MockHashedCursorFactory::new(
629                    keys.iter()
630                        .map(|key| (*key, Account { nonce: 1, ..Default::default() }))
631                        .collect(),
632                    keys.iter().map(|key| (*key, BTreeMap::new())).collect(),
633                ),
634            )
635        };
636
637        let (trie, hashed) = factories(BTreeMap::new(), &old_keys);
638        let (_, updates) = StateRoot::new(trie, hashed).root_with_updates().unwrap();
639        let stored = updates.account_nodes.into_iter().collect::<BTreeMap<_, _>>();
640        let (trie, hashed) = factories(BTreeMap::new(), &live_keys);
641        let expected = StateRoot::new(trie, hashed).root().unwrap();
642        let (trie, hashed) = factories(stored.clone(), &live_keys);
643        assert_eq!(StateRoot::new(trie, hashed).root().unwrap(), expected);
644
645        let (trie, hashed) = factories(stored.clone(), &live_keys);
646        let StateRootProgress::Progress(checkpoint, _, _) =
647            StateRoot::new(trie, hashed).with_threshold(1).root_with_progress().unwrap()
648        else {
649            panic!("expected a checkpoint after the first leaf")
650        };
651        assert_eq!(checkpoint.account_root_state.last_hashed_key, first);
652        assert_eq!(checkpoint.account_root_state.walker_stack.len(), 2);
653        assert!(checkpoint.account_root_state.walker_stack[1].hash_flag());
654
655        // The restored walker can skip [0, f], but the leaf at [0, 0, 0, 1] comes first.
656        let (trie, hashed) = factories(stored, &live_keys);
657        let StateRootProgress::Complete(root, _, _) = StateRoot::new(trie, hashed)
658            .with_intermediate_state(Some(*checkpoint))
659            .with_no_threshold()
660            .root_with_progress()
661            .unwrap()
662        else {
663            panic!("expected the resumed root to finish")
664        };
665        assert_eq!(root, expected);
666    }
667}