Skip to main content

reth_trie/proof_v2/
mod.rs

1//! Proof calculation version 2: Leaf-only implementation.
2//!
3//! This module provides a rewritten proof calculator that:
4//! - Uses only leaf data (HashedAccounts/Storages) to generate proofs
5//! - Returns proof nodes sorted lexicographically by path
6//! - Automatically resets after each calculation
7//! - Re-uses cursors across calculations
8//! - Supports generic value types with lazy evaluation
9
10use crate::{
11    hashed_cursor::{HashedCursor, HashedStorageCursor},
12    trie_cursor::{depth_first, TrieCursor, TrieStorageCursor},
13};
14use alloy_primitives::{keccak256, B256, U256};
15use alloy_rlp::Encodable;
16use alloy_trie::{BranchNodeCompact, TrieMask};
17use reth_execution_errors::trie::StateProofError;
18use reth_trie_common::{
19    prefix_set::PrefixSet, BranchNodeMasks, BranchNodeRef, BranchNodeV2, Nibbles, ProofTrieNodeV2,
20    ProofV2Target, RlpNode, TrieNodeV2,
21};
22use std::cmp::Ordering;
23use tracing::{error, instrument, trace};
24
25mod value;
26pub use value::*;
27
28mod node;
29use node::*;
30
31mod target;
32pub(crate) use target::*;
33
34/// Target to use with the `tracing` crate.
35static TRACE_TARGET: &str = "trie::proof_v2";
36
37/// Number of bytes to pre-allocate for [`ProofCalculator`]'s `rlp_encode_buf` field.
38const RLP_ENCODE_BUF_SIZE: usize = 1024;
39
40/// A proof calculator that generates merkle proofs using only leaf data.
41///
42/// The calculator:
43/// - Accepts one or more B256 proof targets sorted lexicographically
44/// - Returns proof nodes sorted lexicographically by path
45/// - Automatically resets after each calculation
46/// - Re-uses cursors from one calculation to the next
47#[derive(Debug)]
48pub struct ProofCalculator<TC, HC, VE: LeafValueEncoder> {
49    /// Trie cursor for traversing stored branch nodes.
50    trie_cursor: TC,
51    /// Hashed cursor for iterating over leaf data.
52    hashed_cursor: HC,
53    /// Branches which are currently in the process of being constructed, each being a child of
54    /// the previous one.
55    branch_stack: Vec<ProofTrieBranch>,
56    /// The path of the last branch in `branch_stack`.
57    branch_path: Nibbles,
58    /// Children of branches in the `branch_stack`.
59    ///
60    /// Each branch in `branch_stack` tracks which children are in this stack using its
61    /// `state_mask`; the number of children the branch has in this stack is equal to the number of
62    /// bits set in its `state_mask`.
63    ///
64    /// The children for the bottom branch in `branch_stack` are found at the bottom of this stack,
65    /// and so on. When a branch is removed from `branch_stack` its children are removed from this
66    /// one, and the branch is pushed onto this stack in their place (see [`Self::pop_branch`].
67    ///
68    /// Children on the `child_stack` are converted to [`ProofTrieBranchChild::RlpNode`]s via the
69    /// [`Self::commit_child`] method. Committing a child indicates that no further changes are
70    /// expected to happen to it (e.g. splitting its short key when inserting a new branch). Given
71    /// that keys are consumed in lexicographical order, only the last child on the stack can
72    /// ever be modified, and therefore all children besides the last are expected to be
73    /// [`ProofTrieBranchChild::RlpNode`]s.
74    child_stack: Vec<ProofTrieBranchChild<VE::DeferredEncoder>>,
75    /// Cached branch data pulled from the `trie_cursor`. The calculator will use the cached
76    /// [`BranchNodeCompact::hashes`] to skip over the calculation of sub-tries in the overall
77    /// trie. The cached hashes cannot be used for any paths which are prefixes of a proof target.
78    cached_branch_stack: Vec<(Nibbles, BranchNodeCompact)>,
79    /// The proofs which will be returned from the calculation. This gets taken at the end of every
80    /// proof call.
81    retained_proofs: Vec<ProofTrieNodeV2>,
82    /// Free-list of re-usable buffers of [`RlpNode`]s, used for encoding branch nodes to RLP.
83    ///
84    /// We are generally able to re-use these buffers across different branch nodes for the
85    /// duration of a proof calculation, but occasionally we will lose one when a branch
86    /// node is returned as a `ProofTrieNode`.
87    rlp_nodes_bufs: Vec<Vec<RlpNode>>,
88    /// Re-usable byte buffer, used for RLP encoding.
89    rlp_encode_buf: Vec<u8>,
90    /// Prefix set for tracking changed keys.
91    prefix_set: PrefixSet,
92}
93
94impl<TC, HC, VE: LeafValueEncoder> ProofCalculator<TC, HC, VE> {
95    /// Create a new [`ProofCalculator`] instance for calculating account proofs.
96    pub fn new(trie_cursor: TC, hashed_cursor: HC) -> Self {
97        Self {
98            trie_cursor,
99            hashed_cursor,
100            branch_stack: Vec::<_>::with_capacity(64),
101            branch_path: Nibbles::new(),
102            child_stack: Vec::<_>::with_capacity(64),
103            cached_branch_stack: Vec::<_>::with_capacity(64),
104            retained_proofs: Vec::<_>::with_capacity(32),
105            rlp_nodes_bufs: Vec::<_>::with_capacity(8),
106            rlp_encode_buf: Vec::<_>::with_capacity(RLP_ENCODE_BUF_SIZE),
107            prefix_set: PrefixSet::default(),
108        }
109    }
110
111    /// Sets the prefix set and returns `self`.
112    ///
113    /// When given, all cached hashes matching the [`PrefixSet`] will be invalidated. When all but
114    /// one of a branch's children match the prefix set then that remaining child's cached hash, if
115    /// any, will also be invalidated. This allows for properly handling branch collapse situations,
116    /// where all but one child of a branch is deleted and the remaining child is required to be
117    /// unrevealed in order to collapse the branch.
118    pub fn with_prefix_set(mut self, prefix_set: PrefixSet) -> Self {
119        self.prefix_set = prefix_set;
120        self
121    }
122}
123
124impl<TC, HC, VE> ProofCalculator<TC, HC, VE>
125where
126    TC: TrieCursor,
127    HC: HashedCursor,
128    VE: LeafValueEncoder<Value = HC::Value>,
129{
130    /// Takes a re-usable `RlpNode` buffer from the internal free-list, or allocates a new one if
131    /// the free-list is empty.
132    ///
133    /// The returned Vec will have a length of zero.
134    fn take_rlp_nodes_buf(&mut self) -> Vec<RlpNode> {
135        self.rlp_nodes_bufs
136            .pop()
137            .map(|mut buf| {
138                buf.clear();
139                buf
140            })
141            .unwrap_or_else(|| Vec::with_capacity(16))
142    }
143
144    // Returns zero if `branch_stack` is empty, one otherwise.
145    //
146    // This is used when working with the `ext_len` field of [`ProofTrieBranch`]. The `ext_len` is
147    // calculated by taking the difference of the current `branch_path` and the new branch's path;
148    // if the new branch has a parent branch (ie `branch_stack` is not empty) then 1 is subtracted
149    // from the `ext_len` to account for the child's nibble on the parent.
150    #[inline]
151    const fn maybe_parent_nibble(&self) -> usize {
152        !self.branch_stack.is_empty() as usize
153    }
154
155    /// Returns true if the proof of a node at the given path should be retained. A node is retained
156    /// if its path is a prefix of any target.
157    ///
158    /// This may move the `targets` iterator forward if the given path comes after the current
159    /// target.
160    ///
161    /// This method takes advantage of the [`std::slice::Iter`] component of [`TargetsCursor`] to
162    /// check the minimum number of targets. In general it looks at a current target and the next
163    /// target simultaneously, forming an end-exclusive range.
164    ///
165    /// ```text
166    /// * Given targets: [ 0x012, 0x045, 0x678 ]
167    /// * targets.current() returns:
168    ///     - (0x012, Some(0x045)): covers (0x012..0x045)
169    ///     - (0x045, Some(0x678)): covers (0x045..0x678)
170    ///     - (0x678, None): covers (0x678..)
171    /// ```
172    ///
173    /// As long as the path which is passed in lies within that range we can continue to use the
174    /// current target. Once the path goes beyond that range (ie path >= next target) then we can be
175    /// sure that no further paths will be in the range, and we can iterate forward.
176    ///
177    /// ```text
178    /// * Given:
179    ///     - path: 0x04
180    ///     - targets.current() returns (0x012, Some(0x045))
181    ///
182    /// * 0x04 comes _after_ 0x045 in depth-first order, so (0x012..0x045) does not contain 0x04.
183    ///
184    /// * targets.next() is called.
185    ///
186    /// * targets.current() now returns (0x045, Some(0x678)). This does contain 0x04.
187    ///
188    /// * 0x04 is a prefix of 0x045, and so is retained.
189    /// ```
190    #[instrument(
191        target = TRACE_TARGET,
192        level = "trace",
193        skip_all,
194        fields(?path, ?check_parent_path),
195        ret,
196    )]
197    fn should_retain<'a>(
198        &self,
199        targets: &mut Option<TargetsCursor<'a>>,
200        path: &Nibbles,
201        check_parent_path: bool,
202    ) -> bool {
203        // If no targets are given then we never retain anything
204        let Some(targets) = targets.as_mut() else { return false };
205
206        let (mut lower, mut upper) = targets.current();
207
208        loop {
209            // If the node in question is a prefix of the target then we do not iterate targets
210            // further.
211            //
212            // Even if the node is a prefix of the target's key, a target with a parent path only
213            // retains nodes strictly below that already-revealed parent.
214            //
215            // _However_ even if the node doesn't match one target due to its parent path, it may
216            // match other targets whose keys match this node. So we search forwards and backwards
217            // for all targets which might match this node.
218            //
219            // For example, given a branch 0xabc, with children at 0, 1, and 2, and targets:
220            // - key: 0xabc0, parent path length: 1
221            // - key: 0xabc1, parent path length: 0
222            // - key: 0xabc2, parent path length: 3 <-- current
223            // - key: 0xabc3, parent path length: 2
224            //
225            // When the branch node at 0xabc is visited it will be after the targets has iterated
226            // forward to 0xabc2 (because all children will have been visited already). At this
227            // point the target for 0xabc2 will not match the branch due to its prefix, but any of
228            // the other targets would, so we need to check those as well.
229            if lower.key_nibbles.starts_with(path) {
230                let is_below_parent = |target: &ProofV2Target| {
231                    target.parent.path_len().is_none_or(|len| path.len() > len)
232                };
233                return !check_parent_path ||
234                    (is_below_parent(lower) ||
235                        targets
236                            .skip_iter()
237                            .take_while(|target| target.key_nibbles.starts_with(path))
238                            .any(is_below_parent) ||
239                        targets
240                            .rev_iter()
241                            .take_while(|target| target.key_nibbles.starts_with(path))
242                            .any(is_below_parent))
243            }
244
245            // If the path isn't in the current range then iterate forward until it is (or until
246            // there is no upper bound, indicating unbounded).
247            if upper
248                .is_some_and(|upper| depth_first::cmp(path, &upper.key_nibbles) != Ordering::Less)
249            {
250                (lower, upper) = targets.next();
251                trace!(target: TRACE_TARGET, target = ?lower, "upper target <= path, next target");
252            } else {
253                return false
254            }
255        }
256    }
257
258    /// Takes a child which has been removed from the `child_stack` and converts it to an
259    /// [`RlpNode`].
260    ///
261    /// Calling this method indicates that the child will not undergo any further modifications, and
262    /// therefore can be retained as a proof node if applicable.
263    fn commit_child<'a>(
264        &mut self,
265        targets: &mut Option<TargetsCursor<'a>>,
266        child_path: Nibbles,
267        child: ProofTrieBranchChild<VE::DeferredEncoder>,
268    ) -> Result<RlpNode, StateProofError> {
269        // If the child is already an `RlpNode` then there is nothing to do.
270        if let ProofTrieBranchChild::RlpNode(rlp_node) = child {
271            return Ok(rlp_node)
272        }
273
274        // If we should retain the child then do so.
275        if self.should_retain(targets, &child_path, true) {
276            trace!(target: TRACE_TARGET, ?child_path, "Retaining child");
277
278            // Convert to `ProofTrieNodeV2`, which will be what is retained.
279            //
280            // If this node is a branch then its `rlp_nodes_buf` will be taken and not returned to
281            // the `rlp_nodes_bufs` free-list.
282            self.rlp_encode_buf.clear();
283            let proof_node = child.into_proof_trie_node(child_path, &mut self.rlp_encode_buf)?;
284
285            // Use the `ProofTrieNodeV2` to encode the `RlpNode`, and then push it onto retained
286            // nodes before returning.
287            self.rlp_encode_buf.clear();
288            proof_node.node.encode(&mut self.rlp_encode_buf);
289
290            self.retained_proofs.push(proof_node);
291            return Ok(RlpNode::from_rlp(&self.rlp_encode_buf));
292        }
293
294        // If the child path is not being retained then we convert directly to an `RlpNode`
295        // using `into_rlp`. Since we are not retaining the node we can recover any `RlpNode`
296        // buffers for the free-list here, hence why we do this as a separate logical branch.
297        self.rlp_encode_buf.clear();
298        let (child_rlp_node, freed_rlp_nodes_buf) = child.into_rlp(&mut self.rlp_encode_buf)?;
299
300        // If there is an `RlpNode` buffer which can be re-used then push it onto the free-list.
301        if let Some(buf) = freed_rlp_nodes_buf {
302            self.rlp_nodes_bufs.push(buf);
303        }
304
305        Ok(child_rlp_node)
306    }
307
308    /// Returns the path of the child of the currently under-construction branch at the given
309    /// nibble.
310    #[inline]
311    fn child_path_at(&self, nibble: u8) -> Nibbles {
312        let mut child_path = self.branch_path;
313        debug_assert!(child_path.len() < 64);
314        child_path.push_unchecked(nibble);
315        child_path
316    }
317
318    /// Returns index of the highest nibble which is set in the mask.
319    ///
320    /// # Panics
321    ///
322    /// Will panic in debug mode if the mask is empty.
323    #[inline]
324    fn highest_set_nibble(mask: TrieMask) -> u8 {
325        debug_assert!(!mask.is_empty());
326        (u16::BITS - mask.leading_zeros() - 1) as u8
327    }
328
329    /// Returns the path of the child on top of the `child_stack`, or the root path if the stack is
330    /// empty. Returns None if the current branch has not yet pushed a child (empty `state_mask`).
331    fn last_child_path(&self) -> Option<Nibbles> {
332        // If there is no branch under construction then the top child must be the root child.
333        let Some(branch) = self.branch_stack.last() else {
334            return Some(Nibbles::new());
335        };
336
337        (!branch.state_mask.is_empty())
338            .then(|| self.child_path_at(Self::highest_set_nibble(branch.state_mask)))
339    }
340
341    /// Calls [`Self::commit_child`] on the last child of `child_stack`, replacing it with a
342    /// [`ProofTrieBranchChild::RlpNode`].
343    ///
344    /// If `child_stack` is empty then this is a no-op.
345    ///
346    /// NOTE that this method call relies on the `state_mask` of the top branch of the
347    /// `branch_stack` to determine the last child's path. When committing the last child prior to
348    /// pushing a new child, it's important to set the new child's `state_mask` bit _after_ the call
349    /// to this method.
350    #[instrument(
351        target = TRACE_TARGET,
352        level = "trace",
353        skip_all,
354        fields(child_path = ?self.last_child_path()),
355    )]
356    fn commit_last_child<'a>(
357        &mut self,
358        targets: &mut Option<TargetsCursor<'a>>,
359    ) -> Result<(), StateProofError> {
360        if matches!(self.child_stack.last(), Some(ProofTrieBranchChild::RlpNode(_))) {
361            trace!(target: TRACE_TARGET, "Last child already committed, leaving stack unchanged");
362            return Ok(())
363        }
364
365        let Some(child_path) = self.last_child_path() else { return Ok(()) };
366        let child =
367            self.child_stack.pop().expect("child_stack can't be empty if there's a child path");
368
369        // Only commit immediately if retained for the proof. Otherwise, defer conversion
370        // to pop_branch() to give DeferredEncoder time for async work.
371        if self.should_retain(targets, &child_path, true) {
372            let child_rlp_node = self.commit_child(targets, child_path, child)?;
373            trace!(target: TRACE_TARGET, ?child_rlp_node, "Pushing committed child RlpNode onto stack");
374            self.child_stack.push(ProofTrieBranchChild::RlpNode(child_rlp_node));
375        } else {
376            trace!(target: TRACE_TARGET, "Pushing uncommitted child onto stack");
377            self.child_stack.push(child);
378        }
379
380        Ok(())
381    }
382
383    /// Creates a new leaf node on a branch, setting its `state_mask` bit and pushing the leaf onto
384    /// the `child_stack`.
385    ///
386    /// # Panics
387    ///
388    /// - If `branch_stack` is empty
389    /// - If the leaf's nibble is already set in the branch's `state_mask`.
390    fn push_new_leaf<'a>(
391        &mut self,
392        targets: &mut Option<TargetsCursor<'a>>,
393        leaf_nibble: u8,
394        leaf_short_key: Nibbles,
395        leaf_val: VE::DeferredEncoder,
396    ) -> Result<(), StateProofError> {
397        // Before pushing the new leaf onto the `child_stack` we need to commit the previous last
398        // child, so that only `child_stack`'s final child is a non-RlpNode.
399        self.commit_last_child(targets)?;
400
401        // Once the last child is committed we set the new child's bit on the top branch's
402        // `state_mask` and push that new child.
403        let branch = self.branch_stack.last_mut().expect("branch_stack cannot be empty");
404
405        debug_assert!(!branch.state_mask.is_bit_set(leaf_nibble));
406        branch.state_mask.set_bit(leaf_nibble);
407
408        self.child_stack
409            .push(ProofTrieBranchChild::Leaf { short_key: leaf_short_key, value: leaf_val });
410
411        Ok(())
412    }
413
414    /// Pushes a new branch onto the `branch_stack` based on the path and short key of the last
415    /// child on the `child_stack` and the path of the next child which will be pushed on to the
416    /// stack after this call.
417    ///
418    /// Returns the nibble of the branch's `state_mask` which should be set for the new child, and
419    /// short key that the next child should use.
420    fn push_new_branch(&mut self, new_child_path: Nibbles) -> (u8, Nibbles) {
421        // First determine the new child's shortkey relative to the current branch. If there is no
422        // current branch then the short key is the full path.
423        let new_child_short_key = if self.branch_stack.is_empty() {
424            new_child_path
425        } else {
426            // When there is a current branch then trim off its path as well as the nibble that it
427            // has set for this leaf.
428            trim_nibbles_prefix(&new_child_path, self.branch_path.len() + 1)
429        };
430
431        // Get the new branch's first child, which is the child on the top of the stack with which
432        // the new child shares the same nibble on the current branch.
433        let first_child = self
434            .child_stack
435            .last_mut()
436            .expect("push_new_branch can't be called with empty child_stack");
437
438        let first_child_short_key = first_child.short_key();
439        debug_assert!(
440            !first_child_short_key.is_empty(),
441            "push_new_branch called when top child on stack is not a leaf or extension with a short key",
442        );
443
444        // Determine how many nibbles are shared between the new branch's first child and the new
445        // child. This common prefix will be the extension of the new branch
446        let common_prefix_len = first_child_short_key.common_prefix_length(&new_child_short_key);
447
448        // Trim off the common prefix from the first child's short key, plus one nibble which will
449        // stored by the new branch itself in its state mask.
450        let first_child_nibble = first_child_short_key.get_unchecked(common_prefix_len);
451        first_child.trim_short_key_prefix(common_prefix_len + 1);
452
453        // Similarly, trim off the common prefix, plus one nibble for the new branch, from the new
454        // child's short key.
455        let new_child_nibble = new_child_short_key.get_unchecked(common_prefix_len);
456        let new_child_short_key = trim_nibbles_prefix(&new_child_short_key, common_prefix_len + 1);
457
458        // Update the branch path to reflect the new branch about to be pushed. Its path will be
459        // the path of the previous branch, plus the nibble shared by each child, plus the parent
460        // extension (denoted by a non-zero `ext_len`). Since the new branch's path is a prefix of
461        // the original new_child_path we can just slice that.
462        //
463        // If the new branch is the first branch then we do not add the extra 1, as there is no
464        // nibble in a parent branch to account for.
465        let branch_path_len =
466            self.branch_path.len() + common_prefix_len + self.maybe_parent_nibble();
467        self.branch_path = new_child_path.slice_unchecked(0, branch_path_len);
468
469        // Push the new branch onto the `branch_stack`. We do not yet set the `state_mask` bit of
470        // the new child; whatever actually pushes the child onto the `child_stack` is expected to
471        // do that.
472        self.branch_stack.push(ProofTrieBranch {
473            ext_len: common_prefix_len as u8,
474            state_mask: TrieMask::new(1 << first_child_nibble),
475            masks: None,
476        });
477
478        trace!(
479            target: TRACE_TARGET,
480            ?new_child_path,
481            ?common_prefix_len,
482            ?first_child_nibble,
483            branch_path = ?self.branch_path,
484            "Pushed new branch",
485        );
486
487        (new_child_nibble, new_child_short_key)
488    }
489
490    /// Pops the top branch off of the `branch_stack`, hashes its children on the `child_stack`, and
491    /// replaces those children on the `child_stack`. The `branch_path` field will be updated
492    /// accordingly.
493    ///
494    /// # Panics
495    ///
496    /// This method panics if `branch_stack` is empty.
497    #[instrument(target = TRACE_TARGET, level = "trace", skip_all)]
498    fn pop_branch<'a>(
499        &mut self,
500        targets: &mut Option<TargetsCursor<'a>>,
501    ) -> Result<(), StateProofError> {
502        trace!(
503            target: TRACE_TARGET,
504            branch = ?self.branch_stack.last(),
505            branch_path = ?self.branch_path,
506            child_stack_len = ?self.child_stack.len(),
507            "called",
508        );
509
510        // Ensure the final child on the child stack has been committed, as this method expects all
511        // children of the branch to have been committed.
512        self.commit_last_child(targets)?;
513
514        let mut rlp_nodes_buf = self.take_rlp_nodes_buf();
515        let branch = self.branch_stack.pop().expect("branch_stack cannot be empty");
516
517        // Take the branch's children off the stack, using the state mask to determine how many
518        // there are.
519        let num_children = branch.state_mask.count_ones() as usize;
520        debug_assert!(
521            self.child_stack.len() >= num_children,
522            "Stack is missing necessary children ({num_children:?})"
523        );
524        debug_assert!(
525            num_children >= 2,
526            "A branch must have at least two children, got {num_children}"
527        );
528
529        // Collect children into RlpNode Vec. Children are in lexicographic order.
530        rlp_nodes_buf.reserve(num_children);
531        for child in self.child_stack.drain(self.child_stack.len() - num_children..) {
532            let child_rlp_node = match child {
533                ProofTrieBranchChild::RlpNode(rlp_node) => rlp_node,
534                uncommitted_child => {
535                    // Convert uncommitted child (not retained for proof) to RlpNode now.
536                    self.rlp_encode_buf.clear();
537                    let (rlp_node, freed_buf) =
538                        uncommitted_child.into_rlp(&mut self.rlp_encode_buf)?;
539                    if let Some(buf) = freed_buf {
540                        self.rlp_nodes_bufs.push(buf);
541                    }
542                    rlp_node
543                }
544            };
545            rlp_nodes_buf.push(child_rlp_node);
546        }
547
548        debug_assert_eq!(
549            rlp_nodes_buf.len(),
550            num_children,
551            "children length must match number of bits set in state_mask"
552        );
553
554        // Calculate the short key of the parent extension (if the branch has a parent extension).
555        // It's important to calculate this short key prior to modifying the `branch_path`.
556        let short_key = trim_nibbles_prefix(
557            &self.branch_path,
558            self.branch_path.len() - branch.ext_len as usize,
559        );
560
561        // Compute hash for the branch node if it has a parent extension.
562        let rlp_node = if short_key.is_empty() {
563            None
564        } else {
565            self.rlp_encode_buf.clear();
566            BranchNodeRef::new(&rlp_nodes_buf, branch.state_mask).encode(&mut self.rlp_encode_buf);
567            Some(RlpNode::from_rlp(&self.rlp_encode_buf))
568        };
569
570        // Wrap the `BranchNodeV2` so it can be pushed onto the child stack.
571        let branch_as_child = ProofTrieBranchChild::Branch {
572            node: BranchNodeV2::new(short_key, rlp_nodes_buf, branch.state_mask, rlp_node),
573            masks: branch.masks,
574        };
575
576        self.child_stack.push(branch_as_child);
577
578        // Update the branch_path. If this branch is the only branch then only its extension needs
579        // to be trimmed, otherwise we also need to remove its nibble from its parent.
580        let new_path_len =
581            self.branch_path.len() - branch.ext_len as usize - self.maybe_parent_nibble();
582
583        debug_assert!(self.branch_path.len() >= new_path_len);
584        self.branch_path = self.branch_path.slice_unchecked(0, new_path_len);
585
586        Ok(())
587    }
588
589    /// Adds a single leaf for a key to the stack, possibly collapsing an existing branch and/or
590    /// creating a new one depending on the path of the key.
591    fn push_leaf<'a>(
592        &mut self,
593        targets: &mut Option<TargetsCursor<'a>>,
594        key: Nibbles,
595        val: VE::DeferredEncoder,
596    ) -> Result<(), StateProofError> {
597        loop {
598            trace!(
599                target: TRACE_TARGET,
600                ?key,
601                branch_stack_len = ?self.branch_stack.len(),
602                branch_path = ?self.branch_path,
603                child_stack_len = ?self.child_stack.len(),
604                "push_leaf: loop",
605            );
606
607            // Get the `state_mask` of the branch currently being built. If there are no branches
608            // on the stack then it means either the trie is empty or only a single leaf has been
609            // added previously.
610            let curr_branch_state_mask = match self.branch_stack.last() {
611                Some(curr_branch) => curr_branch.state_mask,
612                None if self.child_stack.is_empty() => {
613                    // If the child stack is empty then this is the first leaf, push it and be done
614                    self.child_stack
615                        .push(ProofTrieBranchChild::Leaf { short_key: key, value: val });
616                    return Ok(())
617                }
618                None => {
619                    // If the child stack is not empty then it must only have a single other child
620                    // which is either a leaf or extension with a non-zero short key.
621                    debug_assert_eq!(self.child_stack.len(), 1);
622                    debug_assert!(!self
623                        .child_stack
624                        .last()
625                        .expect("already checked for emptiness")
626                        .short_key()
627                        .is_empty());
628                    let (nibble, short_key) = self.push_new_branch(key);
629                    self.push_new_leaf(targets, nibble, short_key, val)?;
630                    return Ok(())
631                }
632            };
633
634            // Find the common prefix length, which is the number of nibbles shared between the
635            // current branch and the key.
636            let common_prefix_len = self.branch_path.common_prefix_length(&key);
637
638            // If the current branch does not share all of its nibbles with the new key then it is
639            // not the parent of the new key. In this case the current branch will have no more
640            // children. We can pop it and loop back to the top to try again with its parent branch.
641            if common_prefix_len < self.branch_path.len() {
642                self.pop_branch(targets)?;
643                continue
644            }
645
646            // If the current branch is a prefix of the new key then the leaf is a child of the
647            // branch. If the branch doesn't have the leaf's nibble set then the leaf can be added
648            // directly, otherwise a new branch must be created in-between this branch and that
649            // existing child.
650            let nibble = key.get_unchecked(common_prefix_len);
651            if curr_branch_state_mask.is_bit_set(nibble) {
652                // Push a new branch which splits the short key of the existing child at this
653                // nibble.
654                let (nibble, short_key) = self.push_new_branch(key);
655                // Push the new leaf onto the new branch.
656                self.push_new_leaf(targets, nibble, short_key, val)?;
657            } else {
658                let short_key = key.slice_unchecked(common_prefix_len + 1, key.len());
659                self.push_new_leaf(targets, nibble, short_key, val)?;
660            }
661
662            return Ok(())
663        }
664    }
665
666    /// Given the lower and upper bounds (exclusive) of a range of keys, iterates over the
667    /// `hashed_cursor` and calculates all trie nodes possible based on those keys. If the upper
668    /// bound is None then it is considered unbounded.
669    ///
670    /// It is expected that this method is "driven" by `next_uncached_key_range`, which decides
671    /// which ranges of keys need to be calculated based on what cached trie data is available.
672    #[instrument(
673        target = TRACE_TARGET,
674        level = "trace",
675        skip_all,
676        fields(?lower_bound, ?upper_bound),
677    )]
678    fn calculate_key_range<'a>(
679        &mut self,
680        value_encoder: &mut VE,
681        targets: &mut Option<TargetsCursor<'a>>,
682        hashed_cursor_state: &mut HashedCursorState<VE::DeferredEncoder>,
683        lower_bound: Nibbles,
684        upper_bound: Option<Nibbles>,
685    ) -> Result<(), StateProofError> {
686        // A helper closure for mapping entries returned from the `hashed_cursor`, converting the
687        // key to Nibbles and immediately creating the DeferredValueEncoder so that encoding of the
688        // leaf value can begin ASAP.
689        let mut map_hashed_cursor_entry = |(key_b256, val): (B256, _)| {
690            debug_assert_eq!(key_b256.len(), 32);
691            let key = Nibbles::unpack_array(key_b256.as_ref());
692            let val = value_encoder.deferred_encoder(key_b256, val);
693            (key, val)
694        };
695
696        // If the cursor hasn't been used, or the last iterated key is prior to this range's key
697        // range, then seek forward to at least the first key.
698        if hashed_cursor_state.needs_seek_to(&lower_bound) {
699            trace!(
700                target: TRACE_TARGET,
701                current=?hashed_cursor_state.path(),
702                "Seeking hashed cursor to meet lower bound",
703            );
704
705            let lower_key = B256::right_padding_from(&lower_bound.pack());
706            *hashed_cursor_state = HashedCursorState::seeked(
707                lower_bound,
708                self.hashed_cursor.seek(lower_key)?.map(&mut map_hashed_cursor_entry),
709            );
710        }
711
712        // Loop over all keys in the range, calling `push_leaf` on each.
713        while hashed_cursor_state
714            .path()
715            .is_some_and(|key| upper_bound.is_none_or(|upper_bound| key < &upper_bound))
716        {
717            let (key, val) = hashed_cursor_state.take();
718            self.push_leaf(targets, key, val)?;
719            *hashed_cursor_state = HashedCursorState::seeked(
720                key,
721                self.hashed_cursor.next()?.map(&mut map_hashed_cursor_entry),
722            );
723        }
724
725        trace!(target: TRACE_TARGET, "No further keys within range");
726        Ok(())
727    }
728
729    /// Constructs and returns a new [`ProofTrieBranch`] based on an existing [`BranchNodeCompact`].
730    #[inline]
731    const fn new_from_cached_branch(
732        cached_branch: &BranchNodeCompact,
733        ext_len: u8,
734    ) -> ProofTrieBranch {
735        ProofTrieBranch {
736            ext_len,
737            state_mask: TrieMask::new(0),
738            masks: Some(BranchNodeMasks {
739                tree_mask: cached_branch.tree_mask,
740                hash_mask: cached_branch.hash_mask,
741            }),
742        }
743    }
744
745    /// Pushes a new branch onto the `branch_stack` which is based on a cached branch obtained via
746    /// the trie cursor.
747    ///
748    /// If there is already a child at the top branch of `branch_stack` occupying this new branch's
749    /// nibble then that child will have its short-key split with another new branch, and this
750    /// cached branch will be a child of that splitting branch.
751    fn push_cached_branch<'a>(
752        &mut self,
753        targets: &mut Option<TargetsCursor<'a>>,
754        cached_path: Nibbles,
755        cached_branch: &BranchNodeCompact,
756    ) -> Result<(), StateProofError> {
757        debug_assert!(
758            cached_path.starts_with(&self.branch_path),
759            "push_cached_branch called with path {cached_path:?} which is not a child of current branch {:?}",
760            self.branch_path,
761        );
762
763        let parent_branch = self.branch_stack.last();
764
765        // If both stacks are empty then there were no leaves before this cached branch, push it and
766        // be done; the extension of the branch will be its full path.
767        if self.child_stack.is_empty() && parent_branch.is_none() {
768            self.branch_path = cached_path;
769            self.branch_stack
770                .push(Self::new_from_cached_branch(cached_branch, cached_path.len() as u8));
771            return Ok(())
772        }
773
774        // Get the nibble which should be set in the parent branch's `state_mask` for this new
775        // branch.
776        let cached_branch_nibble = cached_path.get_unchecked(self.branch_path.len());
777
778        // We calculate the `ext_len` of the new branch, and potentially update its nibble if a new
779        // parent branch is inserted here, based on the state of the parent branch.
780        let (cached_branch_nibble, ext_len) = if parent_branch
781            .is_none_or(|parent_branch| parent_branch.state_mask.is_bit_set(cached_branch_nibble))
782        {
783            // If the `child_stack` is not empty but the `branch_stack` is then it implies that
784            // there must be a leaf or extension at the root of the trie whose short-key will get
785            // split by a new branch, which will become the parent of both that leaf/extension and
786            // this new branch.
787            //
788            // Similarly, if there is a branch on the `branch_stack` but its `state_mask` bit for
789            // this new branch is already set, then there must be a leaf/extension with a short-key
790            // to be split.
791            debug_assert!(!self
792                .child_stack
793                .last()
794                .expect("already checked for emptiness")
795                .short_key()
796                .is_empty());
797
798            // Split that leaf/extension's short key with a new branch.
799            let (nibble, short_key) = self.push_new_branch(cached_path);
800            (nibble, short_key.len())
801        } else {
802            // If there is a parent branch but its `state_mask` bit for this branch is not set
803            // then we can simply calculate the `ext_len` based on the difference of each, minus
804            // 1 to account for the nibble in the `state_mask`.
805            (cached_branch_nibble, cached_path.len() - self.branch_path.len() - 1)
806        };
807
808        // `commit_last_child` relies on the last set bit of the parent branch's `state_mask` to
809        // determine the path of the last child on the `child_stack`. Since we are about to
810        // change that mask we need to commit that last child first.
811        self.commit_last_child(targets)?;
812
813        // When pushing a new branch we need to set its child nibble in the `state_mask` of
814        // its parent, if there is one.
815        if let Some(parent_branch) = self.branch_stack.last_mut() {
816            parent_branch.state_mask.set_bit(cached_branch_nibble);
817        }
818
819        // Finally update the `branch_path` and push the new branch.
820        self.branch_path = cached_path;
821        self.branch_stack.push(Self::new_from_cached_branch(cached_branch, ext_len as u8));
822
823        trace!(
824            target: TRACE_TARGET,
825            branch=?self.branch_stack.last(),
826            branch_path=?self.branch_path,
827            "Pushed cached branch",
828        );
829
830        Ok(())
831    }
832
833    /// Wraps [`TrieCursor::seek`], skipping cached branches whose sub-tries must be recalculated
834    /// from leaves.
835    ///
836    /// A cached branch is skipped when all but at most one of its children match the prefix set.
837    /// In that case those children might all be deleted, leaving a branch with a single child.
838    /// A single-child branch must be collapsed, but collapsing requires the child to be a full
839    /// node (not a cached hash). Skipping the branch avoids this by forcing recalculation.
840    fn trie_cursor_seek(
841        &mut self,
842        key: Nibbles,
843    ) -> Result<Option<(Nibbles, BranchNodeCompact)>, StateProofError> {
844        let mut entry = self.trie_cursor.seek(key)?;
845        while let Some((ref path, ref branch)) = entry {
846            if !self.should_skip_cached_branch(path, branch) {
847                break
848            }
849            entry = self.trie_cursor.next()?;
850        }
851        Ok(entry)
852    }
853
854    /// Returns true if the cached branch should be skipped entirely and its sub-trie recalculated
855    /// from leaves.
856    fn should_skip_cached_branch(
857        &mut self,
858        cached_path: &Nibbles,
859        cached_branch: &BranchNodeCompact,
860    ) -> bool {
861        if !self.prefix_set.contains(cached_path) {
862            return false
863        }
864
865        let mut num_unmatched = 0u32;
866        let mut child_path = *cached_path;
867        for nibble in 0u8..16 {
868            if cached_branch.state_mask.is_bit_set(nibble) {
869                child_path.truncate(cached_path.len());
870                child_path.push_unchecked(nibble);
871                if !self.prefix_set.contains(&child_path) {
872                    num_unmatched += 1;
873                }
874            }
875        }
876
877        if num_unmatched <= 1 {
878            trace!(
879                target: TRACE_TARGET,
880                ?cached_path,
881                ?num_unmatched,
882                "Skipping cached branch: all but <=1 children match prefix set, branch may collapse",
883            );
884            true
885        } else {
886            false
887        }
888    }
889
890    /// Attempts to pop off the top branch of the `cached_branch_stack`, returning
891    /// [`PopCachedBranchOutcome::Popped`] on success. Returns other variants to indicate that the
892    /// stack is empty and what to do about it.
893    ///
894    /// This method only returns [`PopCachedBranchOutcome::CalculateLeaves`] if there is a cached
895    /// branch on top of the stack.
896    #[inline]
897    fn try_pop_cached_branch(
898        &mut self,
899        trie_cursor_state: &mut TrieCursorState,
900        traversal_upper_bound: Option<&Nibbles>,
901        uncalculated_lower_bound: &Option<Nibbles>,
902    ) -> Result<PopCachedBranchOutcome, StateProofError> {
903        // If the `uncalculated_lower_bound` is None it indicates that there can be no more
904        // leaf data, so similarly there can be no more cached branch data.
905        let Some(uncalculated_lower_bound) = uncalculated_lower_bound else {
906            return Ok(PopCachedBranchOutcome::Exhausted)
907        };
908
909        // If there is a branch on top of the stack we use that.
910        if let Some(cached) = self.cached_branch_stack.pop() {
911            return Ok(PopCachedBranchOutcome::Popped(cached));
912        }
913
914        // There is no cached branch on the stack. It's possible that another one exists
915        // farther on in the trie, but we perform some checks first to prevent unnecessary
916        // attempts to find it.
917
918        // If [`TrieCursorState::path`] returns None it means that the cursor has been
919        // exhausted, so there can be no more cached data.
920        let Some(mut trie_cursor_path) = trie_cursor_state.path() else {
921            return Ok(PopCachedBranchOutcome::Exhausted)
922        };
923
924        // If the trie cursor is seeked to a branch whose leaves have already been processed
925        // then we can't use it, instead we seek forward and try again.
926        if trie_cursor_path < uncalculated_lower_bound {
927            *trie_cursor_state = TrieCursorState::seeked(
928                *uncalculated_lower_bound,
929                self.trie_cursor_seek(*uncalculated_lower_bound)?,
930            );
931
932            // Having just seeked forward we need to check if the cursor is now exhausted,
933            // extracting the new path at the same time.
934            if let Some(new_trie_cursor_path) = trie_cursor_state.path() {
935                trie_cursor_path = new_trie_cursor_path
936            } else {
937                return Ok(PopCachedBranchOutcome::Exhausted)
938            };
939        }
940
941        // If the trie cursor has reached the end of the traversal range then we consider cached
942        // data to be exhausted. The cursor itself remains positioned for reuse by a later range.
943        if traversal_upper_bound.is_some_and(|upper_bound| trie_cursor_path >= upper_bound) {
944            return Ok(PopCachedBranchOutcome::Exhausted)
945        }
946
947        // At this point we can be sure that the cursor is in an `Available` state. We know for
948        // sure it's not `Exhausted` because of the calls to `path` above, and we know it's not
949        // `Taken` because we push all taken branches onto the `cached_branch_stack`, and the
950        // stack is empty.
951        //
952        // We will use this `Available` cached branch as our next branch.
953        let cached = trie_cursor_state.take();
954        trace!(target: TRACE_TARGET, cached=?cached, "Pushed next trie node onto cached_branch_stack");
955
956        // If the calculated range is not caught up to the next cached branch it means there
957        // are portions of the trie prior to that branch which may need to be calculated;
958        // return the uncalculated range up to that branch to make that happen.
959        //
960        // If the next cached branch's path is all zeros then we can skip this catch-up step,
961        // because there cannot be any keys prior to that range.
962        let cached_path = &cached.0;
963        if uncalculated_lower_bound < cached_path && !cached_path.is_zeroes() {
964            let range = (*uncalculated_lower_bound, Some(*cached_path));
965            trace!(target: TRACE_TARGET, ?range, "Returning key range to calculate in order to catch up to cached branch");
966
967            // Push the cached branch onto the stack so it's available once the leaf range is done
968            // being calculated.
969            self.cached_branch_stack.push(cached);
970
971            return Ok(PopCachedBranchOutcome::CalculateLeaves(range));
972        }
973
974        Ok(PopCachedBranchOutcome::Popped(cached))
975    }
976
977    // Pop any under-construction branches that are now complete. Assumes that all trie data prior
978    // to `next_path`, if any, has been computed. Any branches which were under-construction
979    // previously, and which do not share a prefix with `next_path`, can be assumed to be completed;
980    // they will not have any further keys added to them.
981    fn commit_branches<'a>(
982        &mut self,
983        targets: &mut Option<TargetsCursor<'a>>,
984        next_path: &Nibbles,
985    ) -> Result<(), StateProofError> {
986        while !next_path.starts_with(&self.branch_path) {
987            self.pop_branch(targets)?;
988        }
989        Ok(())
990    }
991
992    /// Accepts the current state of both hashed and trie cursors, and determines the next range of
993    /// hashed keys which need to be processed using [`Self::push_leaf`].
994    ///
995    /// This method will use cached branch node data from the trie cursor to skip over all possible
996    /// ranges of keys, to reduce computation as much as possible.
997    ///
998    /// # Returns
999    ///
1000    /// - `None`: No more data to process, finish computation
1001    ///
1002    /// - `Some(lower, None)`: Indicates to call `push_leaf` on all keys starting at `lower`, with
1003    ///   no upper bound. This method won't be called again after this.
1004    ///
1005    /// - `Some(lower, Some(upper))`: Indicates to call `push_leaf` on all keys starting at `lower`,
1006    ///   up to but excluding `upper`, and then call this method once done.
1007    ///
1008    /// Once returned the `branch_stack` will be in the correct state to start calculating leaves
1009    /// for the given range, if any.
1010    #[instrument(target = TRACE_TARGET, level = "trace", skip_all)]
1011    fn next_uncached_key_range<'a>(
1012        &mut self,
1013        targets: &mut Option<TargetsCursor<'a>>,
1014        trie_cursor_state: &mut TrieCursorState,
1015        traversal_upper_bound: Option<&Nibbles>,
1016        mut uncalculated_lower_bound: Option<Nibbles>,
1017    ) -> Result<Option<(Nibbles, Option<Nibbles>)>, StateProofError> {
1018        loop {
1019            if let (Some(lower_bound), Some(upper_bound)) =
1020                (uncalculated_lower_bound.as_ref(), traversal_upper_bound) &&
1021                lower_bound >= upper_bound
1022            {
1023                return Ok(None)
1024            }
1025
1026            // Pop the currently cached branch node.
1027            //
1028            // NOTE we pop off the `cached_branch_stack` because cloning the `BranchNodeCompact`
1029            // means cloning an Arc, which incurs synchronization overhead. We have to be sure to
1030            // push the cached branch back onto the stack once done.
1031            let (cached_path, cached_branch) = match self.try_pop_cached_branch(
1032                trie_cursor_state,
1033                traversal_upper_bound,
1034                &uncalculated_lower_bound,
1035            )? {
1036                PopCachedBranchOutcome::Popped(cached) => cached,
1037                PopCachedBranchOutcome::Exhausted => {
1038                    // If cached branches are exhausted it's possible that there is still an
1039                    // unbounded range of leaves to be processed. `uncalculated_lower_bound` is
1040                    // used to return that range.
1041                    trace!(target: TRACE_TARGET, ?uncalculated_lower_bound, "Exhausted cached trie nodes");
1042                    if let Some(lower) = uncalculated_lower_bound {
1043                        self.commit_branches(targets, &lower)?;
1044                        return Ok(Some((lower, traversal_upper_bound.copied())));
1045                    }
1046                    return Ok(None)
1047                }
1048                PopCachedBranchOutcome::CalculateLeaves(range) => {
1049                    self.commit_branches(targets, &range.0)?;
1050                    return Ok(Some(range));
1051                }
1052            };
1053
1054            let uncalculated_lower_bound_ref = uncalculated_lower_bound
1055                .as_ref()
1056                .expect("try_pop_cached_branch would return Exhausted if this were None");
1057
1058            trace!(
1059                target: TRACE_TARGET,
1060                branch_path = ?self.branch_path,
1061                branch_state_mask = ?self.branch_stack.last().map(|b| b.state_mask),
1062                ?cached_path,
1063                cached_branch_state_mask = ?cached_branch.state_mask,
1064                cached_branch_hash_mask = ?cached_branch.hash_mask,
1065                "loop",
1066            );
1067
1068            self.commit_branches(targets, &cached_path)?;
1069
1070            // Since we've popped all branches which don't start with cached_path, branch_path at
1071            // this point must be equal to or shorter than cached_path.
1072            debug_assert!(
1073                self.branch_path.len() < cached_path.len() || self.branch_path == cached_path,
1074                "branch_path {:?} is different-or-longer-than cached_path {cached_path:?}",
1075                self.branch_path
1076            );
1077
1078            // If the branch_path != cached_path it means the branch_stack is either empty, or the
1079            // top branch is the parent of this cached branch. Either way we push a branch
1080            // corresponding to the cached one onto the stack, so we can begin constructing it.
1081            if self.branch_path != cached_path {
1082                self.push_cached_branch(targets, cached_path, &cached_branch)?;
1083            }
1084
1085            // At this point the top of the branch stack is the same branch which was found in the
1086            // cache.
1087            let curr_branch =
1088                self.branch_stack.last().expect("top of branch_stack corresponds to cached branch");
1089
1090            let cached_state_mask = cached_branch.state_mask;
1091            let curr_state_mask = curr_branch.state_mask;
1092
1093            // Determine all child nibbles which are set in the cached branch but not the
1094            // under-construction branch.
1095            let mut next_child_nibbles = curr_state_mask ^ cached_state_mask;
1096
1097            // Also include child nibbles indicated by the prefix set. The prefix set can
1098            // indicate children that need recalculation from leaves (e.g. new keys inserted
1099            // under this branch). Skip nibbles already set in `curr_state_mask` since those
1100            // children have already been constructed.
1101            if self.prefix_set.contains(&self.branch_path) {
1102                let branch_path_len = self.branch_path.len();
1103                let mut child_path = self.branch_path;
1104                for nibble in 0u8..16 {
1105                    if !curr_state_mask.is_bit_set(nibble) {
1106                        child_path.truncate(branch_path_len);
1107                        child_path.push_unchecked(nibble);
1108                        if self.prefix_set.contains(&child_path) {
1109                            next_child_nibbles.set_bit(nibble);
1110                        }
1111                    }
1112                }
1113            }
1114
1115            let _orig_next_child_nibbles = next_child_nibbles;
1116
1117            // Mask out any child nibbles whose ranges have already been fully processed.
1118            // This can happen when `calculate_key_range` finds no keys for a child's range,
1119            // leaving the child's bit unset in `state_mask`. Without this, re-entering this
1120            // function would select the same child again.
1121            if uncalculated_lower_bound_ref.starts_with(&self.branch_path) &&
1122                uncalculated_lower_bound_ref.len() > self.branch_path.len()
1123            {
1124                let lower_nibble =
1125                    uncalculated_lower_bound_ref.get_unchecked(self.branch_path.len());
1126                // Clear all nibbles strictly below `lower_nibble` since they've been processed.
1127                let already_processed_mask = TrieMask::new((1u16 << lower_nibble) - 1);
1128                next_child_nibbles &= !already_processed_mask;
1129                trace!(
1130                    target: TRACE_TARGET,
1131                    branch_path = ?self.branch_path,
1132                    ?_orig_next_child_nibbles,
1133                    ?already_processed_mask,
1134                    ?next_child_nibbles,
1135                    "Unset already processed key nibbles from next_child_nibbles",
1136                );
1137            } else if !uncalculated_lower_bound_ref.starts_with(&self.branch_path) &&
1138                uncalculated_lower_bound_ref > &self.branch_path
1139            {
1140                // The lower bound has moved entirely past this branch (e.g. branch is 0x6 but
1141                // lower is 0x7). All remaining children have been processed.
1142                next_child_nibbles = TrieMask::default();
1143                trace!(
1144                    target: TRACE_TARGET,
1145                    branch_path = ?self.branch_path,
1146                    ?_orig_next_child_nibbles,
1147                    ?next_child_nibbles,
1148                    "Unset all nibbles from next_child_nibbles due to branch_path being outside this subtrie",
1149                );
1150            }
1151
1152            // If there are no further children to construct for this branch then pop it off both
1153            // stacks and loop using the parent branch.
1154            if next_child_nibbles.is_empty() {
1155                trace!(
1156                    target: TRACE_TARGET,
1157                    path=?cached_path,
1158                    ?curr_branch,
1159                    ?cached_branch,
1160                    "No further children, popping branch",
1161                );
1162                self.pop_branch(targets)?;
1163
1164                // no need to pop from `cached_branch_stack`, the current cached branch is already
1165                // popped (see note at the top of the loop).
1166
1167                // The just-popped branch is completely processed; we know there can be no more keys
1168                // with that prefix. Set the lower bound which can be returned from this method to
1169                // be the next possible prefix, if any.
1170                uncalculated_lower_bound = cached_path.next_without_prefix();
1171
1172                continue
1173            }
1174
1175            // Determine the next nibble of the branch which has not yet been constructed, and
1176            // determine the child's full path.
1177            let child_nibble = next_child_nibbles.trailing_zeros() as u8;
1178            let child_path = self.child_path_at(child_nibble);
1179
1180            // If the previous child was a cached branch with a short key (extension), then the new
1181            // uncalculated_lower_bound will be the increment of that branch's path. If there are
1182            // any dirty leaves between that path and this child, it indicates there may be leaves
1183            // which would split that extension node. In that case we return the range to process
1184            // the leaves.
1185            if uncalculated_lower_bound_ref < &child_path &&
1186                self.prefix_set.contains_range(uncalculated_lower_bound_ref..&child_path)
1187            {
1188                self.cached_branch_stack.push((cached_path, cached_branch));
1189                return Ok(Some((*uncalculated_lower_bound_ref, Some(child_path))));
1190            }
1191
1192            // If the `hash_mask` bit is set for the next child it means the child's hash is cached
1193            // in the `cached_branch`. We can use that instead of re-calculating the hash of the
1194            // entire sub-trie.
1195            //
1196            // If the child needs to be retained for a proof then we should not use the cached
1197            // hash, and instead continue on to calculate its node manually.
1198            //
1199            // If the child's path is in the prefix set then the cached hash is stale and must
1200            // not be used.
1201            if cached_branch.hash_mask.is_bit_set(child_nibble) &&
1202                !self.prefix_set.contains(&child_path)
1203            {
1204                // Commit the last child. We do this here for two reasons:
1205                // - `commit_last_child` will check if the last child needs to be retained. We need
1206                //   to check that before the subsequent `should_retain` call here to prevent
1207                //   `targets` from being moved beyond the last child before it is checked.
1208                // - If we do end up using the cached hash value, then we will need to commit the
1209                //   last child before pushing a new one onto the stack anyway.
1210                self.commit_last_child(targets)?;
1211
1212                if !self.should_retain(targets, &child_path, false) {
1213                    // Pull this child's hash out of the cached branch node. The hash index
1214                    // is the number of hash_mask bits set below this child's nibble.
1215                    let lower_bits = TrieMask::new((1u16 << child_nibble) - 1);
1216                    let hash_idx = (cached_branch.hash_mask & lower_bits).count_ones() as usize;
1217                    let hash = cached_branch.hashes[hash_idx];
1218
1219                    trace!(
1220                        target: TRACE_TARGET,
1221                        ?child_path,
1222                        ?hash_idx,
1223                        ?hash,
1224                        "Using cached hash for child",
1225                    );
1226
1227                    self.child_stack.push(ProofTrieBranchChild::RlpNode(RlpNode::word_rlp(&hash)));
1228                    self.branch_stack
1229                        .last_mut()
1230                        .expect("already asserted there is a last branch")
1231                        .state_mask
1232                        .set_bit(child_nibble);
1233
1234                    // Update the `uncalculated_lower_bound` to indicate that the child whose bit
1235                    // was just set is completely processed.
1236                    uncalculated_lower_bound = child_path.next_without_prefix();
1237
1238                    // Push the current cached branch back onto the stack before looping.
1239                    self.cached_branch_stack.push((cached_path, cached_branch));
1240
1241                    continue
1242                }
1243            }
1244
1245            // We now want to check if there is a cached branch node at this child. The cached
1246            // branch node may be the node at this child directly, or this child may be an
1247            // extension and the cached branch is the child of that extension.
1248
1249            // All trie nodes prior to `child_path` will not be modified further, so we can seek the
1250            // trie cursor to the next cached node at-or-after `child_path`.
1251            if trie_cursor_state.path().is_some_and(|path| path < &child_path) {
1252                trace!(target: TRACE_TARGET, ?child_path, "Seeking trie cursor to child path");
1253                *trie_cursor_state =
1254                    TrieCursorState::seeked(child_path, self.trie_cursor_seek(child_path)?);
1255            }
1256
1257            // If the next cached branch node is a child of `child_path` then we can assume it is
1258            // the cached branch for this child. We push it onto the `cached_branch_stack` and loop
1259            // back to the top.
1260            if let TrieCursorState::Available(next_cached_path, next_cached_branch) =
1261                &trie_cursor_state &&
1262                next_cached_path.starts_with(&child_path)
1263            {
1264                // Push the current cached branch back on before pushing its child and then looping
1265                self.cached_branch_stack.push((cached_path, cached_branch));
1266
1267                // If the next cached branch's path is in the prefix set, it could indicate that
1268                // there are dirty leaves which would split the cached branch's extension node (if
1269                // there is one). In that case we return the range those leaves would potentially be
1270                // in to calculate them.
1271                if self.prefix_set.contains(&child_path) {
1272                    let gap_upper = Some(*next_cached_path);
1273                    self.cached_branch_stack.push(trie_cursor_state.take());
1274                    return Ok(Some((*uncalculated_lower_bound_ref, gap_upper)));
1275                }
1276
1277                trace!(
1278                    target: TRACE_TARGET,
1279                    ?child_path,
1280                    ?next_cached_path,
1281                    ?next_cached_branch,
1282                    "Pushing cached branch for child",
1283                );
1284                self.cached_branch_stack.push(trie_cursor_state.take());
1285                continue;
1286            }
1287
1288            // There is no cached data for the sub-trie at this child, we must recalculate the
1289            // sub-trie root (this child) using the leaves. Return the range of keys based on the
1290            // child path.
1291            let child_path_upper = child_path.next_without_prefix();
1292            trace!(
1293                target: TRACE_TARGET,
1294                lower=?child_path,
1295                upper=?child_path_upper,
1296                "Returning sub-trie's key range to calculate",
1297            );
1298
1299            // Push the current cached branch back onto the stack before returning.
1300            self.cached_branch_stack.push((cached_path, cached_branch));
1301
1302            return Ok(Some((child_path, child_path_upper)));
1303        }
1304    }
1305
1306    /// Calculates trie nodes and retains proofs for targeted nodes within a sub-trie. The
1307    /// sub-trie's bounds are denoted by the `lower_bound` and `upper_bound` arguments,
1308    /// `upper_bound` is exclusive, None indicates unbounded.
1309    #[instrument(
1310        target = TRACE_TARGET,
1311        level = "trace",
1312        skip_all,
1313        fields(
1314            parent_prefix=?sub_trie_targets.parent_prefix,
1315            lower_bound=?sub_trie_targets.lower_bound,
1316            upper_bound=?sub_trie_targets.upper_bound,
1317        ),
1318    )]
1319    fn proof_subtrie<'a>(
1320        &mut self,
1321        value_encoder: &mut VE,
1322        trie_cursor_state: &mut TrieCursorState,
1323        hashed_cursor_state: &mut HashedCursorState<VE::DeferredEncoder>,
1324        sub_trie_targets: SubTrieTargets<'a>,
1325    ) -> Result<(), StateProofError> {
1326        let traversal_lower_bound = sub_trie_targets.lower_bound;
1327        let traversal_upper_bound = sub_trie_targets.upper_bound;
1328
1329        // Wrap targets into a `TargetsCursor`.  targets can be empty if we only want to calculate
1330        // the root, in which case we don't need a cursor.
1331        let mut targets = if sub_trie_targets.targets.is_empty() {
1332            None
1333        } else {
1334            Some(TargetsCursor::new(sub_trie_targets.targets))
1335        };
1336
1337        // Ensure initial state is cleared. By the end of the method call these should be empty once
1338        // again.
1339        debug_assert!(self.cached_branch_stack.is_empty());
1340        debug_assert!(self.branch_stack.is_empty());
1341        debug_assert!(self.branch_path.is_empty());
1342        debug_assert!(self.child_stack.is_empty());
1343
1344        // `next_uncached_key_range`, which will be called in the loop below, expects the trie
1345        // cursor to have already been positioned. Cursor resets for overlapping sub-tries are
1346        // handled by `proof_inner`, so a buffered entry at-or-after this disjoint range remains the
1347        // first unconsumed entry. Exhaustion is similarly stable across forward-only ranges.
1348        if trie_cursor_state.needs_seek_to(&traversal_lower_bound) {
1349            trace!(target: TRACE_TARGET, "Doing initial seek of trie cursor");
1350            *trie_cursor_state = TrieCursorState::seeked(
1351                traversal_lower_bound,
1352                self.trie_cursor_seek(traversal_lower_bound)?,
1353            );
1354        }
1355
1356        // `uncalculated_lower_bound` tracks the lower bound of node paths which have yet to be
1357        // visited, either via the hashed key cursor (`calculate_key_range`) or trie cursor
1358        // (`next_uncached_key_range`). If/when this becomes None then there are no further nodes
1359        // which could exist.
1360        let mut uncalculated_lower_bound = Some(traversal_lower_bound);
1361
1362        trace!(target: TRACE_TARGET, "Starting loop");
1363        loop {
1364            // Save the previous lower bound to detect forward progress.
1365            let prev_uncalculated_lower_bound = uncalculated_lower_bound;
1366
1367            // Determine the range of keys of the overall trie which need to be re-computed.
1368            let Some((calc_lower_bound, calc_upper_bound)) = self.next_uncached_key_range(
1369                &mut targets,
1370                trie_cursor_state,
1371                traversal_upper_bound.as_ref(),
1372                prev_uncalculated_lower_bound,
1373            )?
1374            else {
1375                // If `next_uncached_key_range` determines that there can be no more keys then
1376                // complete the computation.
1377                break;
1378            };
1379
1380            // Forward-progress guard: detect trie inconsistencies that would cause infinite loops.
1381            // If `next_uncached_key_range` returns a range that starts before the previous
1382            // lower bound, we've gone backwards and would loop forever.
1383            //
1384            // This can specifically happen when there is a cached branch which shouldn't exist, or
1385            // if state mask bit is set on a cached branch which shouldn't be.
1386            if let Some(prev_lower) = prev_uncalculated_lower_bound.as_ref() &&
1387                calc_lower_bound < *prev_lower
1388            {
1389                let msg = format!(
1390                    "next_uncached_key_range went backwards: calc_lower={calc_lower_bound:?} < \
1391                     prev_lower={prev_lower:?}, calc_upper={calc_upper_bound:?}, \
1392                     lower_bound={traversal_lower_bound:?}, \
1393                     upper_bound={traversal_upper_bound:?}",
1394                );
1395                error!(target: TRACE_TARGET, "{msg}");
1396                return Err(StateProofError::TrieInconsistency(msg));
1397            }
1398
1399            // Calculate the trie for that range of keys
1400            self.calculate_key_range(
1401                value_encoder,
1402                &mut targets,
1403                hashed_cursor_state,
1404                calc_lower_bound,
1405                calc_upper_bound,
1406            )?;
1407
1408            // Once outside `calculate_key_range`, `hashed_cursor_state` will be at the first key
1409            // after the range, or exhausted.
1410            //
1411            // If the hashed cursor is exhausted, or has reached the end of the traversal range,
1412            // then there are no more keys which can contribute to these target children.
1413            if hashed_cursor_state.path().is_none_or(|key| {
1414                traversal_upper_bound.is_some_and(|upper_bound| key >= &upper_bound)
1415            }) {
1416                break;
1417            }
1418
1419            // The upper bound of previous calculation becomes the lower bound of the uncalculated
1420            // range, for which we'll once again check for cached data.
1421            uncalculated_lower_bound = calc_upper_bound;
1422        }
1423
1424        // Once there's no more leaves we can pop the remaining branches, if any.
1425        trace!(target: TRACE_TARGET, "Exited loop, popping remaining branches");
1426        while !self.branch_stack.is_empty() {
1427            self.pop_branch(&mut targets)?;
1428        }
1429
1430        // At this point the branch stack should be empty. If the child stack is empty it means no
1431        // keys were ever iterated from the hashed cursor in the first place. Otherwise there should
1432        // only be a single node left: the root node.
1433        debug_assert!(self.branch_stack.is_empty());
1434        debug_assert!(self.branch_path.is_empty());
1435        debug_assert!(self.child_stack.len() < 2);
1436
1437        // The `cached_branch_stack` may still have cached branches on it, as it's not affected by
1438        // `pop_branch`, but it is no longer needed and should be cleared.
1439        self.cached_branch_stack.clear();
1440
1441        // We always pop the local root node off of the `child_stack` in order to empty it. If the
1442        // parent branch is already known, compressed roots need to be rebased into a direct child
1443        // of that parent before they can be attached to it.
1444        trace!(
1445            target: TRACE_TARGET,
1446            parent_prefix = ?sub_trie_targets.parent_prefix,
1447            child_stack_empty = self.child_stack.is_empty(),
1448            "Maybe retaining local root",
1449        );
1450        // Either there was only a single leaf node placed on the child stack, or the final branch
1451        // was popped off the branch stack and placed unencoded on the child stack. Either way the
1452        // child stack will not have an RlpNode at this point.
1453        let root_node = match self.child_stack.pop() {
1454            Some(ProofTrieBranchChild::RlpNode(_)) => {
1455                unreachable!("local root cannot be an encoded RLP node")
1456            }
1457            root_node => root_node,
1458        };
1459
1460        // A full-trie calculation always retains a root, using an empty root when traversal
1461        // produced no root node.
1462        let Some(parent_prefix) = sub_trie_targets.parent_prefix else {
1463            let root_node = if let Some(root_node) = root_node {
1464                self.rlp_encode_buf.clear();
1465                root_node.into_proof_trie_node(Nibbles::new(), &mut self.rlp_encode_buf)?
1466            } else {
1467                ProofTrieNodeV2::empty()
1468            };
1469            self.retained_proofs.push(root_node);
1470            return Ok(())
1471        };
1472
1473        // If there's no root node then the subtrie has no keys, return nothing.
1474        let Some(mut root_node) = root_node else { return Ok(()) };
1475
1476        let root_short_key = *root_node.short_key();
1477
1478        // An exact match reconstructed the already-revealed parent; its targeted children were
1479        // retained while that parent branch was popped.
1480        if root_short_key == parent_prefix {
1481            return Ok(())
1482        }
1483
1484        // At this point we have a "root" node which the calculator has based at 0x (empty path),
1485        // but the subtrie targets indicate that there is a known parent branch at parent_prefix
1486        // which this root should be rebased onto.
1487
1488        // The local root of a partial calculation must be at or below its known parent.
1489        if !root_short_key.starts_with(&parent_prefix) {
1490            return Err(StateProofError::TrieInconsistency(format!(
1491                "local root short key {root_short_key:?} does not start with parent prefix \
1492                 {parent_prefix:?}",
1493            )))
1494        }
1495
1496        // Keep the parent branch's child nibble in the proof path so the local root attaches
1497        // directly below that parent.
1498        let child_path_len = parent_prefix.len() + 1;
1499        let child_path = root_short_key.slice_unchecked(0, child_path_len);
1500
1501        // It's possible that the local root lies on a child which is not targeted.
1502        if !sub_trie_targets
1503            .targets
1504            .iter()
1505            .any(|target| target.key_nibbles.starts_with(&child_path))
1506        {
1507            return Ok(())
1508        }
1509
1510        // Retain the requested child with only the path below its parent edge in the short key.
1511        root_node.trim_short_key_prefix(child_path_len);
1512        self.rlp_encode_buf.clear();
1513        let root_node = root_node.into_proof_trie_node(child_path, &mut self.rlp_encode_buf)?;
1514        self.retained_proofs.push(root_node);
1515
1516        Ok(())
1517    }
1518
1519    /// Clears internal computation state. Called after errors to ensure the calculator is not
1520    /// left in a partially-computed state when reused.
1521    fn clear_computation_state(&mut self) {
1522        self.branch_stack.clear();
1523        self.branch_path = Nibbles::new();
1524        self.child_stack.clear();
1525        self.cached_branch_stack.clear();
1526        self.retained_proofs.clear();
1527    }
1528
1529    /// Internal implementation of proof calculation. Assumes both cursors have already been reset.
1530    /// See docs on [`Self::proof`] for expected behavior.
1531    fn proof_inner(
1532        &mut self,
1533        value_encoder: &mut VE,
1534        targets: &mut [ProofV2Target],
1535    ) -> Result<Vec<ProofTrieNodeV2>, StateProofError> {
1536        // If there are no targets then nothing could be returned, return early.
1537        if targets.is_empty() {
1538            trace!(target: TRACE_TARGET, "Empty targets, returning");
1539            return Ok(Vec::new())
1540        }
1541
1542        // Initialize the variables which track the state of the two cursors. Both indicate the
1543        // cursors are unseeked.
1544        let mut trie_cursor_state = TrieCursorState::unseeked();
1545        let mut hashed_cursor_state = HashedCursorState::unseeked();
1546        let mut previous_traversal_bounds: Option<(Nibbles, Option<Nibbles>)> = None;
1547
1548        // Divide targets into bounded ranges, each corresponding to the direct children of one
1549        // already-revealed parent, and handle all proofs within that range.
1550        for sub_trie_targets in iter_sub_trie_targets(targets) {
1551            let traversal_lower_bound = sub_trie_targets.lower_bound;
1552            let traversal_upper_bound = sub_trie_targets.upper_bound;
1553            if previous_traversal_bounds.is_some_and(|(_, previous_upper_bound)| {
1554                previous_upper_bound.is_none_or(|upper_bound| upper_bound > traversal_lower_bound)
1555            }) {
1556                if trie_cursor_state.needs_reset_before_seek(&traversal_lower_bound) {
1557                    trace!(
1558                        target: TRACE_TARGET,
1559                        ?previous_traversal_bounds,
1560                        ?traversal_lower_bound,
1561                        ?traversal_upper_bound,
1562                        "Resetting trie cursor before overlapping or backward traversal range",
1563                    );
1564                    self.trie_cursor.reset();
1565                    trie_cursor_state = TrieCursorState::unseeked();
1566                }
1567                if hashed_cursor_state.needs_reset_before_seek(&traversal_lower_bound) {
1568                    trace!(
1569                        target: TRACE_TARGET,
1570                        ?previous_traversal_bounds,
1571                        ?traversal_lower_bound,
1572                        ?traversal_upper_bound,
1573                        "Resetting hashed cursor before overlapping or backward traversal range",
1574                    );
1575                    self.hashed_cursor.reset();
1576                    hashed_cursor_state = HashedCursorState::unseeked();
1577                }
1578            }
1579
1580            if let Err(err) = self.proof_subtrie(
1581                value_encoder,
1582                &mut trie_cursor_state,
1583                &mut hashed_cursor_state,
1584                sub_trie_targets,
1585            ) {
1586                self.clear_computation_state();
1587                return Err(err);
1588            }
1589
1590            previous_traversal_bounds = Some((traversal_lower_bound, traversal_upper_bound));
1591        }
1592
1593        trace!(
1594            target: TRACE_TARGET,
1595            retained_proofs_len = ?self.retained_proofs.len(),
1596            "proof_inner: returning",
1597        );
1598        self.retained_proofs.sort_unstable_by(|a, b| depth_first::cmp(&a.path, &b.path));
1599        self.retained_proofs.dedup_by(|a, b| a.path == b.path);
1600        Ok(core::mem::take(&mut self.retained_proofs))
1601    }
1602
1603    /// Generate a proof for the given targets.
1604    ///
1605    /// Given a set of [`ProofV2Target`]s, returns nodes whose paths are a prefix of any target. The
1606    /// returned nodes will be sorted depth-first by path.
1607    ///
1608    /// # Panics
1609    ///
1610    /// In debug builds, panics if the targets are not sorted lexicographically.
1611    #[instrument(target = TRACE_TARGET, level = "trace", skip_all)]
1612    pub fn proof(
1613        &mut self,
1614        value_encoder: &mut VE,
1615        targets: &mut [ProofV2Target],
1616    ) -> Result<Vec<ProofTrieNodeV2>, StateProofError> {
1617        self.trie_cursor.reset();
1618        self.hashed_cursor.reset();
1619        self.proof_inner(value_encoder, targets)
1620    }
1621
1622    /// Computes the root hash from a set of proof nodes.
1623    ///
1624    /// Returns `None` if there is no root node (partial proof), otherwise returns the hash of the
1625    /// root node.
1626    ///
1627    /// This method reuses the internal RLP encode buffer for efficiency.
1628    pub fn compute_root_hash(
1629        &mut self,
1630        proof_nodes: &[ProofTrieNodeV2],
1631    ) -> Result<Option<B256>, StateProofError> {
1632        // Find the root node (node at empty path)
1633        let root_node = proof_nodes.iter().find(|node| node.path.is_empty());
1634
1635        let Some(root) = root_node else {
1636            return Ok(None);
1637        };
1638
1639        // Compute the hash of the root node
1640        self.rlp_encode_buf.clear();
1641        root.node.encode(&mut self.rlp_encode_buf);
1642        let root_hash = keccak256(&self.rlp_encode_buf);
1643
1644        Ok(Some(root_hash))
1645    }
1646
1647    /// Calculates the root node of the trie.
1648    ///
1649    /// This method does not accept targets nor retain proofs. Returns the root node which can
1650    /// be used to compute the root hash via [`Self::compute_root_hash`].
1651    #[instrument(target = TRACE_TARGET, level = "trace", skip(self, value_encoder))]
1652    pub fn root_node(
1653        &mut self,
1654        value_encoder: &mut VE,
1655    ) -> Result<ProofTrieNodeV2, StateProofError> {
1656        // Initialize the variables which track the state of the two cursors. Both indicate the
1657        // cursors are unseeked.
1658        let mut trie_cursor_state = TrieCursorState::unseeked();
1659        let mut hashed_cursor_state = HashedCursorState::unseeked();
1660
1661        static EMPTY_TARGETS: [ProofV2Target; 0] = [];
1662        let sub_trie_targets = SubTrieTargets {
1663            lower_bound: Nibbles::new(),
1664            upper_bound: None,
1665            parent_prefix: None,
1666            targets: &EMPTY_TARGETS,
1667        };
1668
1669        if let Err(err) = self.proof_subtrie(
1670            value_encoder,
1671            &mut trie_cursor_state,
1672            &mut hashed_cursor_state,
1673            sub_trie_targets,
1674        ) {
1675            self.clear_computation_state();
1676            return Err(err);
1677        }
1678
1679        // `proof_subtrie` retains the root node when there is no known parent, regardless of
1680        // whether there are any targets.
1681        let mut proofs = core::mem::take(&mut self.retained_proofs);
1682        trace!(
1683            target: TRACE_TARGET,
1684            proofs_len = ?proofs.len(),
1685            "root_node: extracting root",
1686        );
1687
1688        // The root node is at the empty path. Since there is no parent and targets is empty, there
1689        // should be no other retained proofs.
1690        debug_assert_eq!(
1691            proofs.len(), 1,
1692            "prefix is empty, parent path is None, and targets is empty, so there must be only the root node"
1693        );
1694
1695        // Find and remove the root node (node at empty path)
1696        let root_node = proofs.pop().expect("prefix is empty, parent path is None, and targets is empty, so there must be only the root node");
1697
1698        Ok(root_node)
1699    }
1700}
1701
1702/// A proof calculator for storage tries.
1703pub type StorageProofCalculator<TC, HC> = ProofCalculator<TC, HC, StorageValueEncoder>;
1704
1705impl<TC, HC> StorageProofCalculator<TC, HC>
1706where
1707    TC: TrieStorageCursor,
1708    HC: HashedStorageCursor<Value = U256>,
1709{
1710    /// Create a new [`StorageProofCalculator`] instance.
1711    pub fn new_storage(trie_cursor: TC, hashed_cursor: HC) -> Self {
1712        Self::new(trie_cursor, hashed_cursor)
1713    }
1714
1715    /// Generate a proof for a storage trie at the given hashed address.
1716    ///
1717    /// Given a set of [`ProofV2Target`]s, returns nodes whose paths are a prefix of any target. The
1718    /// returned nodes will be sorted depth-first by path.
1719    ///
1720    /// # Panics
1721    ///
1722    /// In debug builds, panics if the targets are not sorted lexicographically.
1723    #[instrument(target = TRACE_TARGET, level = "trace", skip(self, targets))]
1724    pub fn storage_proof(
1725        &mut self,
1726        hashed_address: B256,
1727        targets: &mut [ProofV2Target],
1728    ) -> Result<Vec<ProofTrieNodeV2>, StateProofError> {
1729        self.hashed_cursor.set_hashed_address(hashed_address);
1730
1731        // Shortcut: check if storage is empty
1732        if self.hashed_cursor.is_storage_empty()? {
1733            return Ok(if targets.iter().any(|target| !target.parent.is_known()) {
1734                vec![ProofTrieNodeV2 {
1735                    path: Nibbles::default(),
1736                    node: TrieNodeV2::EmptyRoot,
1737                    masks: None,
1738                }]
1739            } else {
1740                Vec::new()
1741            })
1742        }
1743
1744        // Don't call `set_hashed_address` on the trie cursor until after the previous shortcut has
1745        // been checked.
1746        self.trie_cursor.set_hashed_address(hashed_address);
1747
1748        // Create a mutable storage value encoder
1749        let mut storage_value_encoder = StorageValueEncoder;
1750        self.proof_inner(&mut storage_value_encoder, targets)
1751    }
1752
1753    /// Calculates the root node of a storage trie.
1754    ///
1755    /// This method does not accept targets nor retain proofs. Returns the root node which can
1756    /// be used to compute the root hash via [`Self::compute_root_hash`].
1757    #[instrument(target = TRACE_TARGET, level = "trace", skip(self))]
1758    pub fn storage_root_node(
1759        &mut self,
1760        hashed_address: B256,
1761    ) -> Result<ProofTrieNodeV2, StateProofError> {
1762        self.hashed_cursor.set_hashed_address(hashed_address);
1763
1764        if self.hashed_cursor.is_storage_empty()? {
1765            return Ok(ProofTrieNodeV2 {
1766                path: Nibbles::default(),
1767                node: TrieNodeV2::EmptyRoot,
1768                masks: None,
1769            })
1770        }
1771
1772        // Don't call `set_hashed_address` on the trie cursor until after the previous shortcut has
1773        // been checked.
1774        self.trie_cursor.set_hashed_address(hashed_address);
1775
1776        // Create a mutable storage value encoder
1777        let mut storage_value_encoder = StorageValueEncoder;
1778        self.root_node(&mut storage_value_encoder)
1779    }
1780}
1781
1782/// Helper type wrapping a slice of [`ProofV2Target`]s, primarily used to iterate through targets in
1783/// [`ProofCalculator::should_retain`].
1784///
1785/// It is assumed that the underlying slice is never empty, and that the iterator is never
1786/// exhausted.
1787struct TargetsCursor<'a> {
1788    targets: &'a [ProofV2Target],
1789    i: usize,
1790}
1791
1792impl<'a> TargetsCursor<'a> {
1793    /// Wraps a slice of [`ProofV2Target`]s with the `TargetsCursor`.
1794    ///
1795    /// # Panics
1796    ///
1797    /// Will panic in debug mode if called with an empty slice.
1798    fn new(targets: &'a [ProofV2Target]) -> Self {
1799        debug_assert!(!targets.is_empty());
1800        Self { targets, i: 0 }
1801    }
1802
1803    /// Returns the current and next [`ProofV2Target`] that the cursor is pointed at.
1804    fn current(&self) -> (&'a ProofV2Target, Option<&'a ProofV2Target>) {
1805        (&self.targets[self.i], self.targets.get(self.i + 1))
1806    }
1807
1808    /// Iterates the cursor forward.
1809    ///
1810    /// # Panics
1811    ///
1812    /// Will panic if the cursor is exhausted.
1813    fn next(&mut self) -> (&'a ProofV2Target, Option<&'a ProofV2Target>) {
1814        self.i += 1;
1815        debug_assert!(self.i < self.targets.len());
1816        self.current()
1817    }
1818
1819    // Iterate forwards over the slice, starting from the [`ProofV2Target`] after the current.
1820    fn skip_iter(&self) -> impl Iterator<Item = &'a ProofV2Target> {
1821        self.targets[self.i + 1..].iter()
1822    }
1823
1824    /// Iterated backwards over the slice, starting from the [`ProofV2Target`] previous to the
1825    /// current.
1826    fn rev_iter(&self) -> impl Iterator<Item = &'a ProofV2Target> {
1827        self.targets[..self.i].iter().rev()
1828    }
1829}
1830
1831/// Used to track the state of the trie cursor, allowing us to differentiate between a branch having
1832/// been taken (used as a cached branch) and the cursor having been exhausted.
1833#[derive(Debug)]
1834enum TrieCursorState {
1835    /// The initial state of the cursor, indicating it's never been seeked.
1836    Unseeked,
1837    /// Cursor is seeked to this path and the node has not been used yet.
1838    Available(Nibbles, BranchNodeCompact),
1839    /// Cursor is seeked to this path, but the node has been used.
1840    Taken(Nibbles),
1841    /// Cursor has been exhausted after seeking from the given lower bound.
1842    Exhausted(Nibbles),
1843}
1844
1845impl TrieCursorState {
1846    /// Creates a [`Self::Unseeked`] based on an entry returned from the cursor itself.
1847    const fn unseeked() -> Self {
1848        Self::Unseeked
1849    }
1850
1851    /// Creates a [`Self`] based on an entry returned from the cursor itself.
1852    fn seeked(key: Nibbles, entry: Option<(Nibbles, BranchNodeCompact)>) -> Self {
1853        entry.map_or(Self::Exhausted(key), |(path, node)| Self::Available(path, node))
1854    }
1855
1856    /// Returns the path the cursor is seeked to, or None if it's exhausted.
1857    ///
1858    /// # Panics
1859    ///
1860    /// Panics if the cursor is unseeked.
1861    const fn path(&self) -> Option<&Nibbles> {
1862        match self {
1863            Self::Unseeked => panic!("cursor is unseeked"),
1864            Self::Available(path, _) | Self::Taken(path) => Some(path),
1865            Self::Exhausted(_) => None,
1866        }
1867    }
1868
1869    /// Returns true if the cursor must seek to be usable for a range starting at `path`.
1870    fn needs_seek_to(&self, path: &Nibbles) -> bool {
1871        match self {
1872            Self::Unseeked | Self::Taken(_) => true,
1873            Self::Available(current_path, _) => current_path < path,
1874            Self::Exhausted(_) => false,
1875        }
1876    }
1877
1878    /// Returns true if seeking to `key` requires resetting the forward-only cursor.
1879    fn needs_reset_before_seek(&self, key: &Nibbles) -> bool {
1880        match self {
1881            Self::Unseeked => false,
1882            Self::Available(path, _) | Self::Taken(path) => path > key,
1883            Self::Exhausted(exhausted_at) => exhausted_at > key,
1884        }
1885    }
1886
1887    /// Takes the path and node from a [`Self::Available`]. Panics if not [`Self::Available`].
1888    fn take(&mut self) -> (Nibbles, BranchNodeCompact) {
1889        let Self::Available(path, _) = self else {
1890            panic!("take called on non-Available: {self:?}")
1891        };
1892
1893        let path = *path;
1894        let Self::Available(path, node) = core::mem::replace(self, Self::Taken(path)) else {
1895            unreachable!("already checked that self is Self::Available");
1896        };
1897
1898        (path, node)
1899    }
1900}
1901
1902/// Used to track the state of the hashed cursor, including the path that established exhaustion.
1903enum HashedCursorState<V> {
1904    /// The initial state of the cursor, indicating it's never been seeked.
1905    Unseeked,
1906    /// Cursor is seeked to this path and the value has not been used yet.
1907    Available(Nibbles, V),
1908    /// Cursor has been exhausted at or after the given path.
1909    Exhausted(Nibbles),
1910}
1911
1912impl<V> HashedCursorState<V> {
1913    /// Creates a [`Self::Unseeked`] state.
1914    const fn unseeked() -> Self {
1915        Self::Unseeked
1916    }
1917
1918    /// Creates a [`Self`] based on an entry returned from the cursor itself.
1919    fn seeked(key: Nibbles, entry: Option<(Nibbles, V)>) -> Self {
1920        entry.map_or(Self::Exhausted(key), |(path, value)| Self::Available(path, value))
1921    }
1922
1923    /// Returns the path the cursor is seeked to, or None if it's unseeked or exhausted.
1924    const fn path(&self) -> Option<&Nibbles> {
1925        match self {
1926            Self::Available(path, _) => Some(path),
1927            Self::Unseeked | Self::Exhausted(_) => None,
1928        }
1929    }
1930
1931    /// Returns true if the cursor must seek to be usable for a range starting at `key`.
1932    fn needs_seek_to(&self, key: &Nibbles) -> bool {
1933        match self {
1934            Self::Unseeked => true,
1935            Self::Available(path, _) => path < key,
1936            Self::Exhausted(exhausted_at) => exhausted_at > key,
1937        }
1938    }
1939
1940    /// Returns true if seeking to `key` requires resetting the forward-only cursor.
1941    fn needs_reset_before_seek(&self, key: &Nibbles) -> bool {
1942        match self {
1943            Self::Unseeked => false,
1944            Self::Available(path, _) => path > key,
1945            Self::Exhausted(exhausted_at) => exhausted_at > key,
1946        }
1947    }
1948
1949    /// Takes the path and value from a [`Self::Available`]. Panics if not [`Self::Available`].
1950    fn take(&mut self) -> (Nibbles, V) {
1951        match core::mem::replace(self, Self::Unseeked) {
1952            Self::Available(path, value) => (path, value),
1953            _ => panic!("take called on non-Available hashed cursor state"),
1954        }
1955    }
1956}
1957
1958/// Describes the state of the currently cached branch node (if any).
1959enum PopCachedBranchOutcome {
1960    /// Cached branch has been popped from the `cached_branch_stack` and is ready to be used.
1961    Popped((Nibbles, BranchNodeCompact)),
1962    /// All cached branches have been exhausted.
1963    Exhausted,
1964    /// Need to calculate leaves from this range (exclusive upper) before the cached branch
1965    /// (catch-up range). If None then
1966    CalculateLeaves((Nibbles, Option<Nibbles>)),
1967}
1968
1969#[cfg(test)]
1970mod tests {
1971    use super::*;
1972    use crate::{
1973        hashed_cursor::{mock::MockHashedCursorFactory, HashedCursorFactory},
1974        proof::StorageProof as LegacyStorageProof,
1975        test_utils::TrieTestHarness,
1976        trie_cursor::{depth_first, TrieCursorFactory},
1977    };
1978    use alloy_primitives::map::B256Set;
1979    use alloy_rlp::Decodable;
1980    use alloy_trie::proof::AddedRemovedKeys;
1981    use itertools::Itertools;
1982    use reth_trie_common::{
1983        prefix_set::PrefixSetMut, ProofTrieNode, ProofV2TargetParent, TrieNode, EMPTY_ROOT_HASH,
1984    };
1985    use std::collections::BTreeMap;
1986
1987    /// Converts legacy proofs to V2 proofs by combining extension nodes with their child branch
1988    /// nodes.
1989    ///
1990    /// In the legacy proof format, extension nodes and branch nodes are separate. In the V2 format,
1991    /// they are combined into a single `BranchNodeV2` where the extension's key becomes the
1992    /// branch's `key` field.
1993    ///
1994    /// Converts legacy proofs (sorted in depth-first order) to V2 format.
1995    ///
1996    /// In depth-first order, children come BEFORE parents. So when we encounter an extension node,
1997    /// its child branch has already been processed and is in the result. We need to pop it and
1998    /// combine it with the extension.
1999    fn convert_legacy_proofs_to_v2(legacy_proofs: &[ProofTrieNode]) -> Vec<ProofTrieNodeV2> {
2000        ProofTrieNodeV2::from_sorted_trie_nodes(
2001            legacy_proofs.iter().map(|p| (p.path, p.node.clone(), p.masks)),
2002        )
2003    }
2004
2005    /// Projects a legacy proof node into the representation requested by a V2 target.
2006    fn project_legacy_proof_node(
2007        node: &ProofTrieNodeV2,
2008        target: &ProofV2Target,
2009    ) -> Option<ProofTrieNodeV2> {
2010        let Some(parent_path_len) = target.parent.path_len() else {
2011            return target.key_nibbles.starts_with(&node.path).then(|| node.clone())
2012        };
2013
2014        if node.path.len() > parent_path_len {
2015            return target.key_nibbles.starts_with(&node.path).then(|| node.clone())
2016        }
2017
2018        let logical_path = match &node.node {
2019            TrieNodeV2::Leaf(leaf) => node.path.join(&leaf.key),
2020            TrieNodeV2::Branch(branch) => node.path.join(&branch.key),
2021            TrieNodeV2::EmptyRoot | TrieNodeV2::Extension(_) => return None,
2022        };
2023        let child_path_len = parent_path_len + 1;
2024        if logical_path.len() < child_path_len {
2025            return None
2026        }
2027
2028        let child_path = logical_path.slice(0..child_path_len);
2029        if !target.key_nibbles.starts_with(&child_path) {
2030            return None
2031        }
2032
2033        let trim_len = child_path_len - node.path.len();
2034        let mut projected = node.clone();
2035        projected.path = child_path;
2036        match &mut projected.node {
2037            TrieNodeV2::Leaf(leaf) => leaf.key = leaf.key.slice(trim_len..),
2038            TrieNodeV2::Branch(branch) => {
2039                branch.key = branch.key.slice(trim_len..);
2040                if branch.key.is_empty() {
2041                    branch.branch_rlp_node = None;
2042                }
2043            }
2044            TrieNodeV2::EmptyRoot | TrieNodeV2::Extension(_) => unreachable!(),
2045        }
2046        Some(projected)
2047    }
2048
2049    /// Builds the exact V2 representation expected for a legacy proof and set of targets.
2050    fn project_legacy_proof(
2051        legacy_nodes: &[ProofTrieNodeV2],
2052        targets: &[ProofV2Target],
2053    ) -> Vec<ProofTrieNodeV2> {
2054        let mut projected = targets
2055            .iter()
2056            .flat_map(|target| {
2057                legacy_nodes.iter().filter_map(move |node| project_legacy_proof_node(node, target))
2058            })
2059            .collect::<Vec<_>>();
2060        projected.sort_unstable_by(|a, b| depth_first::cmp(&a.path, &b.path));
2061        projected.dedup_by(|a, b| {
2062            if a.path != b.path {
2063                return false
2064            }
2065            assert_eq!(a, b, "target projections disagree at path {:?}", a.path);
2066            true
2067        });
2068        projected
2069    }
2070
2071    /// A test harness for comparing `StorageProofCalculator` and legacy `StorageProof`
2072    /// implementations.
2073    ///
2074    /// Wraps [`TrieTestHarness`] and adds a method to test that both proof implementations
2075    /// produce equivalent results for storage proofs.
2076    struct ProofTestHarness {
2077        inner: TrieTestHarness,
2078    }
2079
2080    impl std::ops::Deref for ProofTestHarness {
2081        type Target = TrieTestHarness;
2082        fn deref(&self) -> &Self::Target {
2083            &self.inner
2084        }
2085    }
2086
2087    impl ProofTestHarness {
2088        /// Creates a new test harness from a map of hashed storage slots to values.
2089        fn new(storage: BTreeMap<B256, U256>) -> Self {
2090            Self { inner: TrieTestHarness::new(storage) }
2091        }
2092
2093        /// Asserts that `StorageProofCalculator` and legacy `StorageProof` produce equivalent
2094        /// results for storage proofs.
2095        fn assert_proof(
2096            &self,
2097            targets: impl IntoIterator<Item = ProofV2Target>,
2098        ) -> Result<(), StateProofError> {
2099            let mut targets_vec = targets.into_iter().collect::<Vec<_>>();
2100
2101            // Get v2 proof and root hash via harness
2102            let (proof_v2_result, root_hash) = self.proof_v2(&mut targets_vec);
2103
2104            // Verify the root hash matches the expected root (if the proof contains a root
2105            // node)
2106            if let Some(root_hash) = root_hash {
2107                pretty_assertions::assert_eq!(self.original_root(), root_hash);
2108            }
2109
2110            // Fully materialize the legacy proof so compressed branches can be projected across
2111            // arbitrary parent boundaries, including absence targets that diverge inside them.
2112            let legacy_targets = targets_vec
2113                .iter()
2114                .map(|target| B256::from_slice(&target.key_nibbles.pack()))
2115                .chain(self.storage().keys().copied())
2116                .collect::<B256Set>();
2117
2118            // Call legacy StorageProof::storage_multiproof
2119            let proof_legacy_result = LegacyStorageProof::new_hashed(
2120                self.trie_cursor_factory(),
2121                self.hashed_cursor_factory(),
2122                self.hashed_address(),
2123            )
2124            .with_branch_node_masks(true)
2125            .with_added_removed_keys(Some(AddedRemovedKeys::default().with_assume_added(true)))
2126            .storage_multiproof(legacy_targets)?;
2127
2128            // Decode and sort legacy proof nodes
2129            let proof_legacy_nodes = proof_legacy_result
2130                .subtree
2131                .iter()
2132                .map(|(path, node_enc)| {
2133                    let mut buf = node_enc.as_ref();
2134                    let node = TrieNode::decode(&mut buf)
2135                        .expect("legacy implementation should not produce malformed proof nodes");
2136
2137                    let masks = if path.is_empty() {
2138                        None
2139                    } else {
2140                        proof_legacy_result.branch_node_masks.get(path).copied()
2141                    };
2142
2143                    ProofTrieNode { path: *path, node, masks }
2144                })
2145                .sorted_by(|a, b| depth_first::cmp(&a.path, &b.path))
2146                .collect::<Vec<_>>();
2147
2148            // Convert legacy proofs to V2 proofs by combining extensions with their child branches
2149            let all_legacy_nodes_v2 = convert_legacy_proofs_to_v2(&proof_legacy_nodes);
2150
2151            let expected_v2 = project_legacy_proof(&all_legacy_nodes_v2, &targets_vec);
2152            pretty_assertions::assert_eq!(expected_v2, proof_v2_result);
2153
2154            Ok(())
2155        }
2156    }
2157
2158    /// Tests that `clear_computation_state` properly resets internal stacks, allowing a
2159    /// `StorageProofCalculator` to be reused after a mid-computation error left stale state.
2160    /// Before the fix, stale data in `branch_stack`, `child_stack`, and `branch_path`
2161    /// could cause a `usize` underflow panic in `pop_branch`.
2162    #[test]
2163    fn test_proof_calculator_reuse_after_error() {
2164        reth_tracing::init_test_tracing();
2165
2166        let slots = [
2167            B256::right_padding_from(&[0x10]),
2168            B256::right_padding_from(&[0x20]),
2169            B256::right_padding_from(&[0x30]),
2170            B256::right_padding_from(&[0x40]),
2171        ];
2172        let storage: BTreeMap<B256, U256> =
2173            slots.iter().map(|&s| (s, U256::from(100u64))).collect();
2174
2175        let harness = ProofTestHarness::new(storage);
2176
2177        let trie_cursor_factory = harness.trie_cursor_factory();
2178        let hashed_cursor_factory = harness.hashed_cursor_factory();
2179
2180        let hashed_address = harness.hashed_address();
2181        let trie_cursor = trie_cursor_factory.storage_trie_cursor(hashed_address).unwrap();
2182        let hashed_cursor = hashed_cursor_factory.hashed_storage_cursor(hashed_address).unwrap();
2183        let mut proof_calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor);
2184
2185        // Simulate stale state left by a mid-computation error: push fake entries onto internal
2186        // stacks and set a non-empty branch_path.
2187        proof_calculator.branch_stack.push(ProofTrieBranch {
2188            ext_len: 2,
2189            state_mask: TrieMask::new(0b1111),
2190            masks: None,
2191        });
2192        proof_calculator.branch_stack.push(ProofTrieBranch {
2193            ext_len: 0,
2194            state_mask: TrieMask::new(0b11),
2195            masks: None,
2196        });
2197        proof_calculator
2198            .child_stack
2199            .push(ProofTrieBranchChild::RlpNode(RlpNode::word_rlp(&B256::ZERO)));
2200        proof_calculator.branch_path = Nibbles::from_nibbles([0x1, 0x2, 0x3]);
2201
2202        // clear_computation_state should reset everything so a subsequent call works.
2203        proof_calculator.clear_computation_state();
2204
2205        let mut sorted_slots = slots.to_vec();
2206        sorted_slots.sort();
2207        let mut targets: Vec<ProofV2Target> =
2208            sorted_slots.iter().copied().map(ProofV2Target::new).collect();
2209
2210        let result = proof_calculator.storage_proof(hashed_address, &mut targets).unwrap();
2211
2212        // Compare against a fresh calculator to verify correctness.
2213        let trie_cursor = trie_cursor_factory.storage_trie_cursor(hashed_address).unwrap();
2214        let hashed_cursor = hashed_cursor_factory.hashed_storage_cursor(hashed_address).unwrap();
2215        let mut fresh_calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor);
2216        let fresh_result = fresh_calculator.storage_proof(hashed_address, &mut targets).unwrap();
2217
2218        pretty_assertions::assert_eq!(fresh_result, result);
2219    }
2220
2221    #[test]
2222    fn test_partial_storage_proof_after_root_calculation() {
2223        let slot_a = B256::right_padding_from(&[0xae, 0xd4, 0x00]);
2224        let slot_b = B256::right_padding_from(&[0xae, 0xd4, 0x10]);
2225        let harness = ProofTestHarness::new(BTreeMap::from([
2226            (slot_a, U256::from(1)),
2227            (slot_b, U256::from(2)),
2228        ]));
2229        let hashed_address = harness.hashed_address();
2230        let trie_cursor =
2231            harness.trie_cursor_factory().storage_trie_cursor(hashed_address).unwrap();
2232        let hashed_cursor =
2233            harness.hashed_cursor_factory().hashed_storage_cursor(hashed_address).unwrap();
2234        let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor);
2235
2236        let root_node = calculator.storage_root_node(hashed_address).unwrap();
2237        assert_eq!(
2238            calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap(),
2239            Some(harness.original_root())
2240        );
2241
2242        let target = ProofV2Target::new(slot_a).with_parent(ProofV2TargetParent::new(3));
2243        let mut actual_targets = [target];
2244        let actual = calculator.storage_proof(hashed_address, &mut actual_targets).unwrap();
2245        let mut expected_targets = [target];
2246        let (expected, root) = harness.proof_v2(&mut expected_targets);
2247
2248        assert!(root.is_none());
2249        pretty_assertions::assert_eq!(expected, actual);
2250    }
2251
2252    mod proptest_tests {
2253        use super::*;
2254        use proptest::prelude::*;
2255
2256        /// Generate a strategy for storage datasets (hashed slot → value).
2257        fn storage_strategy() -> impl Strategy<Value = BTreeMap<B256, U256>> {
2258            prop::collection::vec((any::<[u8; 32]>(), any::<u64>()), 0..=100).prop_map(|slots| {
2259                slots
2260                    .into_iter()
2261                    .map(|(slot_bytes, value)| (B256::from(slot_bytes), U256::from(value)))
2262                    .filter(|(_, v)| *v != U256::ZERO)
2263                    .collect()
2264            })
2265        }
2266
2267        /// Generate a strategy for proof targets that are 80% from existing storage slots
2268        /// and 20% random keys. Each target has a random parent path length of `None` or 0..15.
2269        fn proof_targets_strategy(
2270            slot_keys: Vec<B256>,
2271        ) -> impl Strategy<Value = Vec<ProofV2Target>> {
2272            let num_slots = slot_keys.len();
2273
2274            let target_count = 0..=(num_slots + 5);
2275
2276            target_count.prop_flat_map(move |count| {
2277                let slot_keys = slot_keys.clone();
2278                prop::collection::vec(
2279                    (
2280                        prop::bool::weighted(0.8).prop_flat_map(move |from_slots| {
2281                            if from_slots && !slot_keys.is_empty() {
2282                                prop::sample::select(slot_keys.clone()).boxed()
2283                            } else {
2284                                any::<[u8; 32]>().prop_map(B256::from).boxed()
2285                            }
2286                        }),
2287                        0u8..16u8,
2288                    )
2289                        .prop_map(|(key, encoded_parent_path_len)| {
2290                            let parent = encoded_parent_path_len.checked_sub(1).map_or(
2291                                ProofV2TargetParent::NONE,
2292                                |parent_path_len| {
2293                                    ProofV2TargetParent::new(usize::from(parent_path_len))
2294                                },
2295                            );
2296                            ProofV2Target::new(key).with_parent(parent)
2297                        }),
2298                    count,
2299                )
2300            })
2301        }
2302
2303        proptest! {
2304            #![proptest_config(ProptestConfig::with_cases(4000))]
2305            #[test]
2306            /// Tests that `StorageProofCalculator` produces valid proofs for randomly generated
2307            /// storage datasets with proof targets.
2308            fn proptest_proof_with_targets(
2309                (storage, targets) in storage_strategy()
2310                    .prop_flat_map(|storage| {
2311                        let mut slot_keys: Vec<B256> = storage.keys().copied().collect();
2312                        slot_keys.sort_unstable();
2313                        let targets_strategy = proof_targets_strategy(slot_keys);
2314                        (Just(storage), targets_strategy)
2315                    })
2316            ) {
2317                reth_tracing::init_test_tracing();
2318                let harness = ProofTestHarness::new(storage);
2319
2320                harness.assert_proof(targets).expect("Proof generation failed");
2321            }
2322        }
2323    }
2324
2325    #[test]
2326    fn test_exact_subtrie_targets_with_root_target() {
2327        reth_tracing::init_test_tracing();
2328
2329        let slot_80 = B256::right_padding_from(&[0x80]);
2330        let slot_82 = B256::right_padding_from(&[0x82]);
2331        let slot_f0 = B256::right_padding_from(&[0xf0]);
2332        let storage = BTreeMap::from([
2333            (slot_80, U256::from(1)),
2334            (slot_82, U256::from(2)),
2335            (slot_f0, U256::from(3)),
2336        ]);
2337        let targets = [
2338            ProofV2Target::new(B256::ZERO),
2339            ProofV2Target::new(slot_80).with_parent(ProofV2TargetParent::new(1)),
2340        ];
2341
2342        let harness = ProofTestHarness::new(storage);
2343        harness.assert_proof(targets).expect("Proof generation failed");
2344    }
2345
2346    #[test]
2347    fn test_rebases_singleton_subtrie_root_below_known_parent() {
2348        let slot = B256::right_padding_from(&[0xae, 0xd4, 0x09]);
2349        let slot_nibbles = Nibbles::unpack(slot);
2350        let harness = ProofTestHarness::new(BTreeMap::from([(slot, U256::from(1))]));
2351        let mut targets = [ProofV2Target::new(slot).with_parent(ProofV2TargetParent::new(3))];
2352
2353        let (proof, root) = harness.proof_v2(&mut targets);
2354
2355        assert!(root.is_none());
2356        assert_eq!(proof.len(), 1);
2357        assert_eq!(proof[0].path, slot_nibbles.slice(0..4));
2358        let TrieNodeV2::Leaf(leaf) = &proof[0].node else {
2359            panic!("singleton subtrie root should remain a leaf")
2360        };
2361        assert_eq!(leaf.key, slot_nibbles.slice(4..));
2362    }
2363
2364    #[test]
2365    fn test_rebases_singleton_leaf_at_max_parent_depth() {
2366        let slot = B256::repeat_byte(0xae);
2367        let slot_nibbles = Nibbles::unpack(slot);
2368        let harness = ProofTestHarness::new(BTreeMap::from([(slot, U256::from(1))]));
2369        let mut targets = [ProofV2Target::new(slot).with_parent(ProofV2TargetParent::new(63))];
2370
2371        let (proof, root) = harness.proof_v2(&mut targets);
2372
2373        assert!(root.is_none());
2374        assert_eq!(proof.len(), 1);
2375        assert_eq!(proof[0].path, slot_nibbles);
2376        let TrieNodeV2::Leaf(leaf) = &proof[0].node else {
2377            panic!("singleton subtrie root should remain a leaf")
2378        };
2379        assert!(leaf.key.is_empty());
2380    }
2381
2382    #[test]
2383    fn test_root_and_root_parent_targets_retain_both_singleton_representations() {
2384        let slot = B256::right_padding_from(&[0x20]);
2385        let slot_nibbles = Nibbles::unpack(slot);
2386        let harness = ProofTestHarness::new(BTreeMap::from([(slot, U256::from(1))]));
2387        let mut targets = [
2388            ProofV2Target::new(slot),
2389            ProofV2Target::new(slot).with_parent(ProofV2TargetParent::new(0)),
2390        ];
2391
2392        let (proof, root) = harness.proof_v2(&mut targets);
2393
2394        assert_eq!(root, Some(harness.original_root()));
2395        let root_node = proof.iter().find(|node| node.path.is_empty()).expect("root proof");
2396        let TrieNodeV2::Leaf(root_leaf) = &root_node.node else { panic!("root should be a leaf") };
2397        assert_eq!(root_leaf.key, slot_nibbles);
2398
2399        let child_path = slot_nibbles.slice(0..1);
2400        let child_node =
2401            proof.iter().find(|node| node.path == child_path).expect("rebased root child proof");
2402        let TrieNodeV2::Leaf(child_leaf) = &child_node.node else {
2403            panic!("root child should be a leaf")
2404        };
2405        assert_eq!(child_leaf.key, slot_nibbles.slice(1..));
2406    }
2407
2408    #[test]
2409    fn test_rebases_compressed_branch_subtrie_root() {
2410        let slot_a = B256::right_padding_from(&[0xae, 0xd4, 0x00]);
2411        let slot_b = B256::right_padding_from(&[0xae, 0xd4, 0x10]);
2412        let slot_nibbles = Nibbles::unpack(slot_a);
2413        let harness = ProofTestHarness::new(BTreeMap::from([
2414            (slot_a, U256::from(1)),
2415            (slot_b, U256::from(2)),
2416        ]));
2417        let mut targets = [ProofV2Target::new(slot_a).with_parent(ProofV2TargetParent::new(3))];
2418
2419        let (proof, root) = harness.proof_v2(&mut targets);
2420
2421        assert!(root.is_none());
2422        let branch_path = slot_nibbles.slice(0..4);
2423        let branch_node =
2424            proof.iter().find(|node| node.path == branch_path).expect("rebased compressed branch");
2425        let TrieNodeV2::Branch(branch) = &branch_node.node else {
2426            panic!("rebased node should be a branch")
2427        };
2428        assert!(branch.key.is_empty());
2429        assert!(branch.branch_rlp_node.is_none());
2430    }
2431
2432    #[test]
2433    fn test_discards_reconstructed_known_parent_branch() {
2434        let slot_a = B256::right_padding_from(&[0xae, 0xd2]);
2435        let slot_b = B256::right_padding_from(&[0xae, 0xd4]);
2436        let slot_nibbles = Nibbles::unpack(slot_a);
2437        let harness = ProofTestHarness::new(BTreeMap::from([
2438            (slot_a, U256::from(1)),
2439            (slot_b, U256::from(2)),
2440        ]));
2441        let mut targets = [ProofV2Target::new(slot_a).with_parent(ProofV2TargetParent::new(3))];
2442
2443        let (proof, root) = harness.proof_v2(&mut targets);
2444
2445        assert!(root.is_none());
2446        assert!(!proof.iter().any(|node| node.path == slot_nibbles.slice(0..3)));
2447        assert!(proof.iter().any(|node| node.path == slot_nibbles.slice(0..4)));
2448    }
2449
2450    #[test]
2451    fn test_rebased_root_matches_direct_child_not_full_short_key() {
2452        let stored_slot = B256::right_padding_from(&[0xae, 0xd4, 0x09]);
2453        let same_child_target = B256::right_padding_from(&[0xae, 0xd4, 0xff]);
2454        let other_child_target = B256::right_padding_from(&[0xae, 0xd5]);
2455        let harness = ProofTestHarness::new(BTreeMap::from([(stored_slot, U256::from(1))]));
2456
2457        let mut same_child =
2458            [ProofV2Target::new(same_child_target).with_parent(ProofV2TargetParent::new(3))];
2459        let (proof, _) = harness.proof_v2(&mut same_child);
2460        assert_eq!(proof.len(), 1, "divergent leaf proves absence below the same child");
2461
2462        let mut other_child =
2463            [ProofV2Target::new(other_child_target).with_parent(ProofV2TargetParent::new(3))];
2464        let (proof, _) = harness.proof_v2(&mut other_child);
2465        assert!(proof.is_empty(), "a different direct child is unrelated to the target");
2466    }
2467
2468    #[test]
2469    fn test_known_parent_sibling_span_retains_only_target_children() {
2470        let stored_slot_a = B256::right_padding_from(&[0xea, 0x53]);
2471        let stored_slot_b = B256::right_padding_from(&[0xeb, 0x53]);
2472        let stored_slot_c = B256::right_padding_from(&[0xec, 0x53]);
2473        let target_a = B256::right_padding_from(&[0xea, 0x1f]);
2474        let target_c = B256::right_padding_from(&[0xec, 0x1f]);
2475        let harness = ProofTestHarness::new(BTreeMap::from([
2476            (stored_slot_a, U256::from(1)),
2477            (stored_slot_b, U256::from(2)),
2478            (stored_slot_c, U256::from(3)),
2479        ]));
2480        let mut targets = [target_a, target_c]
2481            .map(|target| ProofV2Target::new(target).with_parent(ProofV2TargetParent::new(1)));
2482
2483        let (proof, root) = harness.proof_v2(&mut targets);
2484
2485        assert!(root.is_none());
2486        assert_eq!(
2487            proof.iter().map(|node| node.path).collect::<Vec<_>>(),
2488            [Nibbles::from_nibbles([0xe, 0xa]), Nibbles::from_nibbles([0xe, 0xc])]
2489        );
2490    }
2491
2492    #[test]
2493    fn test_known_parent_does_not_use_stale_parent_mask() {
2494        let stored_slot_a = B256::right_padding_from(&[0xea, 0x53]);
2495        let stored_slot = B256::right_padding_from(&[0xeb, 0x53]);
2496        let stored_slot_c = B256::right_padding_from(&[0xec, 0x53]);
2497        let target = B256::right_padding_from(&[0xeb, 0x1f]);
2498        let stored_slot_nibbles = Nibbles::unpack(stored_slot);
2499
2500        // The known parent at `e` is supplied by the sparse trie and may be stale in the database
2501        // when partial persistence masks that path. In particular, its state mask can omit the
2502        // live `eb` child while hashed state already contains that child's leaf.
2503        let stale_parent_mask = TrieMask::new((1 << 0xa) | (1 << 0xc));
2504        let stale_parent = BranchNodeCompact::new(
2505            stale_parent_mask,
2506            TrieMask::new(0),
2507            TrieMask::new(0),
2508            Vec::new(),
2509            None,
2510        );
2511        let storage_nodes = BTreeMap::from([(Nibbles::from_nibbles([0xe]), stale_parent)]);
2512
2513        let mut harness = TrieTestHarness::new(BTreeMap::from([
2514            (stored_slot_a, U256::from(1)),
2515            (stored_slot, U256::from(2)),
2516            (stored_slot_c, U256::from(3)),
2517        ]));
2518        harness.set_trie_nodes(storage_nodes);
2519
2520        let mut targets = [ProofV2Target::new(target).with_parent(ProofV2TargetParent::new(1))];
2521        let (proof, root) = harness.proof_v2(&mut targets);
2522
2523        assert!(root.is_none());
2524        assert_eq!(proof.len(), 1);
2525        assert_eq!(proof[0].path, stored_slot_nibbles.slice(0..2));
2526        let TrieNodeV2::Leaf(leaf) = &proof[0].node else {
2527            panic!("live direct child should be reconstructed as a leaf")
2528        };
2529        assert_eq!(leaf.key, stored_slot_nibbles.slice(2..));
2530    }
2531
2532    #[test]
2533    fn test_empty_storage_respects_parent_context() {
2534        let harness = ProofTestHarness::new(BTreeMap::new());
2535        let slot = B256::ZERO;
2536
2537        let mut partial_target =
2538            [ProofV2Target::new(slot).with_parent(ProofV2TargetParent::new(0))];
2539        let (partial_proof, partial_root) = harness.proof_v2(&mut partial_target);
2540        assert!(partial_proof.is_empty());
2541        assert!(partial_root.is_none());
2542
2543        let mut root_target = [ProofV2Target::new(slot)];
2544        let (root_proof, root) = harness.proof_v2(&mut root_target);
2545        assert_eq!(root_proof.len(), 1);
2546        assert!(matches!(root_proof[0].node, TrieNodeV2::EmptyRoot));
2547        assert_eq!(root, Some(EMPTY_ROOT_HASH));
2548    }
2549
2550    #[test]
2551    fn test_big_trie() {
2552        use rand::prelude::*;
2553
2554        reth_tracing::init_test_tracing();
2555        let mut rng = rand::rngs::SmallRng::seed_from_u64(1);
2556
2557        let mut rand_b256 = || {
2558            let mut buf: [u8; 32] = [0; 32];
2559            rng.fill_bytes(&mut buf);
2560            B256::from_slice(&buf)
2561        };
2562
2563        // Generate random storage dataset.
2564        let mut storage = BTreeMap::new();
2565        for _ in 0..10240 {
2566            let hashed_slot = rand_b256();
2567            storage.insert(hashed_slot, U256::from(1u64));
2568        }
2569
2570        // Collect targets; partially from real keys, partially random keys which probably won't
2571        // exist.
2572        let mut targets = storage.keys().copied().collect::<Vec<_>>();
2573        for _ in 0..storage.len() / 5 {
2574            targets.push(rand_b256());
2575        }
2576        targets.sort();
2577
2578        // Create test harness
2579        let harness = ProofTestHarness::new(storage);
2580
2581        harness
2582            .assert_proof(targets.into_iter().map(ProofV2Target::new))
2583            .expect("Proof generation failed");
2584    }
2585
2586    #[test]
2587    fn test_node_with_masked_empty_child() {
2588        reth_tracing::init_test_tracing();
2589
2590        let val = U256::from(42u64);
2591
2592        // All storage keys share a common first nibble (0x6), so the branch is at path 0x6. The
2593        // second nibble differentiates children: 0,1,3,5,7.
2594        let slot_60 = B256::right_padding_from(&[0x60]);
2595        let slot_61 = B256::right_padding_from(&[0x61]);
2596        let slot_65 = B256::right_padding_from(&[0x65]);
2597        let slot_67 = B256::right_padding_from(&[0x67]);
2598
2599        // Construct a branch node at path 0x6 with state_mask bits 0,1,3,5,7.
2600        // hash_mask has bits 0,1,5,7 (NOT 3) — nibble 3's hash is cleared because it's in the
2601        // prefix set. Hashes are dummy values.
2602        let state_mask = TrieMask::new(0b10101011); // bits 0,1,3,5,7
2603        let hash_mask = TrieMask::new(0b10100011); // bits 0,1,5,7 (NOT 3)
2604        let hashes = vec![B256::repeat_byte(0xaa); hash_mask.count_ones() as usize];
2605        let branch = BranchNodeCompact::new(state_mask, TrieMask::new(0), hash_mask, hashes, None);
2606
2607        let storage_nodes: BTreeMap<Nibbles, BranchNodeCompact> =
2608            std::iter::once((Nibbles::from_nibbles([0x6]), branch)).collect();
2609
2610        // Hashed cursor has slots at children 0, 1, 5, 7 — but NOT child 3 (0x63).
2611        // This simulates the post-state overlay having deleted the slot at 0x63.
2612        let mut harness = TrieTestHarness::new(
2613            [slot_60, slot_61, slot_65, slot_67].iter().map(|s| (*s, val)).collect(),
2614        );
2615        harness.set_trie_nodes(storage_nodes);
2616
2617        let storage_trie_cursor =
2618            harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2619        let hashed_storage_cursor = harness
2620            .hashed_cursor_factory()
2621            .hashed_storage_cursor(harness.hashed_address())
2622            .unwrap();
2623        let mut calculator =
2624            StorageProofCalculator::new_storage(storage_trie_cursor, hashed_storage_cursor);
2625        let root_node = calculator
2626            .storage_root_node(harness.hashed_address())
2627            .expect("storage_root_node should succeed with masked empty child");
2628
2629        let root_hash = calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap();
2630        assert!(root_hash.is_some(), "should produce a root hash");
2631    }
2632
2633    /// Tests that `root_node` handles the case where `uncalculated_lower_bound` has advanced
2634    /// entirely past a cached branch that still has unprocessed children in its `state_mask`.
2635    ///
2636    /// Branch at `0x6` has `state_mask` bits 0,1,5,f where nibble 5 has its `hash_mask`
2637    /// cleared and no leaf data. The last child (nibble f)
2638    /// causes `calculate_key_range` to be called with range `(0x6f, Some(0x7))`. After that range,
2639    /// the hashed cursor still has keys (at `0x70...`), so `proof_subtrie` does not break and
2640    /// re-enters `next_uncached_key_range` with `uncalculated_lower_bound = Some(0x7)`.
2641    /// Since `0x7` is past `0x6`, all remaining children are skipped and the branch is popped.
2642    #[test]
2643    fn test_node_with_masked_empty_child_lower_bound_past_branch() {
2644        reth_tracing::init_test_tracing();
2645
2646        let val = U256::from(42u64);
2647
2648        // Leaf keys under 0x6 and one beyond (0x70) to keep the cursor alive after 0x6.
2649        let slot_60 = B256::right_padding_from(&[0x60]);
2650        let slot_61 = B256::right_padding_from(&[0x61]);
2651        let slot_6f = B256::right_padding_from(&[0x6f]);
2652        let slot_70 = B256::right_padding_from(&[0x70]);
2653
2654        // Branch at 0x6: state_mask bits 0,1,5,f; hash_mask bits 0,1 (NOT 5, NOT f).
2655        // Nibble 5 has state_mask set but no hash and no leaf data (masked empty child).
2656        // Nibble f has state_mask set, no hash, but DOES have leaf data.
2657        let state_mask = TrieMask::new(0b1000_0000_0010_0011); // bits 0,1,5,f
2658        let hash_mask = TrieMask::new(0b0000_0000_0000_0011); // bits 0,1
2659        let hashes = vec![B256::repeat_byte(0xaa); hash_mask.count_ones() as usize];
2660        let branch = BranchNodeCompact::new(state_mask, TrieMask::new(0), hash_mask, hashes, None);
2661
2662        let storage_nodes: BTreeMap<Nibbles, BranchNodeCompact> =
2663            std::iter::once((Nibbles::from_nibbles([0x6]), branch)).collect();
2664
2665        // Hashed cursor: slots at 0x60, 0x61, 0x6f, 0x70 — but NOT 0x65.
2666        let mut harness = TrieTestHarness::new(
2667            [slot_60, slot_61, slot_6f, slot_70].iter().map(|s| (*s, val)).collect(),
2668        );
2669        harness.set_trie_nodes(storage_nodes);
2670
2671        let storage_trie_cursor =
2672            harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2673        let hashed_storage_cursor = harness
2674            .hashed_cursor_factory()
2675            .hashed_storage_cursor(harness.hashed_address())
2676            .unwrap();
2677        let mut calculator =
2678            StorageProofCalculator::new_storage(storage_trie_cursor, hashed_storage_cursor);
2679        let root_node = calculator
2680            .storage_root_node(harness.hashed_address())
2681            .expect("storage_root_node should succeed when lower bound advances past branch");
2682
2683        let root_hash = calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap();
2684        assert!(root_hash.is_some(), "should produce a root hash");
2685    }
2686
2687    /// Tests that the prefix set causes `next_uncached_key_range` to add child nibbles that are
2688    /// not present in the cached branch's `state_mask`.
2689    ///
2690    /// Setup: An original state with leaves at `0x60` and `0x61` produces a cached branch at
2691    /// `0x6` with children at nibbles 0 and 1 (both with real cached hashes from `StorageRoot`).
2692    /// A new leaf is then inserted at `0x63...`, which is NOT in the branch's `state_mask`.
2693    /// The prefix set contains the new key. Without prefix set support, the calculator would
2694    /// skip nibble 3 entirely and produce a stale root hash. With prefix set support, nibble 3
2695    /// is discovered and its subtrie is recalculated from leaves.
2696    #[test]
2697    fn test_prefix_set_adds_child_nibbles() {
2698        reth_tracing::init_test_tracing();
2699
2700        let val = U256::from(42u64);
2701        let slot_60 = B256::right_padding_from(&[0x60]);
2702        let slot_61 = B256::right_padding_from(&[0x61]);
2703        let slot_63 = B256::right_padding_from(&[0x63]);
2704
2705        let harness = TrieTestHarness::new([(slot_60, val), (slot_61, val)].into_iter().collect());
2706
2707        let changeset: BTreeMap<B256, U256> = std::iter::once((slot_63, val)).collect();
2708        let (expected_root, _) = harness.get_root_with_updates(&changeset);
2709
2710        let mut updated_storage = harness.storage().clone();
2711        updated_storage.insert(slot_63, val);
2712
2713        let updated_hashed = MockHashedCursorFactory::new(
2714            BTreeMap::new(),
2715            std::iter::once((harness.hashed_address(), updated_storage)).collect(),
2716        );
2717
2718        let mut prefix_set = PrefixSetMut::default();
2719        prefix_set.insert(Nibbles::unpack(slot_63));
2720
2721        let trie_cursor =
2722            harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2723        let hashed_cursor = updated_hashed.hashed_storage_cursor(harness.hashed_address()).unwrap();
2724        let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
2725            .with_prefix_set(prefix_set.freeze());
2726        let root_node = calculator
2727            .storage_root_node(harness.hashed_address())
2728            .expect("storage_root_node should succeed with prefix set adding child nibbles");
2729        let got_root =
2730            calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap().unwrap();
2731
2732        pretty_assertions::assert_eq!(
2733            expected_root,
2734            got_root,
2735            "Root hash with prefix set should match fresh computation"
2736        );
2737    }
2738
2739    /// Tests that `next_uncached_key_range` does not use a cached hash when the child's path
2740    /// is in the prefix set, forcing recalculation from leaves.
2741    ///
2742    /// Setup: A cached branch at `0x6` with children at nibbles 0,1,5 — all with cached hashes.
2743    /// The leaf at `0x65...` is changed (different value). The prefix set marks `0x65...` as
2744    /// dirty. Without prefix set support, the calculator would use the stale cached hash for
2745    /// nibble 5 and produce a wrong root. With prefix set support, the cached hash is skipped
2746    /// and the subtrie is recalculated from the updated leaf data.
2747    #[test]
2748    fn test_prefix_set_invalidates_cached_hash() {
2749        reth_tracing::init_test_tracing();
2750
2751        let original_val = U256::from(42u64);
2752        let updated_val = U256::from(9999u64);
2753        let slot_60 = B256::right_padding_from(&[0x60]);
2754        let slot_61 = B256::right_padding_from(&[0x61]);
2755        let slot_65 = B256::right_padding_from(&[0x65]);
2756
2757        let harness = TrieTestHarness::new(
2758            [(slot_60, original_val), (slot_61, original_val), (slot_65, original_val)]
2759                .into_iter()
2760                .collect(),
2761        );
2762
2763        let changeset: BTreeMap<B256, U256> = std::iter::once((slot_65, updated_val)).collect();
2764        let (expected_root, _) = harness.get_root_with_updates(&changeset);
2765
2766        let mut updated_storage = harness.storage().clone();
2767        updated_storage.insert(slot_65, updated_val);
2768
2769        let updated_hashed = MockHashedCursorFactory::new(
2770            BTreeMap::new(),
2771            std::iter::once((harness.hashed_address(), updated_storage)).collect(),
2772        );
2773
2774        let mut prefix_set = PrefixSetMut::default();
2775        prefix_set.insert(Nibbles::unpack(slot_65));
2776
2777        let trie_cursor =
2778            harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2779        let hashed_cursor = updated_hashed.hashed_storage_cursor(harness.hashed_address()).unwrap();
2780        let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
2781            .with_prefix_set(prefix_set.freeze());
2782        let root_node = calculator
2783            .storage_root_node(harness.hashed_address())
2784            .expect("storage_root_node should succeed with prefix set invalidating cached hash");
2785        let got_root =
2786            calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap().unwrap();
2787
2788        pretty_assertions::assert_eq!(
2789            expected_root,
2790            got_root,
2791            "Root hash with prefix set invalidation should match fresh computation"
2792        );
2793    }
2794
2795    /// Helper to compute the keccak256 hash of a storage leaf node. The `short_key` is the
2796    /// leaf's key after trimming all branch/extension nibbles consumed by ancestor nodes.
2797    fn storage_leaf_hash(short_key: &Nibbles, value: &U256) -> B256 {
2798        let mut buf = Vec::new();
2799        alloy_trie::nodes::LeafNodeRef::new(short_key, &alloy_rlp::encode_fixed_size(value))
2800            .encode(&mut buf);
2801        keccak256(&buf)
2802    }
2803
2804    /// Tests branch collapse when the removed child comes BEFORE the remaining child.
2805    ///
2806    /// Trie structure (3 hashed storage keys):
2807    ///   `key_a` = 0x20...  (root nibble 2, sub-nibble 0)
2808    ///   `key_b` = 0x21...  (root nibble 2, sub-nibble 1)
2809    ///   `key_c` = 0xb0...  (root nibble b)
2810    ///
2811    /// This creates:
2812    ///   root branch at nibbles {2, b}
2813    ///   sub-branch at path [2] at nibbles {0, 1}
2814    ///
2815    /// `key_a` is removed (prefix set marks it dirty, cursor has no value for it).
2816    /// The sub-branch at [2] collapses into its remaining child (`key_b`). The removed child
2817    /// (nibble 0) comes before the remaining child (nibble 1).
2818    #[test]
2819    fn test_branch_collapse_removed_child_before_remaining() {
2820        reth_tracing::init_test_tracing();
2821
2822        let val = U256::from(1u64);
2823
2824        let key_a = B256::right_padding_from(&[0x20]); // root nibble 2, sub-nibble 0
2825        let key_b = B256::right_padding_from(&[0x21]); // root nibble 2, sub-nibble 1
2826        let key_c = B256::right_padding_from(&[0xb0]); // root nibble b
2827
2828        // Compute leaf hashes for the sub-branch's children.
2829        // The sub-branch at path [2] consumes 2 nibbles from each key (root nibble + sub-nibble).
2830        let leaf_hash_a = storage_leaf_hash(&Nibbles::unpack(key_a).slice(2..), &val);
2831        let leaf_hash_b = storage_leaf_hash(&Nibbles::unpack(key_b).slice(2..), &val);
2832
2833        // Only cache the sub-branch at path [2] — the root will be built from leaves.
2834        // The sub-branch has children at nibbles 0 and 1, both with cached hashes.
2835        let sub_branch_state_mask = TrieMask::new((1 << 0) | (1 << 1));
2836        let cached_sub_branch = BranchNodeCompact::new(
2837            sub_branch_state_mask,
2838            TrieMask::new(0),
2839            sub_branch_state_mask,
2840            vec![leaf_hash_a, leaf_hash_b],
2841            None,
2842        );
2843
2844        let storage_nodes: BTreeMap<Nibbles, BranchNodeCompact> =
2845            std::iter::once((Nibbles::from_nibbles([0x2]), cached_sub_branch)).collect();
2846
2847        // The hashed cursor contains key_b and key_c (the root's other child). key_a was removed
2848        // (not in cursor)
2849        let mut harness = TrieTestHarness::new([(key_b, val), (key_c, val)].into_iter().collect());
2850        harness.set_trie_nodes(storage_nodes);
2851
2852        // Prefix set marks key_a as dirty (removed).
2853        let mut prefix_set_mut = PrefixSetMut::default();
2854        prefix_set_mut.insert(Nibbles::unpack(key_a));
2855        let prefix_set = prefix_set_mut.freeze();
2856
2857        // Compute root with cached branches + prefix set — triggers sub-branch collapse.
2858        let storage_trie_cursor =
2859            harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2860        let hashed_storage_cursor = harness
2861            .hashed_cursor_factory()
2862            .hashed_storage_cursor(harness.hashed_address())
2863            .unwrap();
2864        let mut calculator =
2865            StorageProofCalculator::new_storage(storage_trie_cursor, hashed_storage_cursor)
2866                .with_prefix_set(prefix_set);
2867        let root_node = calculator
2868            .storage_root_node(harness.hashed_address())
2869            .expect("storage_root_node should succeed after branch collapse");
2870        let root_with_collapse =
2871            calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap().unwrap();
2872
2873        // Compute reference root from scratch (no cached branches) using the full final state.
2874        let mut fresh_harness =
2875            TrieTestHarness::new([(key_b, val), (key_c, val)].into_iter().collect());
2876        fresh_harness.set_trie_nodes(BTreeMap::new());
2877        let storage_trie_cursor = fresh_harness
2878            .trie_cursor_factory()
2879            .storage_trie_cursor(fresh_harness.hashed_address())
2880            .unwrap();
2881        let hashed_storage_cursor = fresh_harness
2882            .hashed_cursor_factory()
2883            .hashed_storage_cursor(fresh_harness.hashed_address())
2884            .unwrap();
2885        let mut fresh_calculator =
2886            StorageProofCalculator::new_storage(storage_trie_cursor, hashed_storage_cursor);
2887        let fresh_root_node = fresh_calculator
2888            .storage_root_node(fresh_harness.hashed_address())
2889            .expect("fresh storage_root_node should succeed");
2890        let expected_root = fresh_calculator
2891            .compute_root_hash(core::slice::from_ref(&fresh_root_node))
2892            .unwrap()
2893            .unwrap();
2894
2895        pretty_assertions::assert_eq!(
2896            expected_root,
2897            root_with_collapse,
2898            "Root hash after collapsing branch (removed child before remaining) should match fresh computation"
2899        );
2900    }
2901
2902    /// Tests branch collapse when the removed child comes AFTER the remaining child.
2903    ///
2904    /// Same trie structure as "before" test, but with nibbles 4 and 9 instead of 0 and 1 for
2905    /// the sub-branch, and nibble 9 is removed. The removed child (nibble 9) comes after the
2906    /// remaining child (nibble 4).
2907    #[test]
2908    fn test_branch_collapse_removed_child_after_remaining() {
2909        reth_tracing::init_test_tracing();
2910
2911        let val = U256::from(1u64);
2912
2913        // key_a at sub-nibble 4, key_b at sub-nibble 9 (under root nibble 2).
2914        let key_a = B256::right_padding_from(&[0x24]); // root nibble 2, sub-nibble 4
2915        let key_b = B256::right_padding_from(&[0x29]); // root nibble 2, sub-nibble 9
2916        let key_c = B256::right_padding_from(&[0xb0]); // root nibble b
2917
2918        let leaf_hash_a = storage_leaf_hash(&Nibbles::unpack(key_a).slice(2..), &val);
2919        let leaf_hash_b = storage_leaf_hash(&Nibbles::unpack(key_b).slice(2..), &val);
2920
2921        // Only cache the sub-branch at path [2] — the root will be built from leaves.
2922        let sub_branch_state_mask = TrieMask::new((1 << 4) | (1 << 9));
2923        let cached_sub_branch = BranchNodeCompact::new(
2924            sub_branch_state_mask,
2925            TrieMask::new(0),
2926            sub_branch_state_mask,
2927            vec![leaf_hash_a, leaf_hash_b],
2928            None,
2929        );
2930
2931        let storage_nodes: BTreeMap<Nibbles, BranchNodeCompact> =
2932            std::iter::once((Nibbles::from_nibbles([0x2]), cached_sub_branch)).collect();
2933
2934        // The hashed cursor contains key_a and key_c. key_b was removed (not in cursor)
2935        let mut harness = TrieTestHarness::new([(key_a, val), (key_c, val)].into_iter().collect());
2936        harness.set_trie_nodes(storage_nodes);
2937
2938        // Prefix set marks key_b as dirty (removed).
2939        let mut prefix_set_mut = PrefixSetMut::default();
2940        prefix_set_mut.insert(Nibbles::unpack(key_b));
2941        let prefix_set = prefix_set_mut.freeze();
2942
2943        // Compute root with cached branches + prefix set — triggers sub-branch collapse.
2944        let storage_trie_cursor =
2945            harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
2946        let hashed_storage_cursor = harness
2947            .hashed_cursor_factory()
2948            .hashed_storage_cursor(harness.hashed_address())
2949            .unwrap();
2950        let mut calculator =
2951            StorageProofCalculator::new_storage(storage_trie_cursor, hashed_storage_cursor)
2952                .with_prefix_set(prefix_set);
2953        let root_node = calculator
2954            .storage_root_node(harness.hashed_address())
2955            .expect("storage_root_node should succeed after branch collapse");
2956        let root_with_collapse =
2957            calculator.compute_root_hash(core::slice::from_ref(&root_node)).unwrap().unwrap();
2958
2959        // Compute reference root from scratch (no cached branches) using the full final state.
2960        let mut fresh_harness =
2961            TrieTestHarness::new([(key_a, val), (key_c, val)].into_iter().collect());
2962        fresh_harness.set_trie_nodes(BTreeMap::new());
2963        let storage_trie_cursor = fresh_harness
2964            .trie_cursor_factory()
2965            .storage_trie_cursor(fresh_harness.hashed_address())
2966            .unwrap();
2967        let hashed_storage_cursor = fresh_harness
2968            .hashed_cursor_factory()
2969            .hashed_storage_cursor(fresh_harness.hashed_address())
2970            .unwrap();
2971        let mut fresh_calculator =
2972            StorageProofCalculator::new_storage(storage_trie_cursor, hashed_storage_cursor);
2973        let fresh_root_node = fresh_calculator
2974            .storage_root_node(fresh_harness.hashed_address())
2975            .expect("fresh storage_root_node should succeed");
2976        let expected_root = fresh_calculator
2977            .compute_root_hash(core::slice::from_ref(&fresh_root_node))
2978            .unwrap()
2979            .unwrap();
2980
2981        pretty_assertions::assert_eq!(
2982            expected_root,
2983            root_with_collapse,
2984            "Root hash after collapsing branch (removed child after remaining) should match fresh computation"
2985        );
2986    }
2987
2988    #[test]
2989    fn test_cached_branch_extension_skips_diverging_target() {
2990        reth_tracing::init_test_tracing();
2991
2992        let val = U256::from(100u64);
2993
2994        // Keys whose first bytes directly set the nibble paths we need.
2995        let key_a0 = B256::right_padding_from(&[0x6a, 0x30]); // nibbles: 6,a,3,0,...
2996        let key_a1 = B256::right_padding_from(&[0x6a, 0x31]); // nibbles: 6,a,3,1,...
2997        let key_c = B256::right_padding_from(&[0x6a, 0x80]); // nibbles: 6,a,8,0,...
2998        let key_d = B256::right_padding_from(&[0x6b, 0x00]); // nibbles: 6,b,0,0,...
2999        let key_e = B256::right_padding_from(&[0x6c, 0x00]); // nibbles: 6,c,0,0,...
3000
3001        // Build a correct trie from all five leaves to get the expected root and real hashes.
3002        let all_storage: BTreeMap<B256, U256> =
3003            [(key_a0, val), (key_a1, val), (key_c, val), (key_d, val), (key_e, val)]
3004                .into_iter()
3005                .collect();
3006        let correct_harness = TrieTestHarness::new(all_storage.clone());
3007        let expected_root = correct_harness.original_root();
3008
3009        // Compute leaf hashes for constructing manual cached branch nodes.
3010        let leaf_hash_a0 = storage_leaf_hash(&Nibbles::unpack(key_a0).slice(4..), &val);
3011        let leaf_hash_a1 = storage_leaf_hash(&Nibbles::unpack(key_a1).slice(4..), &val);
3012        let leaf_hash_d = storage_leaf_hash(&Nibbles::unpack(key_d).slice(2..), &val);
3013        let leaf_hash_e = storage_leaf_hash(&Nibbles::unpack(key_e).slice(2..), &val);
3014
3015        // ── Construct cached branch at [6] ─────────────────────────────────────
3016        // state_mask: bits a, b, and c set.
3017        // hash_mask:  bits b and c — both have cached leaf hashes.  Bit a has no hash, so the
3018        //             calculator will seek the trie cursor to find a deeper cached branch.
3019        //
3020        // Having three children with two (b, c) NOT in the prefix set ensures
3021        // `should_skip_cached_branch` does NOT skip this branch (num_unmatched >= 2).
3022        let branch_6_state_mask = TrieMask::new((1 << 0xa) | (1 << 0xb) | (1 << 0xc));
3023        let branch_6_hash_mask = TrieMask::new((1 << 0xb) | (1 << 0xc));
3024        let branch_6 = BranchNodeCompact::new(
3025            branch_6_state_mask,
3026            TrieMask::new(0),
3027            branch_6_hash_mask,
3028            vec![leaf_hash_d, leaf_hash_e],
3029            None,
3030        );
3031
3032        // ── Construct cached branch at [6,a,3] ────────────────────────────────
3033        // state_mask: bits 0 and 1 set (children key_a0 and key_a1).
3034        // hash_mask:  both bits set — both children have cached hashes.
3035        let branch_6a3_state_mask = TrieMask::new((1 << 0) | (1 << 1));
3036        let branch_6a3 = BranchNodeCompact::new(
3037            branch_6a3_state_mask,
3038            TrieMask::new(0),
3039            branch_6a3_state_mask,
3040            vec![leaf_hash_a0, leaf_hash_a1],
3041            None,
3042        );
3043
3044        // Intentionally omit the branch at [6,a] — this is the inconsistency.
3045        let inconsistent_nodes: BTreeMap<Nibbles, BranchNodeCompact> = [
3046            (Nibbles::from_nibbles([0x6]), branch_6),
3047            (Nibbles::from_nibbles([0x6, 0xa, 0x3]), branch_6a3),
3048        ]
3049        .into_iter()
3050        .collect();
3051
3052        // Create harness with all five leaves but the inconsistent trie nodes.
3053        let mut harness = TrieTestHarness::new(all_storage);
3054        harness.set_trie_nodes(inconsistent_nodes);
3055
3056        // Mark key_c as dirty — in the real scenario the leaf was touched by execution.
3057        // The prefix set contains only key_c's full path. `should_skip_cached_branch` will
3058        // NOT skip branch [6] because two of its three children (b, c) are not in the set
3059        // (num_unmatched = 2 > 1). It also will not skip branch [6,a,3] because
3060        // `contains([6,a,3])` is false (key_c's nibbles 6,a,8,... do not start with 6,a,3).
3061        let mut prefix_set = PrefixSetMut::default();
3062        prefix_set.insert(Nibbles::unpack(key_c));
3063
3064        // ── Verify root hash ───────────────────────────────────────────────────
3065        let trie_cursor =
3066            harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
3067        let hashed_cursor = harness
3068            .hashed_cursor_factory()
3069            .hashed_storage_cursor(harness.hashed_address())
3070            .unwrap();
3071        let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
3072            .with_prefix_set(prefix_set.freeze());
3073
3074        let root_node = calculator
3075            .storage_root_node(harness.hashed_address())
3076            .expect("storage_root_node should succeed");
3077        let got_root = calculator
3078            .compute_root_hash(core::slice::from_ref(&root_node))
3079            .unwrap()
3080            .expect("should produce a root hash");
3081
3082        // With the bug, the calculator skips key_c and produces a wrong root.
3083        pretty_assertions::assert_eq!(
3084            expected_root,
3085            got_root,
3086            "Root hash should match correct trie; cached extension must not skip diverging leaves"
3087        );
3088
3089        // ── Verify proof for key_c contains nodes on its path ──────────────────
3090        let mut targets = vec![ProofV2Target::new(key_c)];
3091        let proofs = calculator
3092            .storage_proof(harness.hashed_address(), &mut targets)
3093            .expect("storage_proof should succeed");
3094
3095        let key_c_nibbles = Nibbles::unpack(key_c);
3096        let has_matching_node = proofs.iter().any(|node| key_c_nibbles.starts_with(&node.path));
3097        assert!(
3098            has_matching_node,
3099            "Proof for key_c should contain at least one node on key_c's path, got: {proofs:?}"
3100        );
3101    }
3102
3103    #[test]
3104    fn test_cached_branch_extension_skips_diverging_target_before() {
3105        reth_tracing::init_test_tracing();
3106
3107        let val = U256::from(100u64);
3108
3109        // Keys whose first bytes directly set the nibble paths we need.
3110        let key_a0 = B256::right_padding_from(&[0x6a, 0x80]); // nibbles: 6,a,8,0,...
3111        let key_a1 = B256::right_padding_from(&[0x6a, 0x81]); // nibbles: 6,a,8,1,...
3112        let key_c = B256::right_padding_from(&[0x6a, 0x30]); // nibbles: 6,a,3,0,... (BEFORE [6,a,8])
3113        let key_d = B256::right_padding_from(&[0x6b, 0x00]); // nibbles: 6,b,0,0,...
3114        let key_e = B256::right_padding_from(&[0x6c, 0x00]); // nibbles: 6,c,0,0,...
3115
3116        // Build a correct trie from all five leaves to get the expected root and real hashes.
3117        let all_storage: BTreeMap<B256, U256> =
3118            [(key_a0, val), (key_a1, val), (key_c, val), (key_d, val), (key_e, val)]
3119                .into_iter()
3120                .collect();
3121        let correct_harness = TrieTestHarness::new(all_storage.clone());
3122        let expected_root = correct_harness.original_root();
3123
3124        // Compute leaf hashes for constructing manual cached branch nodes.
3125        let leaf_hash_a0 = storage_leaf_hash(&Nibbles::unpack(key_a0).slice(4..), &val);
3126        let leaf_hash_a1 = storage_leaf_hash(&Nibbles::unpack(key_a1).slice(4..), &val);
3127        let leaf_hash_d = storage_leaf_hash(&Nibbles::unpack(key_d).slice(2..), &val);
3128        let leaf_hash_e = storage_leaf_hash(&Nibbles::unpack(key_e).slice(2..), &val);
3129
3130        // ── Construct cached branch at [6] ─────────────────────────────────────
3131        // state_mask: bits a, b, and c set.
3132        // hash_mask:  bits b and c — both have cached leaf hashes.  Bit a has no hash, so the
3133        //             calculator will seek the trie cursor to find a deeper cached branch.
3134        //
3135        // Having three children with two (b, c) NOT in the prefix set ensures
3136        // `should_skip_cached_branch` does NOT skip this branch (num_unmatched >= 2).
3137        let branch_6_state_mask = TrieMask::new((1 << 0xa) | (1 << 0xb) | (1 << 0xc));
3138        let branch_6_hash_mask = TrieMask::new((1 << 0xb) | (1 << 0xc));
3139        let branch_6 = BranchNodeCompact::new(
3140            branch_6_state_mask,
3141            TrieMask::new(0),
3142            branch_6_hash_mask,
3143            vec![leaf_hash_d, leaf_hash_e],
3144            None,
3145        );
3146
3147        // ── Construct cached branch at [6,a,8] ────────────────────────────────
3148        // state_mask: bits 0 and 1 set (children key_a0 and key_a1).
3149        // hash_mask:  both bits set — both children have cached hashes.
3150        let branch_6a8_state_mask = TrieMask::new((1 << 0) | (1 << 1));
3151        let branch_6a8 = BranchNodeCompact::new(
3152            branch_6a8_state_mask,
3153            TrieMask::new(0),
3154            branch_6a8_state_mask,
3155            vec![leaf_hash_a0, leaf_hash_a1],
3156            None,
3157        );
3158
3159        // Intentionally omit the branch at [6,a] — this is the inconsistency.
3160        let inconsistent_nodes: BTreeMap<Nibbles, BranchNodeCompact> = [
3161            (Nibbles::from_nibbles([0x6]), branch_6),
3162            (Nibbles::from_nibbles([0x6, 0xa, 0x8]), branch_6a8),
3163        ]
3164        .into_iter()
3165        .collect();
3166
3167        // Create harness with all five leaves but the inconsistent trie nodes.
3168        let mut harness = TrieTestHarness::new(all_storage);
3169        harness.set_trie_nodes(inconsistent_nodes);
3170
3171        // Mark key_c as dirty — it comes BEFORE the cached branch [6,a,8] in nibble order.
3172        let mut prefix_set = PrefixSetMut::default();
3173        prefix_set.insert(Nibbles::unpack(key_c));
3174
3175        // ── Verify root hash ───────────────────────────────────────────────────
3176        let trie_cursor =
3177            harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
3178        let hashed_cursor = harness
3179            .hashed_cursor_factory()
3180            .hashed_storage_cursor(harness.hashed_address())
3181            .unwrap();
3182        let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
3183            .with_prefix_set(prefix_set.freeze());
3184
3185        let root_node = calculator
3186            .storage_root_node(harness.hashed_address())
3187            .expect("storage_root_node should succeed");
3188        let got_root = calculator
3189            .compute_root_hash(core::slice::from_ref(&root_node))
3190            .unwrap()
3191            .expect("should produce a root hash");
3192
3193        // With the bug, the calculator skips key_c and produces a wrong root.
3194        pretty_assertions::assert_eq!(
3195            expected_root,
3196            got_root,
3197            "Root hash should match correct trie; cached extension must not skip diverging leaves before cached branch"
3198        );
3199
3200        // ── Verify proof for key_c contains nodes on its path ──────────────────
3201        let mut targets = vec![ProofV2Target::new(key_c)];
3202        let proofs = calculator
3203            .storage_proof(harness.hashed_address(), &mut targets)
3204            .expect("storage_proof should succeed");
3205
3206        let key_c_nibbles = Nibbles::unpack(key_c);
3207        let has_matching_node = proofs.iter().any(|node| key_c_nibbles.starts_with(&node.path));
3208        assert!(
3209            has_matching_node,
3210            "Proof for key_c should contain at least one node on key_c's path, got: {proofs:?}"
3211        );
3212    }
3213
3214    #[test]
3215    fn test_skipped_parent_branch_with_unskipped_child() {
3216        reth_tracing::init_test_tracing();
3217
3218        let val = U256::from(1u64);
3219        let updated_val = U256::from(2u64);
3220
3221        // We need cached branches at [2], [2,f], and [3] in the trie DB.
3222        let key_2 = B256::right_padding_from(&[0x20]);
3223        let key_2f00 = B256::right_padding_from(&[0x2f, 0x00]);
3224        let key_2f01 = B256::right_padding_from(&[0x2f, 0x01]);
3225        let key_2f10 = B256::right_padding_from(&[0x2f, 0x10]);
3226        let key_2f11 = B256::right_padding_from(&[0x2f, 0x11]);
3227        let key_300 = B256::right_padding_from(&[0x30, 0x00]);
3228        let key_301 = B256::right_padding_from(&[0x30, 0x10]);
3229        let key_310 = B256::right_padding_from(&[0x31, 0x00]);
3230        let key_311 = B256::right_padding_from(&[0x31, 0x10]);
3231        let key_500 = B256::right_padding_from(&[0x50, 0x00]);
3232        let key_501 = B256::right_padding_from(&[0x50, 0x10]);
3233        let key_510 = B256::right_padding_from(&[0x51, 0x00]);
3234        let key_511 = B256::right_padding_from(&[0x51, 0x10]);
3235
3236        let all_keys = [
3237            key_2, key_2f00, key_2f01, key_2f10, key_2f11, key_300, key_301, key_310, key_311,
3238            key_500, key_501, key_510, key_511,
3239        ];
3240
3241        let original_storage: BTreeMap<B256, U256> = all_keys.iter().map(|k| (*k, val)).collect();
3242        let harness = TrieTestHarness::new(original_storage);
3243
3244        // Verify that the expected branches exist in the trie.
3245        let trie_updates = harness.storage_trie_updates();
3246        assert!(trie_updates.storage_nodes.contains_key(&Nibbles::from_nibbles([0x2])));
3247        assert!(trie_updates.storage_nodes.contains_key(&Nibbles::from_nibbles([0x2, 0xf])));
3248        assert!(trie_updates.storage_nodes.contains_key(&Nibbles::from_nibbles([0x3])));
3249
3250        // Change only key_2 — triggers skip of parent branch [2] while child [2,f] is not
3251        // skipped.
3252        let changeset: BTreeMap<B256, U256> = std::iter::once((key_2, updated_val)).collect();
3253        let (expected_root, _) = harness.get_root_with_updates(&changeset);
3254
3255        let mut updated_storage = harness.storage().clone();
3256        updated_storage.insert(key_2, updated_val);
3257
3258        let updated_hashed = MockHashedCursorFactory::new(
3259            BTreeMap::new(),
3260            std::iter::once((harness.hashed_address(), updated_storage)).collect(),
3261        );
3262
3263        let mut prefix_set = PrefixSetMut::default();
3264        prefix_set.insert(Nibbles::unpack(key_2));
3265
3266        let trie_cursor =
3267            harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
3268        let hashed_cursor = updated_hashed.hashed_storage_cursor(harness.hashed_address()).unwrap();
3269        let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
3270            .with_prefix_set(prefix_set.freeze());
3271        let root_node = calculator
3272            .storage_root_node(harness.hashed_address())
3273            .expect("storage_root_node should succeed");
3274
3275        let got_root = calculator
3276            .compute_root_hash(&[root_node])
3277            .expect("root hash should succeed")
3278            .expect("root should get hashed");
3279        pretty_assertions::assert_eq!(expected_root, got_root);
3280    }
3281
3282    #[test]
3283    fn test_cached_hash_with_deleted_leaf() {
3284        reth_tracing::init_test_tracing();
3285
3286        // Use different values to ensure distinct leaf hashes.
3287        let val_3 = U256::from(111u64);
3288        let val_5 = U256::from(222u64);
3289        let val_8 = U256::from(333u64);
3290
3291        // Keys under a common prefix `0x6_` to create a branch at path [6].
3292        // Use second byte to distinguish short keys (so they differ after position 2).
3293        let key_63 = B256::right_padding_from(&[0x63, 0xaa]); // nibble path: 6,3,a,a,...
3294        let key_65 = B256::right_padding_from(&[0x65, 0xbb]); // nibble path: 6,5,b,b,...
3295        let key_68 = B256::right_padding_from(&[0x68, 0xcc]); // nibble path: 6,8,c,c,...
3296
3297        // Compute leaf hashes. The branch at [6] consumes 2 nibbles (the branch path [6]
3298        // plus the child nibble), so each leaf's short key starts at position 2.
3299        let leaf_hash_3 = storage_leaf_hash(&Nibbles::unpack(key_63).slice(2..), &val_3);
3300        let leaf_hash_5 = storage_leaf_hash(&Nibbles::unpack(key_65).slice(2..), &val_5);
3301        let leaf_hash_8 = storage_leaf_hash(&Nibbles::unpack(key_68).slice(2..), &val_8);
3302
3303        // Build cached branch at [6] with state_mask and hash_mask bits for nibbles 3, 5, 8.
3304        let state_mask = TrieMask::new((1 << 3) | (1 << 5) | (1 << 8));
3305        let cached_branch = BranchNodeCompact::new(
3306            state_mask,
3307            TrieMask::new(0),
3308            state_mask, // hash_mask = state_mask (all children have cached hashes)
3309            vec![leaf_hash_3, leaf_hash_5, leaf_hash_8],
3310            None,
3311        );
3312
3313        let storage_nodes: BTreeMap<Nibbles, BranchNodeCompact> =
3314            std::iter::once((Nibbles::from_nibbles([0x6]), cached_branch)).collect();
3315
3316        // Compute the expected root from a fresh trie with just key_65 and key_68.
3317        let mut harness =
3318            TrieTestHarness::new([(key_65, val_5), (key_68, val_8)].into_iter().collect());
3319        let expected_root = harness.original_root();
3320
3321        // Update the harness with a cached trie node which will reference key_63 by hash.
3322        harness.set_trie_nodes(storage_nodes);
3323
3324        // Mark key_63 as dirty in the prefix set — in the real scenario the leaf was
3325        // deleted and the HashedPostState overlay masks it out.
3326        let mut prefix_set = PrefixSetMut::default();
3327        prefix_set.insert(Nibbles::unpack(key_63));
3328
3329        // Request a proof for key_63 (absence proof — no leaf exists).
3330        // Because the prefix set marks nibble 3's child path as dirty, the cached hash for
3331        // nibble 3 is skipped.
3332        let mut targets = vec![ProofV2Target::new(key_63)];
3333
3334        let trie_cursor =
3335            harness.trie_cursor_factory().storage_trie_cursor(harness.hashed_address()).unwrap();
3336        let hashed_cursor = harness
3337            .hashed_cursor_factory()
3338            .hashed_storage_cursor(harness.hashed_address())
3339            .unwrap();
3340        let mut calculator = StorageProofCalculator::new_storage(trie_cursor, hashed_cursor)
3341            .with_prefix_set(prefix_set.freeze());
3342
3343        let proofs = calculator
3344            .storage_proof(harness.hashed_address(), &mut targets)
3345            .expect("storage_proof should succeed");
3346        assert_eq!(1, proofs.len());
3347        let got_root = calculator
3348            .compute_root_hash(&proofs)
3349            .expect("compute_root_hash should succeed")
3350            .expect("should produce a root hash (proof contains root node)");
3351
3352        // With the bug, nibble 5 gets hashes[0] (nibble 3's hash) and nibble 8 gets
3353        // hashes[1] (nibble 5's hash), producing a wrong root.
3354        pretty_assertions::assert_eq!(
3355            expected_root,
3356            got_root,
3357            "Root hash should match trie without key_63; cached hash index is off when \
3358             an earlier hashed child has no leaves (absence proof target)"
3359        );
3360    }
3361}