Skip to main content

reth_trie/proof_v2/
calculator.rs

1//! Proof calculation version 2 using leaf data and cached branch hashes.
2//!
3//! This module provides a rewritten proof calculator that:
4//! - Combines hashed account or storage leaves with cached branch hashes from a trie cursor.
5//! - Recalculates subtries containing proof targets or changed keys instead of using cached hashes.
6//! - Returns proof nodes in depth-first post-order (children before parents).
7//! - Automatically resets after each calculation
8//! - Re-uses cursors across calculations
9//! - Supports generic value types with lazy evaluation
10
11use 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
27/// Number of bytes to pre-allocate for [`ProofCalculator`]'s `rlp_encode_buf` field.
28const RLP_ENCODE_BUF_SIZE: usize = 1024;
29
30/// A proof calculator that generates Merkle proofs from leaf data and cached branch hashes.
31///
32/// The hashed cursor supplies leaves, while the trie cursor supplies cached branch hashes to skip
33/// subtries. Subtries containing proof targets or keys in the configured prefix set are
34/// recalculated.
35///
36/// The calculator:
37/// - Accepts proof targets in any order and sorts them in place by parent context, then key.
38/// - Returns proof nodes in depth-first post-order (children before parents).
39/// - Automatically resets after each calculation
40/// - Re-uses cursors from one calculation to the next
41#[derive(Debug)]
42pub struct ProofCalculator<TC, HC, VE: LeafValueEncoder> {
43    /// Trie cursor for traversing stored branch nodes.
44    trie_cursor: TC,
45    /// Hashed cursor for iterating over leaf data.
46    hashed_cursor: HC,
47    /// Branches which are currently in the process of being constructed, each being a child of
48    /// the previous one.
49    branch_stack: Vec<ProofTrieBranch>,
50    /// The path of the last branch in `branch_stack`.
51    branch_path: Nibbles,
52    /// Children of branches in the `branch_stack`.
53    ///
54    /// Each branch in `branch_stack` tracks which children are in this stack using its
55    /// `state_mask`; the number of children the branch has in this stack is equal to the number of
56    /// bits set in its `state_mask`.
57    ///
58    /// The children for the bottom branch in `branch_stack` are found at the bottom of this stack,
59    /// and so on. When a branch is removed from `branch_stack` its children are removed from this
60    /// one, and the branch is pushed onto this stack in their place (see [`Self::pop_branch`].
61    ///
62    /// Given that keys are consumed in lexicographical order, only the last child on the stack
63    /// can still require structural changes (e.g. splitting its short key when inserting a new
64    /// branch). Once a child is finalized, [`Self::commit_last_child`] converts it to a
65    /// [`ProofTrieBranchChild::RlpNode`] if retained for the proof. Unretained children can remain
66    /// unencoded anywhere on the stack until [`Self::pop_branch`], giving deferred encoders more
67    /// time for async work.
68    child_stack: Vec<ProofTrieBranchChild<VE::DeferredEncoder>>,
69    /// Cached branch data pulled from the `trie_cursor`. The calculator will use the cached
70    /// [`BranchNodeCompact::hashes`] to skip over the calculation of sub-tries in the overall
71    /// trie. The cached hashes cannot be used for any paths which are prefixes of a proof target.
72    cached_branch_stack: Vec<(Nibbles, BranchNodeCompact)>,
73    /// The proofs which will be returned from the calculation. This gets taken at the end of every
74    /// proof call.
75    retained_proofs: Vec<ProofTrieNode>,
76    /// Free-list of re-usable buffers of [`RlpNode`]s, used for encoding branch nodes to RLP.
77    ///
78    /// We are generally able to re-use these buffers across different branch nodes for the
79    /// duration of a proof calculation, but occasionally we will lose one when a branch
80    /// node is returned as a `ProofTrieNode`.
81    rlp_nodes_bufs: Vec<Vec<RlpNode>>,
82    /// Re-usable byte buffer, used for RLP encoding.
83    rlp_encode_buf: Vec<u8>,
84    /// Prefix set for tracking changed keys.
85    prefix_set: PrefixSet,
86}
87
88impl<TC, HC, VE: LeafValueEncoder> ProofCalculator<TC, HC, VE> {
89    /// Create a new [`ProofCalculator`] instance for calculating account proofs.
90    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    /// Sets the prefix set and returns `self`.
106    ///
107    /// When given, all cached hashes matching the [`PrefixSet`] will be invalidated and their
108    /// subtries recalculated.
109    pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {
110        self.prefix_set = prefix_set;
111        self
112    }
113
114    /// Replaces the changed-key prefixes applied to subsequent calculations.
115    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    /// Takes a re-usable `RlpNode` buffer from the internal free-list, or allocates a new one if
127    /// the free-list is empty.
128    ///
129    /// The returned Vec will have a length of zero.
130    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    // Returns zero if `branch_stack` is empty, one otherwise.
141    //
142    // This is used when working with the `ext_len` field of [`ProofTrieBranch`]. The `ext_len` is
143    // calculated by taking the difference of the current `branch_path` and the new branch's path;
144    // if the new branch has a parent branch (ie `branch_stack` is not empty) then 1 is subtracted
145    // from the `ext_len` to account for the child's nibble on the parent.
146    #[inline]
147    const fn maybe_parent_nibble(&self) -> usize {
148        !self.branch_stack.is_empty() as usize
149    }
150
151    /// Returns true if the proof of a node at the given path should be retained. A node is retained
152    /// if its path is a prefix of any target.
153    ///
154    /// This may move the `targets` iterator forward if the given path comes after the current
155    /// target.
156    ///
157    /// This method takes advantage of the [`std::slice::Iter`] component of [`TargetsCursor`] to
158    /// check the minimum number of targets. In general it looks at a current target and the next
159    /// target simultaneously, forming an end-exclusive range.
160    ///
161    /// ```text
162    /// * Given targets: [ 0x012, 0x045, 0x678 ]
163    /// * targets.current() returns:
164    ///     - (0x012, Some(0x045)): covers (0x012..0x045)
165    ///     - (0x045, Some(0x678)): covers (0x045..0x678)
166    ///     - (0x678, None): covers (0x678..)
167    /// ```
168    ///
169    /// As long as the path which is passed in lies within that range we can continue to use the
170    /// current target. Once the path goes beyond that range (ie path >= next target) then we can be
171    /// sure that no further paths will be in the range, and we can iterate forward.
172    ///
173    /// ```text
174    /// * Given:
175    ///     - path: 0x04
176    ///     - targets.current() returns (0x012, Some(0x045))
177    ///
178    /// * 0x04 comes _after_ 0x045 in depth-first order, so (0x012..0x045) does not contain 0x04.
179    ///
180    /// * targets.next() is called.
181    ///
182    /// * targets.current() now returns (0x045, Some(0x678)). This does contain 0x04.
183    ///
184    /// * 0x04 is a prefix of 0x045, and so is retained.
185    /// ```
186    #[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        // If no targets are given then we never retain anything
200        let Some(targets) = targets.as_mut() else { return false };
201
202        let (mut lower, mut upper) = targets.current();
203
204        loop {
205            // If the node in question is a prefix of the target then we do not iterate targets
206            // further.
207            //
208            // Even if the node is a prefix of the target's key, a target with a parent path only
209            // retains nodes strictly below that already-revealed parent.
210            //
211            // _However_ even if the node doesn't match one target due to its parent path, it may
212            // match other targets whose keys match this node. So we search forwards and backwards
213            // for all targets which might match this node.
214            //
215            // For example, given a branch 0xabc, with children at 0, 1, and 2, and targets:
216            // - key: 0xabc0, parent path length: 1
217            // - key: 0xabc1, parent path length: 0
218            // - key: 0xabc2, parent path length: 3 <-- current
219            // - key: 0xabc3, parent path length: 2
220            //
221            // When the branch node at 0xabc is visited it will be after the targets has iterated
222            // forward to 0xabc2 (because all children will have been visited already). At this
223            // point the target for 0xabc2 will not match the branch due to its prefix, but any of
224            // the other targets would, so we need to check those as well.
225            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 the path isn't in the current range then iterate forward until it is (or until
242            // there is no upper bound, indicating unbounded).
243            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    /// Takes a child which has been removed from the `child_stack` and converts it to an
255    /// [`RlpNode`], retaining it as a proof node.
256    ///
257    /// Calling this method indicates that the child will not undergo any further modifications.
258    ///
259    /// The caller has already determined via [`Self::should_retain`] that this child is retained.
260    /// That decision must not be re-evaluated here, because `should_retain` advances the `targets`
261    /// cursor. Children which are not retained are converted later, in [`Self::pop_branch`].
262    fn commit_child(
263        &mut self,
264        child_path: Nibbles,
265        child: ProofTrieBranchChild<VE::DeferredEncoder>,
266    ) -> Result<RlpNode, StateProofError> {
267        // An already encoded child only needs an extension if it has been rebased upward.
268        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        // Convert to `ProofTrieNode`, which will be what is retained.
276        //
277        // If this node is a branch then its `rlp_nodes_buf` will be taken and not returned to the
278        // `rlp_nodes_bufs` free-list.
279        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        // Use the `ProofTrieNode` to encode the `RlpNode`, and then push it onto retained nodes
284        // before returning.
285        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    /// Returns the path of the child of the currently under-construction branch at the given
294    /// nibble.
295    #[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    /// Returns index of the highest nibble which is set in the mask.
304    ///
305    /// # Panics
306    ///
307    /// Will panic in debug mode if the mask is empty.
308    #[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    /// Returns the path of the child on top of the `child_stack`, or the root path if the stack is
315    /// empty. Returns None if the current branch has not yet pushed a child (empty `state_mask`).
316    fn last_child_path(&self) -> Option<Nibbles> {
317        // If there is no branch under construction then the top child must be the root child.
318        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    /// If the last child of `child_stack` is retained for the proof, calls [`Self::commit_child`]
327    /// to replace it with a [`ProofTrieBranchChild::RlpNode`]. Otherwise, leaves it unencoded until
328    /// [`Self::pop_branch`].
329    ///
330    /// If `child_stack` is empty then this is a no-op.
331    ///
332    /// NOTE that this method call relies on the `state_mask` of the top branch of the
333    /// `branch_stack` to determine the last child's path. When committing the last child prior to
334    /// pushing a new child, it's important to set the new child's `state_mask` bit _after_ the call
335    /// to this method.
336    #[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        // Only commit immediately if retained for the proof. Otherwise, defer conversion
356        // to pop_branch() to give DeferredEncoder time for async work.
357        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    /// Adds a child at its full path, possibly collapsing an existing branch and/or creating a new
376    /// one depending on the path.
377    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            // Get the `state_mask` of the branch currently being built. If there are no branches
395            // on the stack then the trie is either empty or contains only a single child.
396            let (nibble, short_key) = match self.branch_stack.last().map(|branch| branch.state_mask)
397            {
398                None if self.child_stack.is_empty() => {
399                    // The first child is the root and already has the correct short key.
400                    self.child_stack.push(child);
401                    return Ok(())
402                }
403                None => {
404                    // Split the existing root child from the new child by their common prefix.
405                    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                    // Find the number of nibbles shared by the current branch and the new child.
416                    let common_prefix_len = self.branch_path.common_prefix_length(&path);
417
418                    // A branch which is not a prefix of the child cannot receive any more
419                    // children, so finish it and try again with its parent.
420                    if common_prefix_len < self.branch_path.len() {
421                        self.pop_branch(targets)?;
422                        continue
423                    }
424
425                    // If this nibble is already occupied, split the existing child from the new
426                    // child. Otherwise the new child can be inserted directly into this branch.
427                    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            // Store the child key relative to its new parent branch.
437            child.trim_short_key_prefix(path.len() - short_key.len());
438
439            // The preceding child is structurally final. Commit it if retained for the proof;
440            // otherwise its encoding can wait until pop_branch.
441            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            // Set the new child's bit after commit_last_child, which uses the mask to find the
447            // preceding child's path.
448            branch.state_mask.set_bit(nibble);
449
450            // The parent now contains this child at `nibble`.
451            self.child_stack.push(child);
452            return Ok(())
453        }
454    }
455
456    /// Pushes a new branch onto the `branch_stack` based on the path and short key of the last
457    /// child on the `child_stack` and the path of the next child which will be pushed on to the
458    /// stack after this call.
459    ///
460    /// Returns the nibble of the branch's `state_mask` which should be set for the new child, and
461    /// the short key that child should use.
462    fn push_new_branch(&mut self, new_child_path: Nibbles) -> (u8, Nibbles) {
463        // Get the full path to the root of the existing child. The trie root is used when there is
464        // no parent branch.
465        let first_child_path = self
466            .last_child_path()
467            .expect("push_new_branch requires the current branch to have a child");
468
469        // Put both children in the same coordinate system by trimming the existing child's root
470        // path from the new child's full path.
471        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        // Their shared prefix becomes the new branch's extension. The first differing nibble from
480        // each key becomes that child's position in the branch.
481        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        // Remove the extension and branch nibble from the new child's remaining short key.
486        let new_child_short_key = trim_nibbles_prefix(&new_child_short_key, common_prefix_len + 1);
487
488        // The new branch starts after the existing child's parent path and their shared extension.
489        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        // Rebase the existing child beneath the new branch by removing the extension and its
493        // branch nibble from the front of its short key.
494        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        // Push the new branch onto the `branch_stack`. We do not yet set the `state_mask` bit of
501        // the new child; whatever actually pushes the child onto the `child_stack` is expected to
502        // do that.
503        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    /// Pops the top branch off of the `branch_stack`, hashes its children on the `child_stack`, and
521    /// replaces those children on the `child_stack`. The `branch_path` field will be updated
522    /// accordingly.
523    ///
524    /// # Panics
525    ///
526    /// This method panics if `branch_stack` is empty.
527    #[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        // Retain the final child if needed before draining the branch's children. Unretained
541        // children are encoded below.
542        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        // Take the branch's children off the stack, using the state mask to determine how many
549        // there are.
550        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        // Collect children into RlpNode Vec. Children are in lexicographic order.
561        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        // Calculate the short key of the parent extension (if the branch has a parent extension).
585        // It's important to calculate this short key prior to modifying the `branch_path`.
586        let short_key = trim_nibbles_prefix(
587            &self.branch_path,
588            self.branch_path.len() - branch.ext_len as usize,
589        );
590
591        // Update the branch_path. If this branch is the only branch then only its extension needs
592        // to be trimmed, otherwise we also need to remove its nibble from its parent.
593        let new_path_len =
594            self.branch_path.len() - branch.ext_len as usize - self.maybe_parent_nibble();
595
596        // Keep the branch and its pending parent extension key on the child stack.
597        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    /// Given the lower and upper bounds (exclusive) of a range of keys, iterates over the
612    /// `hashed_cursor` and calculates all trie nodes possible based on those keys. If the upper
613    /// bound is None then it is considered unbounded.
614    ///
615    /// It is expected that this method is "driven" by `next_uncached_key_range`, which decides
616    /// which ranges of keys need to be calculated based on what cached trie data is available.
617    #[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        // A helper closure for mapping entries returned from the `hashed_cursor`, converting the
632        // key to Nibbles and immediately creating the DeferredValueEncoder so that encoding of the
633        // leaf value can begin ASAP.
634        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 the cursor hasn't been used, or the last iterated key is prior to this range's key
642        // range, then seek forward to at least the first key.
643        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        // Loop over all keys in the range, pushing each leaf onto the stack.
658        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    /// Takes a cached branch from the trie cursor and invalidates its hashes if it may collapse.
675    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 every dirty child is deleted, a lone unchanged child must be revealed so the
696            // branch can collapse into it. Keep the masks as structural hints, but prevent any of
697            // this branch's cached hashes from hiding that child.
698            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    /// Attempts to pop off the top branch of the `cached_branch_stack`, returning
713    /// [`PopCachedBranchOutcome::Popped`] on success. Returns other variants to indicate that the
714    /// stack is empty and what to do about it.
715    ///
716    /// This method only returns [`PopCachedBranchOutcome::CalculateLeaves`] if there is a cached
717    /// branch on top of the stack.
718    #[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        // If the `uncalculated_lower_bound` is None it indicates that there can be no more
726        // leaf data, so similarly there can be no more cached branch data.
727        let Some(uncalculated_lower_bound) = uncalculated_lower_bound else {
728            return Ok(PopCachedBranchOutcome::Exhausted)
729        };
730
731        // Use the branch on top of the stack unless a previously calculated range has already
732        // covered its entire subtrie.
733        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        // There is no cached branch on the stack. It's possible that another one exists
746        // farther on in the trie, but we perform some checks first to prevent unnecessary
747        // attempts to find it.
748
749        // If [`TrieCursorState::path`] returns None it means that the cursor has been
750        // exhausted, so there can be no more cached data.
751        let Some(mut trie_cursor_path) = trie_cursor_state.path() else {
752            return Ok(PopCachedBranchOutcome::Exhausted)
753        };
754
755        // If the trie cursor is seeked to a branch whose leaves have already been processed
756        // then we can't use it, instead we seek forward and try again.
757        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            // Having just seeked forward we need to check if the cursor is now exhausted,
764            // extracting the new path at the same time.
765            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 the trie cursor has reached the end of the traversal range then we consider cached
773        // data to be exhausted. The cursor itself remains positioned for reuse by a later range.
774        if traversal_upper_bound.is_some_and(|upper_bound| trie_cursor_path >= upper_bound) {
775            return Ok(PopCachedBranchOutcome::Exhausted)
776        }
777
778        // At this point we can be sure that the cursor is in an `Available` state. We know for
779        // sure it's not `Exhausted` because of the calls to `path` above, and we know it's not
780        // `Taken` because we push all taken branches onto the `cached_branch_stack`, and the
781        // stack is empty.
782        //
783        // We will use this `Available` cached branch as our next branch.
784        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        // If the calculated range is not caught up to the next cached branch it means there
788        // are portions of the trie prior to that branch which may need to be calculated;
789        // return the uncalculated range up to that branch to make that happen.
790        //
791        // If the next cached branch's path is all zeros then we can skip this catch-up step,
792        // because there cannot be any keys prior to that range.
793        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            // Push the cached branch onto the stack so it's available once the leaf range is done
799            // being calculated.
800            self.cached_branch_stack.push(cached);
801
802            return Ok(PopCachedBranchOutcome::CalculateLeaves(range));
803        }
804
805        Ok(PopCachedBranchOutcome::Popped(cached))
806    }
807
808    /// Pop any under-construction branches that are now complete. Assumes that all trie data prior
809    /// to `next_path`, if any, has been computed. Any branches which were under-construction
810    /// previously, and which do not share a prefix with `next_path`, can be assumed to be
811    /// completed; they will not have any further keys added to them.
812    ///
813    /// Returns a range to calculate if a branch still has dirty keys to process, or popping it
814    /// exposes dirty keys which could split its extension. A missing lower bound disables these
815    /// checks when the caller has already scheduled the remaining range.
816    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 the lower bound is still within this branch, process any remaining dirty keys
842            // before popping it so they can be added directly to the branch.
843            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            // Once popped, this branch becomes a child at this path. Its upper bound therefore
852            // covers any keys which could split the branch's extension on the right.
853            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        // Bound only this post-pop scan at the cached path so traversal can reuse its descendants.
863        // The pre-pop check must finish dirty keys inside the branch before it is encoded.
864        //
865        // An empty branch_stack is skipped because a popped local root does not need this check:
866        // any gap before `next_path` was already returned by `try_pop_cached_branch`, and forward
867        // traversal will split its extension and process later dirty keys as needed.
868        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    // Returns the next child nibble on the current branch to process, or None if there are no
882    // further nibbles to process.
883    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        // Also include child nibbles indicated by the prefix set. The prefix set can
892        // indicate children that need recalculation from leaves (e.g. new keys inserted
893        // under this branch).
894        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        // Mask out any child nibbles whose ranges have already been fully processed.
909        // This can happen when `calculate_key_range` finds no keys for a child's range,
910        // leaving the child's bit unset in `state_mask`. Without this, re-entering this
911        // function would select the same child again.
912        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            // Clear all nibbles strictly below `lower_nibble`. If the lower bound is within the
917            // current child, the remainder of that child may still need to be processed.
918            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            // The lower bound has moved entirely past this branch (e.g. branch is 0x6 but
932            // lower is 0x7). All remaining children have been processed.
933            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    /// Accepts the current state of both hashed and trie cursors, and determines the next range of
947    /// hashed keys which need to be processed using [`Self::calculate_key_range`].
948    ///
949    /// This method will use cached branch node data from the trie cursor to skip over all possible
950    /// ranges of keys, to reduce computation as much as possible.
951    ///
952    /// # Returns
953    ///
954    /// - `None`: No more data to process, finish computation
955    ///
956    /// - `Some(lower, None)`: Indicates to process all keys starting at `lower`, with no upper
957    ///   bound. This method won't be called again after this.
958    ///
959    /// - `Some(lower, Some(upper))`: Indicates to process all keys starting at `lower`, up to but
960    ///   excluding `upper`, and then call this method once done.
961    ///
962    /// Once returned the `branch_stack` will be in the correct state to start calculating leaves
963    /// for the given range, if any.
964    #[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            // Pop the currently cached branch node.
981            //
982            // NOTE we pop off the `cached_branch_stack` because cloning the `BranchNodeCompact`
983            // means cloning an Arc, which incurs synchronization overhead. We have to be sure to
984            // push the cached branch back onto the stack once done.
985            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                    // If cached branches are exhausted it's possible that there is still an
993                    // unbounded range of leaves to be processed. `uncalculated_lower_bound` is
994                    // used to return that range.
995                    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            // Since we've popped all constructed branches which don't contain `cached_path`, the
1030            // remaining branch path must be its prefix.
1031            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            // Dirty keys before this cached path may split the extension leading to it. Process
1038            // them before using the cached branch as a hint.
1039            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                // no need to pop from `cached_branch_stack`, the current cached branch is already
1062                // popped (see note at the top of the loop).
1063
1064                // The completed branch has no more keys with its prefix. Set the lower bound which
1065                // can be returned from this method to be the next possible prefix, if any.
1066                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 the `hash_mask` bit is set for the next child it means the child's hash is cached
1076            // in the `cached_branch`. We can use that instead of re-calculating the hash of the
1077            // entire sub-trie.
1078            //
1079            // If the child needs to be retained for a proof then we should not use the cached
1080            // hash, and instead continue on to calculate its node manually.
1081            //
1082            // If the child's path is in the prefix set then the cached hash is stale and must
1083            // not be used.
1084            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                // Pull this child's hash out of the cached branch node. The hash index is the
1089                // number of hash_mask bits set below this child's nibble.
1090                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                // `take_cached_branch` replaces hashes with zero when their nodes must be
1095                // revealed to support a possible branch collapse.
1096                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                        // Keep this hint available while inserting the child so a branch which is
1108                        // naturally materialized at `cached_path` can inherit its masks.
1109                        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                        // Update the `uncalculated_lower_bound` to indicate that the child whose
1128                        // bit was just set is completely processed.
1129                        uncalculated_lower_bound = child_path.next_without_prefix();
1130
1131                        continue
1132                    }
1133                }
1134            }
1135
1136            // We now want to check if there is a cached branch node at this child. The cached
1137            // branch node may be the node at this child directly, or this child may be an
1138            // extension and the cached branch is the child of that extension.
1139
1140            // All trie nodes prior to `child_lower_bound` have been processed, so seek the trie
1141            // cursor forward if necessary.
1142            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 the next cached branch node is a child of `child_path` then we can assume it is
1151            // the cached branch for this child. We push it onto the `cached_branch_stack` and loop
1152            // back to the top.
1153            if let TrieCursorState::Available(next_cached_path, next_cached_branch) =
1154                &trie_cursor_state &&
1155                next_cached_path.starts_with(&child_path)
1156            {
1157                // Push the current cached branch back on before pushing its child and then looping
1158                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            // There is no cached data for the sub-trie at this child, we must recalculate the
1173            // sub-trie root (this child) using the leaves. Return the range of keys based on the
1174            // child path.
1175            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            // Push the current cached branch back onto the stack before returning.
1184            self.cached_branch_stack.push((cached_path, cached_branch));
1185
1186            return Ok(Some((child_lower_bound, child_upper_bound)));
1187        }
1188    }
1189
1190    /// Calculates trie nodes and retains proofs for targeted nodes within a sub-trie. The
1191    /// sub-trie's bounds are denoted by the `lower_bound` and `upper_bound` arguments,
1192    /// `upper_bound` is exclusive, None indicates unbounded.
1193    #[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        // Wrap targets into a `TargetsCursor`.  targets can be empty if we only want to calculate
1214        // the root, in which case we don't need a cursor.
1215        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        // Ensure initial state is cleared. By the end of the method call these should be empty once
1222        // again.
1223        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        // `next_uncached_key_range`, which will be called in the loop below, expects the trie
1229        // cursor to have already been positioned. Cursor resets for overlapping sub-tries are
1230        // handled by `proof_inner`, so a buffered entry at-or-after this disjoint range remains the
1231        // first unconsumed entry. Exhaustion is similarly stable across forward-only ranges.
1232        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        // `uncalculated_lower_bound` tracks the lower bound of node paths which have yet to be
1241        // visited, either via the hashed key cursor (`calculate_key_range`) or trie cursor
1242        // (`next_uncached_key_range`). If/when this becomes None then there are no further nodes
1243        // which could exist.
1244        let mut uncalculated_lower_bound = Some(traversal_lower_bound);
1245
1246        trace!(target: TRACE_TARGET, "Starting loop");
1247        loop {
1248            // Save the previous lower bound to detect forward progress.
1249            let prev_uncalculated_lower_bound = uncalculated_lower_bound;
1250
1251            // Determine the range of keys of the overall trie which need to be re-computed.
1252            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                // If `next_uncached_key_range` determines that there can be no more keys then
1260                // complete the computation.
1261                break;
1262            };
1263
1264            // Forward-progress guard: detect trie inconsistencies that would cause infinite loops.
1265            // If `next_uncached_key_range` returns a range that starts before the previous
1266            // lower bound, we've gone backwards and would loop forever.
1267            //
1268            // This can specifically happen when there is a cached branch which shouldn't exist, or
1269            // if state mask bit is set on a cached branch which shouldn't be.
1270            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            // Calculate the trie for that range of keys
1284            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            // Once outside `calculate_key_range`, `hashed_cursor_state` will be at the first key
1293            // after the range, or exhausted.
1294            //
1295            // If the hashed cursor is exhausted, or has reached the end of the traversal range,
1296            // then there are no more keys which can contribute to these target children.
1297            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            // The upper bound of previous calculation becomes the lower bound of the uncalculated
1304            // range, for which we'll once again check for cached data.
1305            uncalculated_lower_bound = calc_upper_bound;
1306        }
1307
1308        // Once there's no more leaves we can pop the remaining branches, if any.
1309        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        // At this point the branch stack should be empty. If the child stack is empty it means no
1315        // keys were ever iterated from the hashed cursor in the first place. Otherwise there should
1316        // only be a single node left: the root node.
1317        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        // The `cached_branch_stack` may still have cached branches on it, as it's not affected by
1322        // `pop_branch`, but it is no longer needed and should be cleared.
1323        self.cached_branch_stack.clear();
1324
1325        // We always pop the local root node off of the `child_stack` in order to empty it. If the
1326        // parent branch is already known, compressed roots need to be rebased into a direct child
1327        // of that parent before they can be attached to it.
1328        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        // A full-trie calculation always retains a root, using an empty root when traversal
1337        // produced no root node.
1338        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            // Direct root branches do not have an entry in the branch node table. A root extension
1347            // has a separate child branch carrying its own masks.
1348            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        // If there's no root node then the subtrie has no keys, return nothing.
1358        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        // A partial calculation traverses only one child of the known parent.
1364        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        // Keep the parent branch's child nibble in the proof path so the local root attaches
1372        // directly below that parent.
1373        let child_path_len = child_path.len();
1374
1375        // Retain the requested child with only the path below its parent edge in the short key.
1376        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    /// Clears internal computation state. Called after errors to ensure the calculator is not
1387    /// left in a partially-computed state when reused.
1388    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    /// Internal implementation of proof calculation. Assumes both cursors have already been reset.
1397    /// See docs on [`Self::proof`] for expected behavior.
1398    fn proof_inner(
1399        &mut self,
1400        value_encoder: &mut VE,
1401        targets: &mut [ProofV2Target],
1402    ) -> Result<Vec<ProofTrieNode>, StateProofError> {
1403        // If there are no targets then nothing could be returned, return early.
1404        if targets.is_empty() {
1405            trace!(target: TRACE_TARGET, "Empty targets, returning");
1406            return Ok(Vec::new())
1407        }
1408
1409        // Initialize the variables which track the state of the two cursors. Both indicate the
1410        // cursors are unseeked.
1411        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        // Divide targets into bounded ranges, each corresponding to one direct child of an
1416        // already-revealed parent, and handle all proofs within that range.
1417        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    /// Generate a proof for the given targets.
1471    ///
1472    /// Given a set of [`ProofV2Target`]s, returns nodes on the requested paths, including the child
1473    /// branch of every retained extension so its persistence masks remain available even for an
1474    /// absence target that diverges within the extension key. Nodes are sorted in depth-first
1475    /// post-order (children before parents).
1476    ///
1477    /// Targets may be supplied in any order. Calculation sorts the slice in place by known parent
1478    /// context, then by key within each group.
1479    #[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    /// Computes the root hash from a set of proof nodes.
1491    ///
1492    /// Returns `None` if there is no root node (partial proof), otherwise returns the hash of the
1493    /// root node.
1494    ///
1495    /// This method reuses the internal RLP encode buffer for efficiency.
1496    pub fn compute_root_hash(
1497        &mut self,
1498        proof_nodes: &[ProofTrieNode],
1499    ) -> Result<Option<B256>, StateProofError> {
1500        // Find the root node (node at empty path)
1501        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        // Compute the hash of the root node
1508        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    /// Calculates the root node of the trie.
1516    ///
1517    /// This method does not accept targets or retain descendant proofs. Returns the standard root
1518    /// node, which can be used to compute the root hash via [`Self::compute_root_hash`]. For a root
1519    /// extension, use [`Self::root_nodes`] to also obtain its separate child branch.
1520    #[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    /// Calculates the root and, for an extension root, its separate child branch.
1528    ///
1529    /// Nodes are returned children before parents; the root is always last, even for an empty trie.
1530    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        // Initialize the variables which track the state of the two cursors. Both indicate the
1538        // cursors are unseeked.
1539        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
1564/// A proof calculator for storage tries.
1565pub 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    /// Create a new [`StorageProofCalculator`] instance.
1573    pub fn new_storage(trie_cursor: TC, hashed_cursor: HC) -> Self {
1574        Self::new(trie_cursor, hashed_cursor)
1575    }
1576
1577    /// Generate a proof for a storage trie at the given hashed address.
1578    ///
1579    /// Given a set of [`ProofV2Target`]s, returns nodes on the requested paths, including the child
1580    /// branch of every retained extension so its persistence masks remain available even for an
1581    /// absence target that diverges within the extension key. Nodes are sorted in depth-first
1582    /// post-order (children before parents).
1583    ///
1584    /// Targets may be supplied in any order. Calculation sorts the slice in place by known parent
1585    /// context, then by key within each group.
1586    #[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        // Shortcut: check if storage is empty
1595        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        // Don't call `set_hashed_address` on the trie cursor until after the previous shortcut has
1608        // been checked.
1609        self.trie_cursor.set_hashed_address(hashed_address);
1610
1611        // Create a mutable storage value encoder
1612        let mut storage_value_encoder = StorageValueEncoder;
1613        self.proof_inner(&mut storage_value_encoder, targets)
1614    }
1615
1616    /// Calculates the root node of a storage trie.
1617    ///
1618    /// This method does not accept targets or retain descendant proofs. Returns the standard root
1619    /// node, which can be used to compute the root hash via [`Self::compute_root_hash`]. For a root
1620    /// extension, use [`Self::storage_root_nodes`] to also obtain its separate child branch.
1621    #[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    /// Calculates storage root nodes in children-before-parents order.
1634    ///
1635    /// Includes the separate child branch of an extension root, even without proof targets.
1636    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        // Don't call `set_hashed_address` on the trie cursor until after the previous shortcut has
1647        // been checked.
1648        self.trie_cursor.set_hashed_address(hashed_address);
1649
1650        // Create a mutable storage value encoder
1651        let mut storage_value_encoder = StorageValueEncoder;
1652        self.root_nodes(&mut storage_value_encoder)
1653    }
1654
1655    /// Calculates the storage root hash of the account at `hashed_address`.
1656    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/// Helper type wrapping a slice of [`ProofV2Target`]s, primarily used to iterate through targets in
1665/// [`ProofCalculator::should_retain`].
1666///
1667/// It is assumed that the underlying slice is never empty, and that the iterator is never
1668/// exhausted.
1669#[derive(Clone)]
1670struct TargetsCursor<'a> {
1671    targets: &'a [ProofV2Target],
1672    i: usize,
1673}
1674
1675impl<'a> TargetsCursor<'a> {
1676    /// Wraps a slice of [`ProofV2Target`]s with the `TargetsCursor`.
1677    ///
1678    /// # Panics
1679    ///
1680    /// Will panic in debug mode if called with an empty slice.
1681    fn new(targets: &'a [ProofV2Target]) -> Self {
1682        debug_assert!(!targets.is_empty());
1683        Self { targets, i: 0 }
1684    }
1685
1686    /// Returns the current and next [`ProofV2Target`] that the cursor is pointed at.
1687    fn current(&self) -> (&'a ProofV2Target, Option<&'a ProofV2Target>) {
1688        (&self.targets[self.i], self.targets.get(self.i + 1))
1689    }
1690
1691    /// Iterates the cursor forward.
1692    ///
1693    /// # Panics
1694    ///
1695    /// Will panic if the cursor is exhausted.
1696    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    // Iterate forwards over the slice, starting from the [`ProofV2Target`] after the current.
1703    fn skip_iter(&self) -> impl Iterator<Item = &'a ProofV2Target> {
1704        self.targets[self.i + 1..].iter()
1705    }
1706
1707    /// Iterated backwards over the slice, starting from the [`ProofV2Target`] previous to the
1708    /// current.
1709    fn rev_iter(&self) -> impl Iterator<Item = &'a ProofV2Target> {
1710        self.targets[..self.i].iter().rev()
1711    }
1712}
1713
1714/// Used to track the state of the trie cursor, allowing us to differentiate between a branch having
1715/// been taken (used as a cached branch) and the cursor having been exhausted.
1716#[derive(Debug)]
1717enum TrieCursorState {
1718    /// The initial state of the cursor, indicating it's never been seeked.
1719    Unseeked,
1720    /// Cursor is seeked to this path and the node has not been used yet.
1721    Available(Nibbles, BranchNodeCompact),
1722    /// Cursor is seeked to this path, but the node has been used.
1723    Taken(Nibbles),
1724    /// Cursor has been exhausted after seeking from the given lower bound.
1725    Exhausted(Nibbles),
1726}
1727
1728impl TrieCursorState {
1729    /// Creates a [`Self::Unseeked`] based on an entry returned from the cursor itself.
1730    const fn unseeked() -> Self {
1731        Self::Unseeked
1732    }
1733
1734    /// Creates a [`Self`] based on an entry returned from the cursor itself.
1735    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    /// Returns the path the cursor is seeked to, or None if it's exhausted.
1740    ///
1741    /// # Panics
1742    ///
1743    /// Panics if the cursor is unseeked.
1744    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    /// Returns true if the cursor must seek to be usable for a range starting at `path`.
1753    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    /// Returns true if seeking to `key` requires resetting the forward-only cursor.
1762    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    /// Takes the path and node from a [`Self::Available`]. Panics if not [`Self::Available`].
1771    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
1785/// Used to track the state of the hashed cursor, including the path that established exhaustion.
1786enum HashedCursorState<V> {
1787    /// The initial state of the cursor, indicating it's never been seeked.
1788    Unseeked,
1789    /// Cursor is seeked to this path and the value has not been used yet.
1790    Available(Nibbles, V),
1791    /// Cursor has been exhausted at or after the given path.
1792    Exhausted(Nibbles),
1793}
1794
1795impl<V> HashedCursorState<V> {
1796    /// Creates a [`Self::Unseeked`] state.
1797    const fn unseeked() -> Self {
1798        Self::Unseeked
1799    }
1800
1801    /// Creates a [`Self`] based on an entry returned from the cursor itself.
1802    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    /// Returns the path the cursor is seeked to, or None if it's unseeked or exhausted.
1807    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    /// Returns true if the cursor must seek to be usable for a range starting at `key`.
1815    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    /// Returns true if seeking to `key` requires resetting the forward-only cursor.
1824    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    /// Takes the path and value from a [`Self::Available`]. Panics if not [`Self::Available`].
1833    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
1841/// Describes the state of the currently cached branch node (if any).
1842enum PopCachedBranchOutcome {
1843    /// Cached branch has been popped from the `cached_branch_stack` and is ready to be used.
1844    Popped((Nibbles, BranchNodeCompact)),
1845    /// All cached branches have been exhausted.
1846    Exhausted,
1847    /// Need to calculate leaves from this range (exclusive upper) before the cached branch
1848    /// (catch-up range). If None then
1849    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    /// Projects a legacy proof node into the representation requested by a V2 target.
1879    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                // The branch itself is projected separately when the extension is fully trimmed.
1913                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    /// Builds the exact V2 representation expected for a legacy proof and set of targets.
1924    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        // A retained extension also reveals its child branch and persistence masks, even when
1935        // the target diverges within the extension key.
1936        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    /// A test harness for comparing `StorageProofCalculator` and legacy `StorageProof`
1957    /// implementations.
1958    ///
1959    /// Wraps [`TrieTestHarness`] and adds a method to test that both proof implementations
1960    /// produce equivalent results for storage proofs.
1961    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        /// Creates a new test harness from a map of hashed storage slots to values.
1974        fn new(storage: BTreeMap<B256, U256>) -> Self {
1975            Self { inner: TrieTestHarness::new(storage) }
1976        }
1977
1978        /// Computes the storage root while treating the supplied prefixes as dirty.
1979        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        /// Asserts that `StorageProofCalculator` and legacy `StorageProof` produce equivalent
1993        /// results for storage proofs.
1994        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            // Get v2 proof and root hash via harness
2001            let (proof_v2_result, root_hash) = self.proof_v2(&mut targets_vec);
2002
2003            // Verify the root hash matches the expected root (if the proof contains a root
2004            // node)
2005            if let Some(root_hash) = root_hash {
2006                pretty_assertions::assert_eq!(self.original_root(), root_hash);
2007            }
2008
2009            // Fully materialize the legacy proof so compressed branches can be projected across
2010            // arbitrary parent boundaries, including absence targets that diverge inside them.
2011            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            // Call legacy StorageProof::storage_multiproof
2018            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            // Decode and sort legacy proof nodes
2028            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    /// Tests that `clear_computation_state` properly resets internal stacks, allowing a
2055    /// `StorageProofCalculator` to be reused after a mid-computation error left stale state.
2056    /// Before the fix, stale data in `branch_stack`, `child_stack`, and `branch_path`
2057    /// could cause a `usize` underflow panic in `pop_branch`.
2058    #[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        // Simulate stale state left by a mid-computation error: push fake entries onto internal
2082        // stacks and set a non-empty branch_path.
2083        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        // clear_computation_state should reset everything so a subsequent call works.
2098        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        // Compare against a fresh calculator to verify correctness.
2108        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        /// Generate a strategy for storage datasets (hashed slot → value).
2185        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        /// Generate a strategy for proof targets that are 80% from existing storage slots
2196        /// and 20% random keys. Each target has a random parent path length of `None` or 0..15.
2197        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            // Vary both nibbles of each byte to cover adjacent branches and extensions.
2233            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            /// Tests that `StorageProofCalculator` produces valid proofs for randomly generated
2242            /// storage datasets with proof targets.
2243            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        // The known parent at `e` is supplied by the sparse trie and may be stale in the database
2503        // when partial persistence masks that path. In particular, its state mask can omit the
2504        // live `eb` child while hashed state already contains that child's leaf.
2505        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        // Generate random storage dataset.
2565        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        // Collect targets; partially from real keys, partially random keys which probably won't
2572        // exist.
2573        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        // Create test harness
2580        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        // All storage keys share a common first nibble (0x6), so the branch is at path 0x6. The
2594        // second nibble differentiates children: 0,1,3,5,7.
2595        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        // Construct a branch node at path 0x6 with state_mask bits 0,1,3,5,7.
2601        // hash_mask has bits 0,1,5,7 (NOT 3) — nibble 3's hash is cleared because it's in the
2602        // prefix set. Hashes are dummy values.
2603        let state_mask = TrieMask::new(0b10101011); // bits 0,1,3,5,7
2604        let hash_mask = TrieMask::new(0b10100011); // bits 0,1,5,7 (NOT 3)
2605        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        // Hashed cursor has slots at children 0, 1, 5, 7 — but NOT child 3 (0x63).
2612        // This simulates the post-state overlay having deleted the slot at 0x63.
2613        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    /// Tests that `root_node` handles the case where `uncalculated_lower_bound` has advanced
2635    /// entirely past a cached branch that still has unprocessed children in its `state_mask`.
2636    ///
2637    /// Branch at `0x6` has `state_mask` bits 0,1,5,f where nibble 5 has its `hash_mask`
2638    /// cleared and no leaf data. The last child (nibble f)
2639    /// causes `calculate_key_range` to be called with range `(0x6f, Some(0x7))`. After that range,
2640    /// the hashed cursor still has keys (at `0x70...`), so `proof_subtrie` does not break and
2641    /// re-enters `next_uncached_key_range` with `uncalculated_lower_bound = Some(0x7)`.
2642    /// Since `0x7` is past `0x6`, all remaining children are skipped and the branch is popped.
2643    #[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        // Leaf keys under 0x6 and one beyond (0x70) to keep the cursor alive after 0x6.
2650        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        // Branch at 0x6: state_mask bits 0,1,5,f; hash_mask bits 0,1 (NOT 5, NOT f).
2656        // Nibble 5 has state_mask set but no hash and no leaf data (masked empty child).
2657        // Nibble f has state_mask set, no hash, but DOES have leaf data.
2658        let state_mask = TrieMask::new(0b1000_0000_0010_0011); // bits 0,1,5,f
2659        let hash_mask = TrieMask::new(0b0000_0000_0000_0011); // bits 0,1
2660        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        // Hashed cursor: slots at 0x60, 0x61, 0x6f, 0x70 — but NOT 0x65.
2667        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    /// Tests that the prefix set causes `next_uncached_key_range` to add child nibbles that are
2689    /// not present in the cached branch's `state_mask`.
2690    ///
2691    /// Setup: An original state with leaves at `0x60` and `0x61` produces a cached branch at
2692    /// `0x6` with children at nibbles 0 and 1 (both with real cached hashes from `StorageRoot`).
2693    /// A new leaf is then inserted at `0x63...`, which is NOT in the branch's `state_mask`.
2694    /// The prefix set contains the new key. Without prefix set support, the calculator would
2695    /// skip nibble 3 entirely and produce a stale root hash. With prefix set support, nibble 3
2696    /// is discovered and its subtrie is recalculated from leaves.
2697    #[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    /// Tests that `next_uncached_key_range` does not use a cached hash when the child's path
2741    /// is in the prefix set, forcing recalculation from leaves.
2742    ///
2743    /// Setup: A cached branch at `0x6` with children at nibbles 0,1,5 — all with cached hashes.
2744    /// The leaf at `0x65...` is changed (different value). The prefix set marks `0x65...` as
2745    /// dirty. Without prefix set support, the calculator would use the stale cached hash for
2746    /// nibble 5 and produce a wrong root. With prefix set support, the cached hash is skipped
2747    /// and the subtrie is recalculated from the updated leaf data.
2748    #[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        // The dirty children straddle a clean cached descendant under branch 0x02. Traversal
2849        // must resume at the trailing dirty sibling after using the cached descendant.
2850        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        // Returning from 0x040 to cached parent 0x04 must not scan all leaves up to 0x05.
2889        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        // Returning to cached ancestor 0x1 must finish dirty sibling 0x122 before encoding 0x12.
2929        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    /// Helper to compute the keccak256 hash of a storage leaf node. The `short_key` is the
2934    /// leaf's key after trimming all branch/extension nibbles consumed by ancestor nodes.
2935    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    /// Checks collapsing a cached branch after removing one of its two direct branch children.
2943    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        // Build the cached trie through the production HashBuilder path. Each child at
2957        // `remaining_nibble` and `removed_nibble` is a direct branch with two leaf children.
2958        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        // The prefix set marks the entire removed child subtree dirty.
2985        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        // The cached branch at 0x80 remains parked while its children are rebuilt. Processing the
3064        // dirty child advances the lower bound to 0x9, past the cached branch's entire range.
3065        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        // Keys whose first bytes directly set the nibble paths we need.
3089        let key_a0 = B256::right_padding_from(&[0x6a, 0x30]); // nibbles: 6,a,3,0,...
3090        let key_a1 = B256::right_padding_from(&[0x6a, 0x31]); // nibbles: 6,a,3,1,...
3091        let key_c = B256::right_padding_from(&[0x6a, 0x80]); // nibbles: 6,a,8,0,...
3092        let key_d = B256::right_padding_from(&[0x6b, 0x00]); // nibbles: 6,b,0,0,...
3093        let key_e = B256::right_padding_from(&[0x6c, 0x00]); // nibbles: 6,c,0,0,...
3094
3095        // Build a correct trie from all five leaves to get the expected root and real hashes.
3096        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        // Compute leaf hashes for constructing manual cached branch nodes.
3104        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        // ── Construct cached branch at [6] ─────────────────────────────────────
3110        // state_mask: bits a, b, and c set.
3111        // hash_mask:  bits b and c — both have cached leaf hashes.  Bit a has no hash, so the
3112        //             calculator will seek the trie cursor to find a deeper cached branch.
3113        //
3114        // Children b and c remain clean and can still use their cached hashes.
3115        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        // ── Construct cached branch at [6,a,3] ────────────────────────────────
3126        // state_mask: bits 0 and 1 set (children key_a0 and key_a1).
3127        // hash_mask:  both bits set — both children have cached hashes.
3128        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        // Intentionally omit the branch at [6,a] — this is the inconsistency.
3138        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        // Create harness with all five leaves but the inconsistent trie nodes.
3146        let mut harness = TrieTestHarness::new(all_storage);
3147        harness.set_trie_nodes(inconsistent_nodes);
3148
3149        // Mark key_c as dirty — in the real scenario the leaf was touched by execution. The
3150        // nested branch [6,a,3] remains clean because key_c diverges at [6,a,8].
3151        let mut prefix_set = PrefixSetMut::default();
3152        prefix_set.insert(Nibbles::unpack(key_c));
3153
3154        // ── Verify root hash ───────────────────────────────────────────────────
3155        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        // With the bug, the calculator skips key_c and produces a wrong root.
3173        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        // ── Verify proof for key_c contains nodes on its path ──────────────────
3180        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        // Keys whose first bytes directly set the nibble paths we need.
3200        let key_a0 = B256::right_padding_from(&[0x6a, 0x80]); // nibbles: 6,a,8,0,...
3201        let key_a1 = B256::right_padding_from(&[0x6a, 0x81]); // nibbles: 6,a,8,1,...
3202        let key_c = B256::right_padding_from(&[0x6a, 0x30]); // nibbles: 6,a,3,0,... (BEFORE
3203                                                             // [6,a,8])
3204        let key_d = B256::right_padding_from(&[0x6b, 0x00]); // nibbles: 6,b,0,0,...
3205        let key_e = B256::right_padding_from(&[0x6c, 0x00]); // nibbles: 6,c,0,0,...
3206
3207        // Build a correct trie from all five leaves to get the expected root and real hashes.
3208        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        // Compute leaf hashes for constructing manual cached branch nodes.
3216        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        // ── Construct cached branch at [6] ─────────────────────────────────────
3222        // state_mask: bits a, b, and c set.
3223        // hash_mask:  bits b and c — both have cached leaf hashes.  Bit a has no hash, so the
3224        //             calculator will seek the trie cursor to find a deeper cached branch.
3225        //
3226        // Children b and c remain clean and can still use their cached hashes.
3227        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        // ── Construct cached branch at [6,a,8] ────────────────────────────────
3238        // state_mask: bits 0 and 1 set (children key_a0 and key_a1).
3239        // hash_mask:  both bits set — both children have cached hashes.
3240        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        // Intentionally omit the branch at [6,a] — this is the inconsistency.
3250        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        // Create harness with all five leaves but the inconsistent trie nodes.
3258        let mut harness = TrieTestHarness::new(all_storage);
3259        harness.set_trie_nodes(inconsistent_nodes);
3260
3261        // Mark key_c as dirty — it comes BEFORE the cached branch [6,a,8] in nibble order.
3262        let mut prefix_set = PrefixSetMut::default();
3263        prefix_set.insert(Nibbles::unpack(key_c));
3264
3265        // ── Verify root hash ───────────────────────────────────────────────────
3266        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        // With the bug, the calculator skips key_c and produces a wrong root.
3284        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        // ── Verify proof for key_c contains nodes on its path ──────────────────
3291        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        // We need cached branches at [2], [2,f], and [3] in the trie DB.
3312        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        // Verify that the expected branches exist in the trie.
3335        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        // Change only key_2 — triggers skip of parent branch [2] while child [2,f] is not
3341        // skipped.
3342        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        // Use different values to ensure distinct leaf hashes.
3403        let val_3 = U256::from(111u64);
3404        let val_5 = U256::from(222u64);
3405        let val_8 = U256::from(333u64);
3406
3407        // Keys under a common prefix `0x6_` to create a branch at path [6].
3408        // Use second byte to distinguish short keys (so they differ after position 2).
3409        let key_63 = B256::right_padding_from(&[0x63, 0xaa]); // nibble path: 6,3,a,a,...
3410        let key_65 = B256::right_padding_from(&[0x65, 0xbb]); // nibble path: 6,5,b,b,...
3411        let key_68 = B256::right_padding_from(&[0x68, 0xcc]); // nibble path: 6,8,c,c,...
3412
3413        // Compute leaf hashes. The branch at [6] consumes 2 nibbles (the branch path [6]
3414        // plus the child nibble), so each leaf's short key starts at position 2.
3415        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        // Build cached branch at [6] with state_mask and hash_mask bits for nibbles 3, 5, 8.
3420        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, // hash_mask = state_mask (all children have cached hashes)
3425            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        // Compute the expected root from a fresh trie with just key_65 and key_68.
3433        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        // Update the harness with a cached trie node which will reference key_63 by hash.
3438        harness.set_trie_nodes(storage_nodes);
3439
3440        // Mark key_63 as dirty in the prefix set — in the real scenario the leaf was
3441        // deleted and the HashedPostState overlay masks it out.
3442        let mut prefix_set = PrefixSetMut::default();
3443        prefix_set.insert(Nibbles::unpack(key_63));
3444
3445        // Request a proof for key_63 (absence proof — no leaf exists).
3446        // Because the prefix set marks nibble 3's child path as dirty, the cached hash for
3447        // nibble 3 is skipped.
3448        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        // With the bug, nibble 5 gets hashes[0] (nibble 3's hash) and nibble 8 gets
3473        // hashes[1] (nibble 5's hash), producing a wrong root.
3474        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}