Skip to main content

reth_trie_sparse/arena/
mod.rs

1mod branch_child_idx;
2mod cursor;
3mod node_arena;
4mod nodes;
5
6// Require a custom cfg as well as `fuzz`: ordinary `--all-features` Clippy, udeps, doctests
7// and private docs must not instantiate the 28,674-function coverage bank. Enable explicitly
8// with `RUSTFLAGS="--cfg reth_sparse_trie_coverage"` and `--features fuzz`.
9#[cfg(all(feature = "fuzz", reth_sparse_trie_coverage))]
10mod sparse_guidance;
11
12use branch_child_idx::{BranchChildIdx, BranchChildIter};
13use cursor::{branch_idx, ArenaCursor, NextResult, SeekResult};
14use node_arena::{BranchChild, Index, NodeArena};
15use nodes::{ArenaSparseNode, ArenaSparseNodeBranch, ArenaSparseNodeState, ExtensionChild};
16
17use crate::{
18    LeafLookup, LeafLookupError, LeafUpdate, SparseTrie, SparseTrieUpdates, TrieNodeEpoch,
19};
20use alloc::{borrow::Cow, boxed::Box, vec::Vec};
21use alloy_primitives::{keccak256, map::B256Map, B256};
22use alloy_trie::TrieMask;
23use core::{cmp::Reverse, mem};
24use reth_concurrency::sync::rayon::iter::{
25    IntoParallelIterator, IntoParallelRefMutIterator, ParallelIterator,
26};
27use reth_execution_errors::{SparseTrieErrorKind, SparseTrieResult};
28use reth_trie_common::{
29    BranchNodeMasks, BranchNodeRef, ExtensionNodeRef, LeafNodeRef, Nibbles, ProofTrieNode,
30    ProofV2TargetParent, RlpNode, TrieNode, EMPTY_ROOT_HASH,
31};
32use smallvec::SmallVec;
33use tracing::{instrument, trace};
34
35const TRACE_TARGET: &str = "trie::arena";
36
37/// The maximum path length (in nibbles) for nodes that live in the upper trie. Nodes at this
38/// depth or deeper belong to lower subtries.
39const UPPER_TRIE_MAX_DEPTH: usize = 2;
40
41/// Reads revealed and leaf masks from live handles, including lower-subtrie roots.
42/// Taken update subtries have not been mutated yet, so their roots retain the observed shape.
43#[cfg(all(feature = "fuzz", reth_sparse_trie_coverage))]
44fn coverage_branch_masks(
45    arena: &NodeArena,
46    branch: &ArenaSparseNodeBranch,
47    taken: &[(Index, Box<ArenaSparseSubtrie>, core::ops::Range<usize>)],
48) -> (u16, u16) {
49    let mut revealed = TrieMask::default();
50    let mut leaf = TrieMask::default();
51    for (nibble, child) in branch.child_iter() {
52        if let Some(child_idx) = child.revealed_index() {
53            revealed.set_bit(nibble);
54            let mut node = &arena[child_idx];
55            if matches!(node, ArenaSparseNode::TakenSubtrie) {
56                let (_, subtrie, _) = taken
57                    .iter()
58                    .find(|(idx, _, _)| *idx == child_idx)
59                    .expect("taken child must have a pending update subtrie");
60                node = &subtrie.arena[subtrie.root];
61            }
62            while let ArenaSparseNode::Subtrie(subtrie) = node {
63                node = &subtrie.arena[subtrie.root];
64            }
65            if matches!(node, ArenaSparseNode::Leaf { .. }) {
66                leaf.set_bit(nibble);
67            }
68        }
69    }
70    (revealed.get(), leaf.get())
71}
72
73/// Observes a proof target at emission, before any mutation changes its logical parent.
74/// A blinded root or opaque backing branch has no revealed parent shape. Collapse parents contain
75/// only the current child and its blinded sibling, so they have no taken sibling to resolve.
76#[cfg(all(feature = "fuzz", reth_sparse_trie_coverage))]
77fn observe_proof_target(
78    arena: &NodeArena,
79    parent: Option<(Index, usize)>,
80    target_path: &Nibbles,
81    taken: &[(Index, Box<ArenaSparseSubtrie>, core::ops::Range<usize>)],
82) {
83    if let Some((parent_idx, depth)) = parent &&
84        branch_idx(arena, parent_idx).is_some()
85    {
86        let branch = branch_data(arena, parent_idx);
87        let target = target_path.get_unchecked(depth);
88        // An opaque extension's backing branch has no revealed immediate branch neighborhood.
89        if let Some(child_idx) = BranchChildIdx::new(branch.state_mask, target) &&
90            let Some(idx) = branch.children[child_idx].revealed_index() &&
91            has_blinded_branch(arena, idx)
92        {
93            observe_blind_root_proof_target();
94            return;
95        }
96        let (revealed, leaf) = coverage_branch_masks(arena, branch, taken);
97        sparse_guidance::observe_proof_target(
98            depth,
99            true,
100            target,
101            branch.state_mask.get(),
102            revealed,
103            leaf,
104        );
105    } else {
106        observe_blind_root_proof_target();
107    }
108}
109
110/// Observes a proof request without a revealed immediate branch neighborhood.
111#[cfg(all(feature = "fuzz", reth_sparse_trie_coverage))]
112pub(crate) fn observe_blind_root_proof_target() {
113    sparse_guidance::observe_proof_target(0, false, 0, 0, 0, 0);
114}
115
116/// Returns the branch data for a branch or extension node.
117fn branch_data(arena: &NodeArena, idx: Index) -> &ArenaSparseNodeBranch {
118    arena[branch_idx(arena, idx).expect("node must be a branch or extension")].branch_ref()
119}
120
121/// Returns the mutable branch data for a branch or extension node.
122fn branch_data_mut(arena: &mut NodeArena, idx: Index) -> &mut ArenaSparseNodeBranch {
123    let idx = branch_idx(arena, idx).expect("node must be a branch or extension");
124    arena[idx].branch_mut()
125}
126
127/// Returns the cached or dirty state for a node, following subtrie roots.
128fn node_state_ref(arena: &NodeArena, idx: Index) -> Option<&ArenaSparseNodeState> {
129    match &arena[idx] {
130        ArenaSparseNode::Subtrie(subtrie) => node_state_ref(&subtrie.arena, subtrie.root),
131        node => node.state_ref(),
132    }
133}
134
135/// Returns mutable cached or dirty state for a branch, extension, leaf, or empty root node.
136fn node_state_mut(arena: &mut NodeArena, idx: Index) -> &mut ArenaSparseNodeState {
137    arena[idx].state_mut()
138}
139
140/// Returns whether a node should contribute a bit in its parent's tree mask.
141fn node_tree_mask_bit(arena: &NodeArena, idx: Index) -> bool {
142    match &arena[idx] {
143        ArenaSparseNode::Branch(branch) => !branch.branch_masks.is_empty(),
144        ArenaSparseNode::Extension { child: ExtensionChild::Revealed(child), .. } => {
145            !arena[*child].branch_ref().branch_masks.is_empty()
146        }
147        ArenaSparseNode::Subtrie(subtrie) => node_tree_mask_bit(&subtrie.arena, subtrie.root),
148        _ => false,
149    }
150}
151
152/// Returns whether an extension (possibly a subtrie root) has a blinded backing branch.
153fn has_blinded_branch(arena: &NodeArena, idx: Index) -> bool {
154    match &arena[idx] {
155        ArenaSparseNode::Extension { child, .. } => matches!(child, ExtensionChild::Blinded(_)),
156        ArenaSparseNode::Subtrie(s) => has_blinded_branch(&s.arena, s.root),
157        _ => false,
158    }
159}
160
161/// A blinded backing branch has no known logical parent branch. Start its proof at the
162/// extension, using the extension's parent rather than claiming the hidden branch is revealed.
163fn blinded_proof_parent(arena: &NodeArena, cursor: &ArenaCursor) -> ProofV2TargetParent {
164    if has_blinded_branch(arena, cursor.head().expect("cursor is non-empty").index) {
165        cursor
166            .head_path_len()
167            .checked_sub(1)
168            .map_or(ProofV2TargetParent::NONE, ProofV2TargetParent::new)
169    } else {
170        ProofV2TargetParent::new(cursor.head_logical_branch_path_len(arena))
171    }
172}
173
174/// Structural changes need the backing branch's persistence masks before moving an extension.
175fn split_needs_proof(
176    arena: &NodeArena,
177    cursor: &ArenaCursor,
178    result: &SeekResult,
179    update: &LeafUpdate,
180) -> bool {
181    matches!(result, SeekResult::Diverged) &&
182        matches!(update, LeafUpdate::Changed(value) if !value.is_empty()) &&
183        has_blinded_branch(arena, cursor.head().expect("cursor is non-empty").index)
184}
185
186/// A surviving extension also needs its backing masks before a branch can collapse onto it.
187fn child_needs_collapse_proof(arena: &NodeArena, child: BranchChild) -> bool {
188    child.revealed_index().is_none_or(|idx| has_blinded_branch(arena, idx))
189}
190
191/// Select a key below an opaque extension rather than an exclusion target diverging from it.
192fn extend_blinded_branch_path(arena: &NodeArena, child: BranchChild, path: &mut Nibbles) {
193    if let Some(idx) = child.revealed_index() {
194        match &arena[idx] {
195            ArenaSparseNode::Extension { key, .. } => path.extend(key),
196            ArenaSparseNode::Subtrie(s) => {
197                if let Some(key) = s.arena[s.root].extension_key() {
198                    path.extend(key);
199                }
200            }
201            _ => {}
202        }
203    }
204}
205
206/// Sorts and compacts proof batches, which may combine overlapping calculator outputs.
207/// All records for a path describe the same node; keep any supplied persistence masks.
208fn sort_proof_nodes(nodes: &mut [ProofTrieNode]) -> &mut [ProofTrieNode] {
209    nodes.sort_unstable_by_key(|node| node.path);
210    let mut len = 0;
211    for index in 0..nodes.len() {
212        if len > 0 && nodes[index].path == nodes[len - 1].path {
213            nodes[len - 1].masks = nodes[index].masks.or(nodes[len - 1].masks);
214        } else {
215            nodes.swap(len, index);
216            len += 1;
217        }
218    }
219    // Callers can pass the same batch from set_root to reveal_nodes without replaying duplicates.
220    for node in &mut nodes[len..] {
221        *node = ProofTrieNode::empty();
222    }
223    &mut nodes[..len]
224}
225
226/// Reject a non-branch record at an extension's child path before changing the arena.
227/// A missing child is valid: its reference remains blinded until a later proof.
228fn validate_extension_child(
229    node: &ProofTrieNode,
230    child: Option<&ProofTrieNode>,
231) -> SparseTrieResult<()> {
232    if let TrieNode::Extension(extension) = &node.node &&
233        child.is_some_and(|child| {
234            child.path == node.path.join(&extension.key) &&
235                !matches!(child.node, TrieNode::Branch(_))
236        })
237    {
238        return Err(SparseTrieErrorKind::Reveal {
239            path: node.path,
240            node: Box::new(extension.clone()),
241        }
242        .into());
243    }
244    Ok(())
245}
246
247/// Takes an adjacent branch proof when it accompanies an extension.
248fn take_extension_child(nodes: &mut [ProofTrieNode], index: usize) -> Option<ProofTrieNode> {
249    let TrieNode::Extension(extension) = &nodes[index].node else { return None };
250    nodes
251        .get(index + 1)
252        .is_some_and(|child| {
253            child.path == nodes[index].path.join(&extension.key) &&
254                matches!(child.node, TrieNode::Branch(_))
255        })
256        .then(|| mem::replace(&mut nodes[index + 1], ProofTrieNode::empty()))
257}
258
259/// Moves a node into another arena, keeping an extension with its branch child.
260fn move_node(dst: &mut NodeArena, src: &mut NodeArena, idx: Index) -> Index {
261    let node = src.drain_node(idx);
262    let new_idx = dst.insert(node);
263    if let Some(child_idx) = dst[new_idx].extension_child() {
264        let child = src.drain_node(child_idx);
265        let new_child_idx = dst.insert(child);
266        let ArenaSparseNode::Extension { child, .. } = &mut dst[new_idx] else { unreachable!() };
267        *child = ExtensionChild::Revealed(new_child_idx);
268    }
269    new_idx
270}
271
272/// Compacts an arena by BFS-copying all reachable nodes into a fresh arena, dropping
273/// unreachable (pruned) slots. Parents are stored before children for cache-friendly top-down
274/// traversal.
275fn compact_arena(arena: &mut NodeArena, root: &mut Index) {
276    let mut new_arena = NodeArena::with_capacity(arena.len());
277    let mut marks = new_arena.adopt_blinded(arena);
278    let root_node = arena.drain_node(*root);
279    let new_root = new_arena.insert(root_node);
280
281    // Nodes append consecutively without removals, so the destination vector is also the BFS
282    // queue. Each visited node's children still reference the source arena until rewritten.
283    let mut next = 0;
284    while next < new_arena.len() {
285        let new_idx = Index::new(next);
286        next += 1;
287        if let Some(child) = new_arena[new_idx].extension_child() {
288            let child_node = arena.drain_node(child);
289            let new_child_idx = new_arena.insert(child_node);
290            let ArenaSparseNode::Extension { child, .. } = &mut new_arena[new_idx] else {
291                unreachable!()
292            };
293            *child = ExtensionChild::Revealed(new_child_idx);
294            continue;
295        }
296
297        let old_children: SmallVec<[(usize, Index); 16]> = match &new_arena[new_idx] {
298            ArenaSparseNode::Branch(b) => b
299                .children
300                .iter()
301                .enumerate()
302                .filter_map(|(pos, child)| match child.revealed_index() {
303                    Some(old_child_idx) => Some((pos, old_child_idx)),
304                    // A blinded child needs no rewrite, its slot survived the adoption.
305                    None => {
306                        marks.mark(*child);
307                        None
308                    }
309                })
310                .collect(),
311            _ => continue,
312        };
313
314        for (child_pos, old_child_idx) in old_children {
315            let child_node = arena.drain_node(old_child_idx);
316            let new_child_idx = new_arena.insert(child_node);
317            debug_assert_eq!(
318                new_child_idx.get() + 1,
319                new_arena.len(),
320                "compaction must append, the destination doubles as the BFS queue",
321            );
322            new_arena[new_idx].branch_mut().children[child_pos] =
323                BranchChild::revealed(new_child_idx);
324        }
325    }
326
327    debug_assert!(
328        arena.iter().next().is_none(),
329        "compact_arena: {} orphaned nodes remaining after BFS drain",
330        arena.iter().count(),
331    );
332
333    new_arena.sweep_blinded(marks);
334    *arena = new_arena;
335    *root = new_root;
336}
337
338/// Reusable traversal state and optional accumulators shared by
339/// [`ArenaSparseSubtrie`] and [`ArenaParallelSparseTrie`].
340#[derive(Debug, Default, Clone)]
341struct ArenaTrieBuffers {
342    /// Reusable cursor for trie traversals.
343    cursor: ArenaCursor,
344    /// Trie updates built up directly during hashing and structural changes. `Some` when
345    /// tracking updates, `None` otherwise. Initialized alongside `updates` in `set_updates`.
346    updates: Option<SparseTrieUpdates>,
347    /// Reusable buffer for RLP encoding.
348    rlp_buf: Vec<u8>,
349    /// Reusable buffer for child `RlpNode`s during hashing.
350    rlp_node_buf: Vec<RlpNode>,
351}
352
353impl ArenaTrieBuffers {
354    fn clear(&mut self) {
355        if let Some(updates) = self.updates.as_mut() {
356            updates.clear();
357        }
358        self.rlp_buf.clear();
359        self.rlp_node_buf.clear();
360    }
361}
362
363/// A subtrie within the arena-based parallel sparse trie.
364///
365/// Each subtrie owns its own arena, allowing parallel mutations across subtries.
366#[derive(Debug, Clone)]
367struct ArenaSparseSubtrie {
368    /// The arena allocating nodes within this subtrie.
369    arena: NodeArena,
370    /// The root node of this subtrie.
371    root: Index,
372    /// The absolute path of this subtrie's root in the full trie.
373    path: Nibbles,
374    /// Reusable buffers for traversal, RLP encoding, and update actions.
375    buffers: ArenaTrieBuffers,
376    /// Reusable buffer for collecting required proofs during leaf updates.
377    /// Each entry is `(index, proof)` where `index` is the position of the target in the
378    /// `sorted_updates` slice passed to [`Self::update_leaves`].
379    required_proofs: Vec<(usize, ArenaRequiredProof)>,
380    /// Total number of revealed leaves in this subtrie.
381    num_leaves: u64,
382    /// Number of dirty (modified since last hash) leaves in this subtrie.
383    num_dirty_leaves: u64,
384}
385
386impl ArenaSparseSubtrie {
387    /// Creates a new subtrie with a pre-allocated root slot containing
388    /// [`ArenaSparseNode::EmptyRoot`]. The caller must overwrite `subtrie.arena[subtrie.root]`
389    /// before use.
390    fn new(record_updates: bool) -> Box<Self> {
391        let mut arena = NodeArena::new();
392        let root =
393            arena.insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Revealed });
394        let buffers = ArenaTrieBuffers {
395            updates: record_updates.then(SparseTrieUpdates::default),
396            ..Default::default()
397        };
398        Box::new(Self {
399            arena,
400            root,
401            path: Nibbles::default(),
402            buffers,
403            required_proofs: Vec::new(),
404            num_leaves: 0,
405            num_dirty_leaves: 0,
406        })
407    }
408
409    /// Asserts that `num_leaves` and `num_dirty_leaves` match the actual counts in the arena.
410    #[cfg(all(debug_assertions, not(feature = "fuzz")))]
411    fn debug_assert_counters(&self) {
412        let (actual_leaves, actual_dirty) =
413            ArenaParallelSparseTrie::count_leaves_and_dirty(&self.arena, self.root);
414        debug_assert_eq!(
415            self.num_leaves, actual_leaves,
416            "subtrie {:?} num_leaves mismatch: stored {} vs actual {}",
417            self.path, self.num_leaves, actual_leaves,
418        );
419        debug_assert_eq!(
420            self.num_dirty_leaves, actual_dirty,
421            "subtrie {:?} num_dirty_leaves mismatch: stored {} vs actual {}",
422            self.path, self.num_dirty_leaves, actual_dirty,
423        );
424    }
425
426    /// Collapses nodes last modified before `prune_before` into hash stubs while copying retained
427    /// nodes into a compacted arena.
428    ///
429    /// Expects that all nodes have computed hashes (i.e. `prune` is called after hashing).
430    fn prune(&mut self, prune_before: TrieNodeEpoch) -> usize {
431        // Only branches can have pruneable children.
432        if branch_idx(&self.arena, self.root).is_none() {
433            return 0;
434        }
435
436        debug_assert_eq!(self.num_dirty_leaves, 0, "prune must run after hashing");
437
438        if prune_before == TrieNodeEpoch::UNMODIFIED {
439            return 0;
440        }
441
442        let old_count = self.arena.len();
443        // Reserve an upper bound on the retained nodes and hand the excess back after the copy,
444        // so that copying never reallocates but discarded nodes still release their capacity.
445        let mut new_arena = NodeArena::with_capacity(old_count);
446        let mut marks = new_arena.adopt_blinded(&mut self.arena);
447        let mut new_num_leaves = 0u64;
448
449        // The subtrie root is retained by the owning upper trie.
450        let new_root = move_node(&mut new_arena, &mut self.arena, self.root);
451        let mut stack = Vec::new();
452        if let Some(frame) =
453            prepare_retained_node(&new_arena, new_root, self.path, &mut new_num_leaves)
454        {
455            stack.push(frame);
456        }
457
458        while let Some(frame) = stack.last_mut() {
459            let Some((child_pos, nibble, child)) = frame.next_child(&new_arena) else {
460                stack.pop();
461                continue;
462            };
463
464            let Some(old_child_idx) = child.revealed_index() else {
465                // A blinded child needs no rewrite, its slot survived the adoption.
466                marks.mark(child);
467                continue;
468            };
469
470            let parent_new_idx = frame.new_idx;
471            let mut child_path = frame.branch_logical_path;
472            child_path.push(nibble);
473
474            let child_epoch = node_state_ref(&self.arena, old_child_idx)
475                .and_then(ArenaSparseNodeState::cached_epoch)
476                .expect("prune must run after hashing");
477
478            if child_epoch.should_prune(prune_before) {
479                let node = &self.arena[old_child_idx];
480                let rlp_node = node_state_ref(&self.arena, old_child_idx)
481                    .and_then(ArenaSparseNodeState::cached_rlp_node)
482                    .cloned()
483                    .expect("prune must run after hashing");
484                trace!(
485                    target: TRACE_TARGET,
486                    path = ?child_path,
487                    variant = %AsRef::<str>::as_ref(node),
488                    cached_rlp_node = ?rlp_node,
489                    "pruning node",
490                );
491                let new_child = new_arena.insert_blinded(rlp_node);
492                marks.mark(new_child);
493                branch_data_mut(&mut new_arena, parent_new_idx).children[child_pos] = new_child;
494                let node = self.arena.drain_node(old_child_idx);
495                if let Some(child) = node.extension_child() {
496                    self.arena.drain_node(child);
497                }
498            } else {
499                let new_child_idx = move_node(&mut new_arena, &mut self.arena, old_child_idx);
500                if let Some(frame) = prepare_retained_node(
501                    &new_arena,
502                    new_child_idx,
503                    child_path,
504                    &mut new_num_leaves,
505                ) {
506                    stack.push(frame);
507                }
508                branch_data_mut(&mut new_arena, parent_new_idx).children[child_pos] =
509                    BranchChild::revealed(new_child_idx);
510            }
511        }
512
513        new_arena.sweep_blinded(marks);
514        new_arena.shrink_nodes_to_fit();
515        let pruned = old_count - new_arena.len();
516        self.num_leaves = new_num_leaves;
517        self.num_dirty_leaves = 0;
518        self.arena = new_arena;
519        self.root = new_root;
520
521        #[cfg(all(debug_assertions, not(feature = "fuzz")))]
522        self.debug_assert_counters();
523        return pruned;
524
525        struct CopyFrame {
526            new_idx: Index,
527            branch_logical_path: Nibbles,
528            state_mask: TrieMask,
529            remaining_child_mask: TrieMask,
530        }
531
532        impl CopyFrame {
533            fn next_child(&mut self, new_arena: &NodeArena) -> Option<(usize, u8, BranchChild)> {
534                let b = branch_data(new_arena, self.new_idx);
535
536                let nibble = self.remaining_child_mask.first_set_bit_index()?;
537                self.remaining_child_mask.unset_bit(nibble);
538                let child_idx = BranchChildIdx::new(self.state_mask, nibble)
539                    .expect("remaining_child_mask must be a subset of state_mask");
540
541                Some((child_idx.get(), nibble, b.children[child_idx]))
542            }
543        }
544
545        /// Prepares a retained node for copying, returning a stack frame when the node has children
546        /// to walk.
547        fn prepare_retained_node(
548            new_arena: &NodeArena,
549            new_idx: Index,
550            node_path: Nibbles,
551            new_num_leaves: &mut u64,
552        ) -> Option<CopyFrame> {
553            if branch_idx(new_arena, new_idx).is_none() {
554                if matches!(&new_arena[new_idx], ArenaSparseNode::Leaf { .. }) {
555                    *new_num_leaves += 1;
556                }
557                return None;
558            }
559            let b = branch_data(new_arena, new_idx);
560
561            let mut branch_logical_path = node_path;
562            if let Some(key) = new_arena[new_idx].extension_key() {
563                branch_logical_path.extend(key);
564            }
565
566            Some(CopyFrame {
567                new_idx,
568                branch_logical_path,
569                state_mask: b.state_mask,
570                remaining_child_mask: b.state_mask,
571            })
572        }
573    }
574
575    /// Applies leaf updates within this subtrie. Uses the same walk-down-with-cursor pattern as
576    /// [`Self::reveal_nodes`], but checks accessibility for [`LeafUpdate::Touched`] entries.
577    ///
578    /// `sorted_updates` must be sorted lexicographically by their nibbles path (index 1).
579    ///
580    /// Any required proofs are appended to `self.required_proofs` and should be drained by the
581    /// caller after this method returns.
582    #[instrument(
583        level = "trace",
584        target = TRACE_TARGET,
585        skip_all,
586        fields(
587            subtrie = ?self.path,
588            num_updates = sorted_updates.len(),
589        ),
590    )]
591    fn update_leaves(&mut self, sorted_updates: &[(B256, Nibbles, LeafUpdate)]) {
592        if sorted_updates.is_empty() {
593            return;
594        }
595        trace!(target: TRACE_TARGET, "Subtrie update_leaves");
596
597        debug_assert!(
598            !matches!(self.arena[self.root], ArenaSparseNode::EmptyRoot { .. }),
599            "subtrie root must not be EmptyRoot at start of update_leaves"
600        );
601
602        self.buffers.cursor.reset(&self.arena, self.root, self.path);
603
604        for (idx, &(key, ref full_path, ref update)) in sorted_updates.iter().enumerate() {
605            let find_result = self.buffers.cursor.seek(&mut self.arena, full_path);
606
607            // If the path hits a blinded node, request a proof regardless of update type.
608            if matches!(find_result, SeekResult::Blinded) ||
609                split_needs_proof(&self.arena, &self.buffers.cursor, &find_result, update)
610            {
611                let proof_key = if matches!(find_result, SeekResult::Diverged) {
612                    ArenaParallelSparseTrie::nibbles_to_padded_b256(
613                        &self.buffers.cursor.head_logical_branch_path(&self.arena),
614                    )
615                } else {
616                    key
617                };
618                #[cfg(all(feature = "fuzz", reth_sparse_trie_coverage))]
619                let logical_len = self.buffers.cursor.head_logical_branch_path_len(&self.arena);
620                #[cfg(all(feature = "fuzz", reth_sparse_trie_coverage))]
621                observe_proof_target(
622                    &self.arena,
623                    self.buffers.cursor.head().map(|entry| (entry.index, logical_len)),
624                    full_path,
625                    &[],
626                );
627                self.required_proofs.push((
628                    idx,
629                    ArenaRequiredProof {
630                        key: proof_key,
631                        parent: blinded_proof_parent(&self.arena, &self.buffers.cursor),
632                    },
633                ));
634                continue;
635            }
636
637            match update {
638                LeafUpdate::Changed(value) if !value.is_empty() => {
639                    // Upsert: insert or update a leaf with the given value.
640                    let (_result, deltas) = ArenaParallelSparseTrie::upsert_leaf(
641                        &mut self.arena,
642                        &mut self.buffers.cursor,
643                        &mut self.root,
644                        full_path,
645                        value,
646                        find_result,
647                    );
648                    self.num_leaves = (self.num_leaves as i64 + deltas.num_leaves_delta) as u64;
649                    self.num_dirty_leaves =
650                        (self.num_dirty_leaves as i64 + deltas.num_dirty_leaves_delta) as u64;
651                }
652                LeafUpdate::Changed(_) => {
653                    let (result, deltas) = ArenaParallelSparseTrie::remove_leaf(
654                        &mut self.arena,
655                        &mut self.buffers.cursor,
656                        &mut self.root,
657                        key,
658                        full_path,
659                        find_result,
660                        &mut self.buffers.updates,
661                    );
662                    self.num_leaves = (self.num_leaves as i64 + deltas.num_leaves_delta) as u64;
663                    self.num_dirty_leaves =
664                        (self.num_dirty_leaves as i64 + deltas.num_dirty_leaves_delta) as u64;
665
666                    // The removed leaf is already revealed, so only the blinded sibling needs a
667                    // proof. The caller retries the update once that sibling is revealed.
668                    if let RemoveLeafResult::NeedsProof { proof_key, parent, .. } = result {
669                        self.required_proofs
670                            .push((idx, ArenaRequiredProof { key: proof_key, parent }));
671                    }
672                }
673                LeafUpdate::Touched => {}
674            }
675        }
676
677        // Drain remaining cursor entries, propagating dirty state.
678        self.buffers.cursor.drain(&mut self.arena);
679
680        #[cfg(all(debug_assertions, not(feature = "fuzz")))]
681        self.debug_assert_counters();
682    }
683
684    /// Reveals nodes inside this subtrie. Uses [`ArenaCursor::seek`] to locate the ancestor
685    /// node, then replaces blinded children with the proof nodes.
686    fn reveal_nodes(&mut self, nodes: &mut [ProofTrieNode]) -> SparseTrieResult<()> {
687        if nodes.is_empty() {
688            return Ok(());
689        }
690        trace!(target: TRACE_TARGET, path = ?self.path, num_nodes = nodes.len(), "Subtrie reveal_nodes");
691
692        debug_assert!(
693            !matches!(self.arena[self.root], ArenaSparseNode::EmptyRoot { .. }),
694            "subtrie root must not be EmptyRoot in reveal_nodes"
695        );
696
697        self.buffers.cursor.reset(&self.arena, self.root, self.path);
698
699        let mut node_idx = 0;
700        while node_idx < nodes.len() {
701            let find_result = self.buffers.cursor.seek(&mut self.arena, &nodes[node_idx].path);
702            let extension_child = if matches!(find_result, SeekResult::Blinded) {
703                take_extension_child(nodes, node_idx)
704            } else {
705                None
706            };
707            let next_idx = node_idx + 1 + usize::from(extension_child.is_some());
708            let node = &mut nodes[node_idx];
709            if ArenaParallelSparseTrie::reveal_node(
710                &mut self.arena,
711                &self.buffers.cursor,
712                node,
713                extension_child,
714                find_result,
715            )
716            .is_some_and(|child_idx| matches!(self.arena[child_idx], ArenaSparseNode::Leaf { .. }))
717            {
718                self.num_leaves += 1;
719            }
720            node_idx = next_idx;
721        }
722
723        // Drain remaining cursor entries, propagating dirty state.
724        self.buffers.cursor.drain(&mut self.arena);
725
726        #[cfg(all(debug_assertions, not(feature = "fuzz")))]
727        self.debug_assert_counters();
728
729        Ok(())
730    }
731
732    /// Computes and caches `RlpNode` for all dirty nodes via iterative post-order DFS.
733    /// After this call every node reachable from `self.root` will be in `Cached` state.
734    ///
735    /// Trie updates are written directly to `self.buffers.updates` (if `Some`).
736    fn update_cached_rlp(&mut self, new_epoch: TrieNodeEpoch) {
737        ArenaParallelSparseTrie::update_cached_rlp(
738            &mut self.arena,
739            self.root,
740            self.path,
741            &mut self.buffers,
742            new_epoch,
743        );
744        self.num_dirty_leaves = 0;
745        #[cfg(all(debug_assertions, not(feature = "fuzz")))]
746        self.debug_assert_counters();
747    }
748}
749
750/// Tracks the net change in leaf counters caused by a trie mutation (upsert or removal).
751/// Returned alongside [`UpsertLeafResult`] / [`RemoveLeafResult`] so the caller can maintain
752/// aggregate counters on [`ArenaSparseSubtrie`] without scanning the arena.
753#[derive(Debug, Default)]
754struct SubtrieCounterDeltas {
755    num_leaves_delta: i64,
756    num_dirty_leaves_delta: i64,
757}
758
759/// Result of `upsert_leaf` indicating whether a new child was created that the caller
760/// may need to wrap as a subtrie (in the upper trie).
761#[derive(Debug)]
762enum UpsertLeafResult {
763    /// A leaf was updated in place (no structural change).
764    Updated,
765    /// A new leaf was created (e.g. EmptyRoot→Leaf, or root-level split).
766    NewLeaf,
767    /// A new child (branch or leaf) was created or inserted. The child is the cursor head
768    /// and its parent is the cursor's parent.
769    NewChild,
770}
771
772/// Result of `remove_leaf` indicating whether a proof is needed to complete a branch
773/// collapse.
774#[derive(Debug)]
775enum RemoveLeafResult {
776    /// No proof needed — the removal (and any collapse) completed fully.
777    Removed,
778    /// No leaf was found at the given path (no-op).
779    NotFound,
780    /// The branch collapse requires revealing a blinded sibling. The caller must request a
781    /// proof for the given key below the revealed logical parent branch.
782    NeedsProof { key: B256, proof_key: B256, parent: ProofV2TargetParent },
783}
784
785/// A proof request generated during leaf updates when a blinded node is encountered.
786#[derive(Debug, Clone)]
787struct ArenaRequiredProof {
788    /// The key requiring a proof.
789    key: B256,
790    /// The revealed logical parent branch.
791    parent: ProofV2TargetParent,
792}
793
794/// An arena-based parallel sparse trie.
795///
796/// Configuration for controlling when parallelism is enabled in [`ArenaParallelSparseTrie`]
797/// operations.
798#[derive(Debug, Clone, Copy, PartialEq, Eq)]
799pub struct ArenaParallelismThresholds {
800    /// Minimum number of dirty leaves in a subtrie before it is eligible for parallel hash
801    /// computation. Subtries with fewer dirty leaves than this are hashed serially during
802    /// [`ArenaParallelSparseTrie::update_subtrie_hashes`].
803    pub min_dirty_leaves: u64,
804    /// Minimum number of nodes to reveal in a subtrie before it is eligible for parallel
805    /// reveal. Subtries with fewer nodes to reveal than this are revealed inline during the
806    /// upper trie walk.
807    pub min_revealed_nodes: usize,
808    /// Minimum number of leaf updates targeting a subtrie before it is eligible for parallel
809    /// update. Subtries with fewer updates than this are updated inline during the upper trie
810    /// walk.
811    pub min_updates: usize,
812    /// Minimum number of revealed leaves in a subtrie before it is eligible for parallel
813    /// pruning. Subtries with fewer leaves than this are pruned inline during the upper trie
814    /// walk.
815    pub min_leaves_for_prune: u64,
816}
817
818impl Default for ArenaParallelismThresholds {
819    fn default() -> Self {
820        Self {
821            min_dirty_leaves: 64,
822            min_revealed_nodes: 16,
823            min_updates: 128,
824            min_leaves_for_prune: 128,
825        }
826    }
827}
828
829/// An arena-based sparse trie whose subtries can be mutated in parallel.
830///
831/// ## Structure
832///
833/// Uses arena allocation (`NodeArena`) for node storage with direct index-based child
834/// pointers, avoiding the per-node hashing overhead of a `HashMap`-based trie. The trie is split
835/// into two tiers:
836///
837/// - **Upper trie** (`upper_arena`): Contains nodes whose path is shorter than
838///   `UPPER_TRIE_MAX_DEPTH` nibbles. These are the root and its immediate children.
839/// - **Lower subtries** (`ArenaSparseSubtrie`): Each child of an upper-trie branch at the depth
840///   boundary becomes the root of its own subtrie, stored as an `ArenaSparseNode::Subtrie` child in
841///   the upper arena. Each subtrie owns its own arena, enabling lock-free parallel mutation.
842///
843/// Node placement is determined by path length (not counting a branch's short key):
844///
845/// - Paths with **< `UPPER_TRIE_MAX_DEPTH`** nibbles live in `upper_arena`.
846/// - Paths with **≥ `UPPER_TRIE_MAX_DEPTH`** nibbles live in a subtrie.
847///
848/// ## Node Revealing
849///
850/// Nodes are lazily revealed from proof data via [`SparseTrie::reveal_nodes`]. Each node is
851/// placed into the upper arena or delegated to its subtrie based on path depth. Unrevealed
852/// children are stored as blinded `BranchChild`s referencing their RLP encoding.
853/// When multiple subtries have pending reveals, they are processed in parallel using rayon
854/// (controlled by [`ArenaParallelismThresholds::min_revealed_nodes`]).
855///
856/// ## Leaf Operations
857///
858/// Leaf updates and removals are applied via [`SparseTrie::update_leaves`]. The method walks
859/// the upper trie to route each update to the correct subtrie, then processes subtries in
860/// parallel when the update count exceeds [`ArenaParallelismThresholds::min_updates`].
861///
862/// After updates, structural changes (branch collapse, subtrie unwrapping) are handled by
863/// propagating dirty state back up through the upper trie.
864///
865/// ## Root Hash Calculation
866///
867/// Root hash computation follows a bottom-up approach:
868///
869/// 1. **[`SparseTrie::update_subtrie_hashes`]**: Takes dirty subtries from the upper arena and
870///    hashes them in parallel (when dirty leaf count meets
871///    [`ArenaParallelismThresholds::min_dirty_leaves`]), then walks the upper trie to restore
872///    hashed subtries and inline-hash any remaining dirty nodes.
873/// 2. **[`SparseTrie::root`]**: Calls `update_subtrie_hashes`, then RLP-encodes the full upper trie
874///    depth-first to produce the root hash.
875///
876/// Each node tracks its state via `ArenaSparseNodeState` (`Revealed`, `Cached`, or `Dirty`)
877/// so only modified subtrees are recomputed.
878///
879/// ## Pruning
880///
881/// [`SparseTrie::prune`] replaces nodes older than its epoch cutoff with
882/// blinded `BranchChild` entries using their cached RLP, then compacts the
883/// arenas. Subtries are pruned in parallel when their leaf count exceeds
884/// [`ArenaParallelismThresholds::min_leaves_for_prune`].
885#[derive(Debug, Clone)]
886pub struct ArenaParallelSparseTrie {
887    /// The arena allocating nodes in the upper trie.
888    upper_arena: NodeArena,
889    /// The root node of the upper trie.
890    root: Index,
891    /// Reusable buffers for traversal, RLP encoding, and update actions.
892    buffers: ArenaTrieBuffers,
893    /// Thresholds controlling when parallelism is enabled for different operations.
894    parallelism_thresholds: ArenaParallelismThresholds,
895}
896
897impl ArenaParallelSparseTrie {
898    /// Sets the thresholds that control when parallelism is used during operations.
899    pub const fn with_parallelism_thresholds(
900        mut self,
901        thresholds: ArenaParallelismThresholds,
902    ) -> Self {
903        self.parallelism_thresholds = thresholds;
904        self
905    }
906
907    /// Returns `true` if a node at the given path length should be placed in a subtrie rather
908    /// than the upper arena.
909    const fn should_be_subtrie(path_len: usize) -> bool {
910        path_len == UPPER_TRIE_MAX_DEPTH
911    }
912
913    /// If the child at the cursor head should be a subtrie based on its depth, wraps it
914    /// in [`ArenaSparseNode::Subtrie`].
915    ///
916    /// The child must be the cursor head and its parent the cursor's parent.
917    fn maybe_wrap_in_subtrie(&mut self, child_idx: Index, child_path: &Nibbles) {
918        if !Self::should_be_subtrie(child_path.len()) {
919            return;
920        }
921
922        // Only branch and leaf nodes can become subtrie roots.
923        if !matches!(
924            self.upper_arena[child_idx],
925            ArenaSparseNode::Branch(_) |
926                ArenaSparseNode::Extension { .. } |
927                ArenaSparseNode::Leaf { .. }
928        ) {
929            return;
930        }
931
932        trace!(target: TRACE_TARGET, ?child_path, "Wrapping child into subtrie");
933        let mut subtrie = ArenaSparseSubtrie::new(self.buffers.updates.is_some());
934        subtrie.path = *child_path;
935        let mut root_node =
936            mem::replace(&mut self.upper_arena[child_idx], ArenaSparseNode::TakenSubtrie);
937
938        // Migrate any children from the upper arena into the subtrie arena.
939        Self::migrate_children(&mut subtrie.arena, &mut self.upper_arena, &mut root_node);
940
941        subtrie.arena[subtrie.root] = root_node;
942        let (leaves, dirty) = Self::count_leaves_and_dirty(&subtrie.arena, subtrie.root);
943        subtrie.num_leaves = leaves;
944        subtrie.num_dirty_leaves = dirty;
945        #[cfg(all(debug_assertions, not(feature = "fuzz")))]
946        subtrie.debug_assert_counters();
947        self.upper_arena[child_idx] = ArenaSparseNode::Subtrie(subtrie);
948    }
949
950    /// If the cursor head is a branch, wraps any revealed children that sit at
951    /// the subtrie boundary depth (`UPPER_TRIE_MAX_DEPTH`). This is needed after
952    /// structural changes like root-level splits or subtrie unwraps that can place
953    /// non-subtrie nodes at the boundary depth.
954    fn maybe_wrap_branch_children(&mut self, cursor: &ArenaCursor) {
955        let head_idx = cursor.head().expect("cursor is non-empty").index;
956        let head_path = cursor.head_path();
957
958        let Some(branch_idx) = branch_idx(&self.upper_arena, head_idx) else { return };
959        let short_key = self.upper_arena[head_idx].extension_key().copied();
960        let b = self.upper_arena[branch_idx].branch_ref();
961        let children: SmallVec<[_; 4]> = b
962            .child_iter()
963            .filter_map(|(nibble, child)| Some((nibble, child.revealed_index()?)))
964            .collect();
965
966        for (nibble, child_idx) in children {
967            let mut child_path = head_path;
968            if let Some(key) = short_key {
969                child_path.extend(&key);
970            }
971            child_path.push_unchecked(nibble);
972            self.maybe_wrap_in_subtrie(child_idx, &child_path);
973        }
974    }
975
976    /// Checks whether the subtrie at the cursor head has become empty after updates.
977    /// If the subtrie's root is [`ArenaSparseNode::EmptyRoot`] (all leaves were removed), the
978    /// child slot is removed from the parent branch entirely, the subtrie is recycled, and
979    /// if the parent is left with a single revealed child, it is collapsed via
980    /// `collapse_branch`.
981    ///
982    /// The subtrie must be the cursor head and its parent the cursor's parent.
983    /// Pops the subtrie entry (propagating leaf count deltas) before returning.
984    #[instrument(
985        level = "trace",
986        target = TRACE_TARGET,
987        skip_all,
988        fields(subtrie_path = ?cursor.head_path()),
989    )]
990    fn maybe_unwrap_subtrie(&mut self, cursor: &mut ArenaCursor) {
991        let subtrie_idx = cursor.head().expect("cursor is non-empty").index;
992
993        let ArenaSparseNode::Subtrie(subtrie) = &self.upper_arena[subtrie_idx] else {
994            return;
995        };
996
997        if !matches!(subtrie.arena[subtrie.root], ArenaSparseNode::EmptyRoot { .. }) {
998            return;
999        }
1000
1001        let child_nibble =
1002            cursor.head_last_nibble().expect("subtrie path must have at least one nibble");
1003        let parent_idx = cursor.parent().expect("cursor has parent").index;
1004
1005        // Pop the subtrie entry before mutating, so collapse_branch sees the parent as
1006        // the cursor head.
1007        cursor.pop(&mut self.upper_arena);
1008
1009        self.recycle_subtrie_from_idx(subtrie_idx);
1010
1011        trace!(target: TRACE_TARGET, "Unwrapping empty subtrie, removing child slot");
1012        *node_state_mut(&mut self.upper_arena, parent_idx) = ArenaSparseNodeState::Dirty;
1013        let parent_branch = branch_data_mut(&mut self.upper_arena, parent_idx);
1014        let child_idx = BranchChildIdx::new(parent_branch.state_mask, child_nibble)
1015            .expect("child nibble not found in parent state_mask");
1016
1017        parent_branch.children.remove(child_idx.get());
1018        parent_branch.unset_child_bit(child_nibble);
1019        // The branch structure changed (child removed), so any cached RLP is stale.
1020        parent_branch.state = parent_branch.state.to_dirty();
1021
1022        self.maybe_collapse_or_remove_branch(cursor);
1023    }
1024
1025    /// Merges buffered updates from a [`ArenaSparseNode::Subtrie`] and drops it.
1026    ///
1027    /// # Panics
1028    ///
1029    /// Panics if `node` is not a `Subtrie`.
1030    fn recycle_subtrie(&mut self, node: ArenaSparseNode) {
1031        let ArenaSparseNode::Subtrie(mut subtrie) = node else {
1032            unreachable!("recycle_subtrie called on non-Subtrie node")
1033        };
1034        Self::merge_subtrie_updates(&mut self.buffers.updates, &mut subtrie.buffers.updates);
1035    }
1036
1037    /// Removes a [`ArenaSparseNode::Subtrie`] from the upper arena at `idx` and recycles it.
1038    fn recycle_subtrie_from_idx(&mut self, idx: Index) {
1039        let node = self.upper_arena.remove(idx).expect("subtrie exists in arena");
1040        self.recycle_subtrie(node);
1041    }
1042
1043    /// Puts a subtrie that was taken for parallel processing back into its upper arena slot.
1044    ///
1045    /// The slot must still hold the [`ArenaSparseNode::TakenSubtrie`] placeholder: indices carry
1046    /// no generation, so a slot that was removed and handed out again would silently be
1047    /// overwritten.
1048    fn restore_taken_subtrie(&mut self, idx: Index, subtrie: Box<ArenaSparseSubtrie>) {
1049        debug_assert!(
1050            matches!(self.upper_arena[idx], ArenaSparseNode::TakenSubtrie),
1051            "taken subtrie slot {idx:?} was removed or reused before restoration",
1052        );
1053        self.upper_arena[idx] = ArenaSparseNode::Subtrie(subtrie);
1054    }
1055
1056    /// Handles cascading structural changes on the branch at the cursor head after a child
1057    /// has been removed.
1058    ///
1059    /// Depending on the remaining child count:
1060    /// - **0 children**: the branch becomes `EmptyRoot` (if root) or is removed from its parent,
1061    ///   cascading upward.
1062    /// - **1 child**: collapses the branch into its sole child, unless that child is a
1063    ///   `TakenSubtrie` (deferred) or blinded. If the remaining child is an empty subtrie, it is
1064    ///   also removed, reducing to the 0-children case.
1065    /// - **2+ children**: nothing to do.
1066    fn maybe_collapse_or_remove_branch(&mut self, cursor: &mut ArenaCursor) {
1067        loop {
1068            let branch_node_idx = cursor.head().expect("cursor is non-empty").index;
1069            let branch_path = cursor.head_path();
1070
1071            // Read-only phase: extract the count and remaining-child info we need before
1072            // mutating. All values here are Copy so the borrow is released.
1073            let Some(branch_child_idx) = branch_idx(&self.upper_arena, branch_node_idx) else {
1074                return;
1075            };
1076            let count = self.upper_arena[branch_child_idx].branch_ref().state_mask.count_bits();
1077
1078            if count >= 2 {
1079                return;
1080            }
1081
1082            if count == 0 {
1083                if branch_node_idx == self.root {
1084                    self.upper_arena[branch_node_idx] =
1085                        ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Dirty };
1086                    if branch_child_idx != branch_node_idx {
1087                        self.upper_arena.remove(branch_child_idx);
1088                    }
1089                    return;
1090                }
1091                // Remove the empty branch from its parent.
1092                let branch_nibble = branch_path.last().expect("non-root branch");
1093                cursor.pop(&mut self.upper_arena);
1094                self.upper_arena.remove(branch_node_idx);
1095                if branch_child_idx != branch_node_idx {
1096                    self.upper_arena.remove(branch_child_idx);
1097                }
1098                let parent_idx = cursor.head().expect("cursor is non-empty").index;
1099                *node_state_mut(&mut self.upper_arena, parent_idx) = ArenaSparseNodeState::Dirty;
1100                let parent_branch = branch_data_mut(&mut self.upper_arena, parent_idx);
1101                let child_idx = BranchChildIdx::new(parent_branch.state_mask, branch_nibble)
1102                    .expect("child nibble not found in parent state_mask");
1103                parent_branch.children.remove(child_idx.get());
1104                parent_branch.unset_child_bit(branch_nibble);
1105                parent_branch.state = parent_branch.state.to_dirty();
1106                continue; // re-check the parent
1107            }
1108
1109            // count == 1 — determine what kind of child remains.
1110            let (remaining_nibble, remaining_child_idx) = {
1111                let b = self.upper_arena[branch_child_idx].branch_ref();
1112                let nibble = b.state_mask.iter().next().expect("branch has at least one child");
1113                (nibble, b.children[0].revealed_index())
1114            };
1115
1116            let Some(child_idx) = remaining_child_idx else {
1117                debug_assert!(false, "single remaining child is blinded — should have been caught by check_subtrie_collapse_needs_proof");
1118                return;
1119            };
1120
1121            if matches!(self.upper_arena[child_idx], ArenaSparseNode::TakenSubtrie) {
1122                // Subtrie hasn't been restored yet; collapse is deferred to the
1123                // post-restore phase.
1124                return;
1125            }
1126
1127            // Check if the remaining child is an empty subtrie that should also be removed.
1128            let is_empty_subtrie = matches!(
1129                &self.upper_arena[child_idx],
1130                ArenaSparseNode::Subtrie(s) if matches!(s.arena[s.root], ArenaSparseNode::EmptyRoot { .. })
1131            );
1132
1133            if is_empty_subtrie {
1134                self.recycle_subtrie_from_idx(child_idx);
1135                *node_state_mut(&mut self.upper_arena, branch_node_idx) =
1136                    ArenaSparseNodeState::Dirty;
1137                let branch = branch_data_mut(&mut self.upper_arena, branch_node_idx);
1138                branch.children.remove(0);
1139                branch.unset_child_bit(remaining_nibble);
1140                branch.state = branch.state.to_dirty();
1141                continue; // now count == 0, will be handled next iteration
1142            }
1143
1144            // Normal collapse: the remaining child is a Leaf, Branch, or non-empty Subtrie.
1145            Self::collapse_branch(
1146                &mut self.upper_arena,
1147                cursor,
1148                &mut self.root,
1149                &mut self.buffers.updates,
1150            );
1151
1152            // After collapse, the remaining child (now at cursor head) may be a
1153            // Subtrie whose path was shortened by the collapsed branch's prefix. Since
1154            // should_be_subtrie requires path_len == UPPER_TRIE_MAX_DEPTH and the collapse
1155            // made the path shorter, the subtrie is no longer eligible — unwrap it.
1156            let child_idx = cursor.head().expect("cursor is non-empty").index;
1157            if let ArenaSparseNode::Subtrie(_) = &self.upper_arena[child_idx] {
1158                let ArenaSparseNode::Subtrie(mut subtrie) =
1159                    mem::replace(&mut self.upper_arena[child_idx], ArenaSparseNode::TakenSubtrie)
1160                else {
1161                    unreachable!()
1162                };
1163                Self::migrate_nodes(
1164                    &mut self.upper_arena,
1165                    &mut subtrie.arena,
1166                    subtrie.root,
1167                    Some(child_idx),
1168                );
1169                Self::merge_subtrie_updates(
1170                    &mut self.buffers.updates,
1171                    &mut subtrie.buffers.updates,
1172                );
1173
1174                // The migrated subtrie root may be a branch whose children now live in
1175                // the upper arena at or beyond the subtrie boundary depth. Re-wrap any
1176                // such children as subtries.
1177                self.maybe_wrap_branch_children(cursor);
1178            }
1179            return;
1180        }
1181    }
1182
1183    /// Merges updates from a subtrie's buffer into the parent's buffer.
1184    /// Both `dst` and `src` must be `Some` when updates are being tracked.
1185    ///
1186    /// Source removals cancel destination insertions (and vice versa) so that
1187    /// updates accumulated across multiple `root()` calls within a single block
1188    /// stay consistent.
1189    fn merge_subtrie_updates(
1190        dst: &mut Option<SparseTrieUpdates>,
1191        src: &mut Option<SparseTrieUpdates>,
1192    ) {
1193        if let Some(dst_updates) = dst.as_mut() {
1194            let src_updates = src.as_mut().expect("updates are enabled");
1195
1196            // Source insertions cancel destination removals.
1197            for path in src_updates.updated_nodes.keys() {
1198                dst_updates.removed_nodes.remove(path);
1199            }
1200            dst_updates.updated_nodes.extend(src_updates.updated_nodes.drain());
1201
1202            // Source removals cancel destination insertions.
1203            for path in &src_updates.removed_nodes {
1204                dst_updates.updated_nodes.remove(path);
1205            }
1206            dst_updates.removed_nodes.extend(src_updates.removed_nodes.drain());
1207        }
1208    }
1209
1210    /// Right-pads a nibble path with zeros and packs it into a [`B256`].
1211    fn nibbles_to_padded_b256(path: &Nibbles) -> B256 {
1212        let mut bytes = [0u8; 32];
1213        path.pack_to(&mut bytes);
1214        B256::from(bytes)
1215    }
1216
1217    /// Returns the [`BranchNodeMasks`] for a branch based on the status of its children.
1218    fn get_branch_masks(arena: &NodeArena, branch: &ArenaSparseNodeBranch) -> BranchNodeMasks {
1219        let mut masks = BranchNodeMasks::default();
1220
1221        for (nibble, child) in branch.child_iter() {
1222            let (hash_bit, tree_bit) = match child.revealed_index() {
1223                Some(child_idx) => {
1224                    let child = &arena[child_idx];
1225                    (
1226                        child.hash_mask_bit(),
1227                        if has_blinded_branch(arena, child_idx) {
1228                            branch.branch_masks.tree_mask.is_bit_set(nibble)
1229                        } else {
1230                            node_tree_mask_bit(arena, child_idx)
1231                        },
1232                    )
1233                }
1234                None => (
1235                    branch.branch_masks.hash_mask.is_bit_set(nibble),
1236                    branch.branch_masks.tree_mask.is_bit_set(nibble),
1237                ),
1238            };
1239
1240            masks.set_child_bits(nibble, hash_bit, tree_bit);
1241        }
1242
1243        masks
1244    }
1245
1246    /// Computes and caches `RlpNode` for all dirty nodes reachable from `root` in `arena`.
1247    ///
1248    /// Uses the cursor's stack to walk dirty branches depth-first. For each branch,
1249    /// children are iterated left-to-right:
1250    /// - Blinded, cached, leaf, and `EmptyRoot` children have their `RlpNode` pushed directly onto
1251    ///   `rlp_node_buf`.
1252    /// - Dirty branch children are pushed onto `stack` and processed recursively first.
1253    ///
1254    /// When a dirty branch child finishes and is popped, the parent resumes iteration after
1255    /// the child's nibble. Once all children of a branch are processed, the branch is encoded
1256    /// via `BranchNodeRef` using the last N entries on `rlp_node_buf`, then replaced with a
1257    /// single result `RlpNode`.
1258    #[instrument(level = "trace", target = TRACE_TARGET, skip_all, fields(base_path = ?base_path), ret)]
1259    fn update_cached_rlp(
1260        arena: &mut NodeArena,
1261        root: Index,
1262        base_path: Nibbles,
1263        buffers: &mut ArenaTrieBuffers,
1264        new_epoch: TrieNodeEpoch,
1265    ) -> RlpNode {
1266        let cursor = &mut buffers.cursor;
1267        let rlp_buf = &mut buffers.rlp_buf;
1268        let rlp_node_buf = &mut buffers.rlp_node_buf;
1269        let updates = &mut buffers.updates;
1270
1271        rlp_node_buf.clear();
1272
1273        // Step 1: Handle trivial roots that don't need the stack-based walk.
1274        // Empty roots and leaves are encoded in place. Already-cached branches need no work.
1275        // Only dirty branches enter the main loop below.
1276        if has_blinded_branch(arena, root) {
1277            Self::encode_blinded_extension(arena, root, rlp_buf, new_epoch);
1278            return node_state_ref(arena, root)
1279                .and_then(ArenaSparseNodeState::cached_rlp_node)
1280                .expect("extension was encoded")
1281                .clone();
1282        }
1283        match &arena[root] {
1284            ArenaSparseNode::EmptyRoot { state } => {
1285                let node_epoch = match state {
1286                    ArenaSparseNodeState::Cached { epoch, .. } => *epoch,
1287                    ArenaSparseNodeState::Revealed => TrieNodeEpoch::UNMODIFIED,
1288                    ArenaSparseNodeState::Dirty => new_epoch,
1289                };
1290                let rlp_node = RlpNode::word_rlp(&EMPTY_ROOT_HASH);
1291                *arena[root].state_mut() =
1292                    ArenaSparseNodeState::Cached { rlp_node: rlp_node.clone(), epoch: node_epoch };
1293                return rlp_node
1294            }
1295            ArenaSparseNode::Leaf { .. } => {
1296                Self::encode_leaf(arena, root, rlp_buf, rlp_node_buf, new_epoch);
1297                return rlp_node_buf.pop().expect("encode_leaf must push an RlpNode");
1298            }
1299            ArenaSparseNode::Branch(_) | ArenaSparseNode::Extension { .. } => {
1300                if let Some(ArenaSparseNodeState::Cached { rlp_node, .. }) =
1301                    node_state_ref(arena, root)
1302                {
1303                    let rlp_node = rlp_node.clone();
1304                    return rlp_node;
1305                }
1306            }
1307            ArenaSparseNode::Subtrie(_) | ArenaSparseNode::TakenSubtrie | ArenaSparseNode::Free => {
1308                unreachable!("Subtrie/TakenSubtrie/Free cannot be a subtrie's root");
1309            }
1310        }
1311
1312        cursor.reset(arena, root, base_path);
1313
1314        // Step 2: Walk dirty branches depth-first using `cursor.next`. Only dirty branches
1315        // are descended into; all other children (leaves, cached branches, blinded, subtries)
1316        // are encoded when their parent branch is popped.
1317        loop {
1318            let result = cursor.next(&mut *arena, |_, node| {
1319                matches!(node, ArenaSparseNode::Branch(_) | ArenaSparseNode::Extension { .. }) &&
1320                    !node.is_cached()
1321            });
1322
1323            match result {
1324                NextResult::Done => break,
1325                NextResult::NonBranch => {
1326                    let idx = cursor.head().expect("cursor is non-empty").index;
1327                    Self::encode_blinded_extension(arena, idx, rlp_buf, new_epoch);
1328                    continue;
1329                }
1330                NextResult::Branch => {}
1331            };
1332
1333            let head_idx = cursor.head().expect("cursor is non-empty").index;
1334            let head_path = cursor.head_path();
1335
1336            // The branch at `head_idx` is exhausted. All its dirty child branches
1337            // have already been encoded and cached. Collect all children's RLP nodes
1338            // and encode the branch.
1339            trace!(
1340                target: TRACE_TARGET,
1341                branch_path = ?head_path,
1342                branch_short_key = ?arena[head_idx].extension_key(),
1343                state_mask = ?branch_data(arena, head_idx).state_mask,
1344                "Calculating branch RlpNode",
1345            );
1346
1347            rlp_node_buf.clear();
1348            // A changed extension key can wrap an unchanged branch whose epoch includes
1349            // modifications to descendants that have since been removed or pruned.
1350            let mut node_epoch = branch_data(arena, head_idx)
1351                .state
1352                .cached_epoch()
1353                .unwrap_or(TrieNodeEpoch::UNMODIFIED);
1354            let state_mask = branch_data(arena, head_idx).state_mask;
1355            for (dense_idx, _nibble) in BranchChildIter::new(state_mask) {
1356                let child = branch_data(arena, head_idx).children[dense_idx];
1357                match child.revealed_index() {
1358                    None => {
1359                        rlp_node_buf.push(arena.blinded(child).clone());
1360                    }
1361                    Some(child_idx) => {
1362                        match &arena[child_idx] {
1363                            ArenaSparseNode::Leaf { .. } => {
1364                                Self::encode_leaf(
1365                                    arena,
1366                                    child_idx,
1367                                    rlp_buf,
1368                                    rlp_node_buf,
1369                                    new_epoch,
1370                                );
1371                            }
1372                            ArenaSparseNode::Branch(child_b) => {
1373                                let ArenaSparseNodeState::Cached { rlp_node, .. } = &child_b.state
1374                                else {
1375                                    panic!("child branch must be cached after DFS");
1376                                };
1377                                let rlp_node = rlp_node.clone();
1378                                rlp_node_buf.push(rlp_node);
1379                            }
1380                            ArenaSparseNode::Extension { state, .. } => {
1381                                let ArenaSparseNodeState::Cached { rlp_node, .. } = state else {
1382                                    panic!("extension must be cached after DFS");
1383                                };
1384                                rlp_node_buf.push(rlp_node.clone());
1385                            }
1386                            ArenaSparseNode::Subtrie(subtrie) => {
1387                                let Some(ArenaSparseNodeState::Cached { rlp_node, .. }) =
1388                                    node_state_ref(&subtrie.arena, subtrie.root)
1389                                else {
1390                                    panic!("subtrie root must be cached");
1391                                };
1392                                rlp_node_buf.push(rlp_node.clone());
1393                            }
1394                            ArenaSparseNode::TakenSubtrie |
1395                            ArenaSparseNode::EmptyRoot { .. } |
1396                            ArenaSparseNode::Free => {
1397                                unreachable!("Unexpected child {:?}", arena[child_idx]);
1398                            }
1399                        }
1400                        let Some(ArenaSparseNodeState::Cached { epoch: child_epoch, .. }) =
1401                            node_state_ref(arena, child_idx)
1402                        else {
1403                            panic!("revealed child must be cached after encoding");
1404                        };
1405                        node_epoch = node_epoch.max(*child_epoch);
1406                    }
1407                }
1408            }
1409
1410            // Encode the branch, optionally wrapping in its parent extension.
1411            let b = branch_data(arena, head_idx);
1412            let short_key = arena[head_idx].extension_key().copied().unwrap_or_default();
1413            let state_mask = b.state_mask;
1414            let prev_branch_masks = b.branch_masks;
1415            let new_branch_masks = Self::get_branch_masks(arena, b);
1416            let was_dirty = matches!(b.state, ArenaSparseNodeState::Dirty);
1417            if was_dirty ||
1418                matches!(node_state_ref(arena, head_idx), Some(ArenaSparseNodeState::Dirty))
1419            {
1420                node_epoch = node_epoch.max(new_epoch);
1421            }
1422
1423            rlp_buf.clear();
1424            let rlp_node = BranchNodeRef::new(rlp_node_buf, state_mask).rlp(rlp_buf);
1425
1426            let branch = branch_data_mut(arena, head_idx);
1427            branch.state =
1428                ArenaSparseNodeState::Cached { rlp_node: rlp_node.clone(), epoch: node_epoch };
1429            branch.branch_masks = new_branch_masks;
1430
1431            let rlp_node = if short_key.is_empty() {
1432                rlp_node
1433            } else {
1434                rlp_buf.clear();
1435                ExtensionNodeRef::new(&short_key, &rlp_node).rlp(rlp_buf)
1436            };
1437
1438            trace!(
1439                target: TRACE_TARGET,
1440                path = ?head_path,
1441                short_key = ?arena[head_idx].short_key(),
1442                children = ?state_mask.iter().zip(rlp_node_buf.iter()).collect::<Vec<_>>(),
1443                rlp_node = ?rlp_node,
1444                "Calculated branch RlpNode",
1445            );
1446
1447            *node_state_mut(arena, head_idx) =
1448                ArenaSparseNodeState::Cached { rlp_node, epoch: node_epoch };
1449
1450            // Record trie updates for dirty branches only.
1451            // Skip the root node (empty logical path) as PST does.
1452            if let Some(trie_updates) = updates.as_mut().filter(|_| was_dirty) {
1453                let mut logical_path = head_path;
1454                logical_path.extend(&short_key);
1455
1456                if !logical_path.is_empty() {
1457                    if !prev_branch_masks.is_empty() && new_branch_masks.is_empty() {
1458                        trie_updates.updated_nodes.remove(&logical_path);
1459                        trie_updates.removed_nodes.insert(logical_path);
1460                    } else if !new_branch_masks.is_empty() {
1461                        let compact = branch_data(arena, head_idx).branch_node_compact(arena);
1462                        trie_updates.updated_nodes.insert(logical_path, compact);
1463                        trie_updates.removed_nodes.remove(&logical_path);
1464                    }
1465                }
1466            }
1467        }
1468
1469        let Some(ArenaSparseNodeState::Cached { rlp_node, .. }) = node_state_ref(arena, root)
1470        else {
1471            panic!("root must be cached after update_cached_rlp");
1472        };
1473        rlp_node.clone()
1474    }
1475
1476    /// Caches an extension without decoding its backing branch.
1477    fn encode_blinded_extension(
1478        arena: &mut NodeArena,
1479        idx: Index,
1480        rlp_buf: &mut Vec<u8>,
1481        new_epoch: TrieNodeEpoch,
1482    ) {
1483        let ArenaSparseNode::Extension { key, child: ExtensionChild::Blinded(rlp_node), state } =
1484            &mut arena[idx]
1485        else {
1486            unreachable!("expected extension with blinded branch")
1487        };
1488        if !matches!(state, ArenaSparseNodeState::Cached { .. }) {
1489            rlp_buf.clear();
1490            let rlp_node = ExtensionNodeRef::new(key, rlp_node).rlp(rlp_buf);
1491            // A deferred collapse can change the key while the backing branch remains opaque.
1492            let epoch = if matches!(state, ArenaSparseNodeState::Dirty) {
1493                new_epoch
1494            } else {
1495                TrieNodeEpoch::UNMODIFIED
1496            };
1497            *state = ArenaSparseNodeState::Cached { rlp_node, epoch };
1498        }
1499    }
1500
1501    /// Immutable traversal to find a leaf value at `full_path` starting from `root` in `arena`.
1502    /// `path_offset` is the number of nibbles already consumed from `full_path`.
1503    fn get_leaf_value_in_arena<'a>(
1504        arena: &'a NodeArena,
1505        mut current: Index,
1506        full_path: &Nibbles,
1507        mut path_offset: usize,
1508    ) -> Option<&'a Vec<u8>> {
1509        loop {
1510            match &arena[current] {
1511                ArenaSparseNode::EmptyRoot { .. } |
1512                ArenaSparseNode::TakenSubtrie |
1513                ArenaSparseNode::Free => return None,
1514                ArenaSparseNode::Leaf { key, value, .. } => {
1515                    let remaining = full_path.slice_unchecked(path_offset, full_path.len());
1516                    return (remaining == *key).then_some(value);
1517                }
1518                ArenaSparseNode::Extension { key, child, .. } => {
1519                    let logical_end = path_offset + key.len();
1520                    if full_path.len() <= logical_end ||
1521                        full_path.slice_unchecked(path_offset, logical_end) != *key
1522                    {
1523                        return None;
1524                    }
1525                    current = child.revealed_index()?;
1526                    path_offset = logical_end;
1527                }
1528                ArenaSparseNode::Branch(b) => {
1529                    if full_path.len() <= path_offset {
1530                        return None;
1531                    }
1532
1533                    let child_nibble = full_path.get_unchecked(path_offset);
1534                    let child_idx = BranchChildIdx::new(b.state_mask, child_nibble)?;
1535                    current = b.children[child_idx].revealed_index()?;
1536                    path_offset += 1;
1537                }
1538                ArenaSparseNode::Subtrie(subtrie) => {
1539                    return Self::get_leaf_value_in_arena(
1540                        &subtrie.arena,
1541                        subtrie.root,
1542                        full_path,
1543                        path_offset,
1544                    );
1545                }
1546            }
1547        }
1548    }
1549
1550    /// Immutable traversal from the given root in `arena`, following `full_path` to find a leaf.
1551    /// Returns whether the leaf exists or not, or an error if a blinded node is encountered or
1552    /// the value doesn't match.
1553    fn find_leaf_in_arena(
1554        arena: &NodeArena,
1555        mut current: Index,
1556        full_path: &Nibbles,
1557        mut path_offset: usize,
1558        expected_value: Option<&Vec<u8>>,
1559    ) -> Result<LeafLookup, LeafLookupError> {
1560        loop {
1561            match &arena[current] {
1562                ArenaSparseNode::EmptyRoot { .. } |
1563                ArenaSparseNode::TakenSubtrie |
1564                ArenaSparseNode::Free => {
1565                    return Ok(LeafLookup::NonExistent);
1566                }
1567                ArenaSparseNode::Leaf { key, value, .. } => {
1568                    let remaining = full_path.slice(path_offset..);
1569                    if remaining != *key {
1570                        return Ok(LeafLookup::NonExistent);
1571                    }
1572                    if let Some(expected) = expected_value &&
1573                        *expected != *value
1574                    {
1575                        return Err(LeafLookupError::ValueMismatch {
1576                            path: *full_path,
1577                            expected: Some(expected.clone()),
1578                            actual: value.clone(),
1579                        });
1580                    }
1581                    return Ok(LeafLookup::Exists);
1582                }
1583                ArenaSparseNode::Extension { key, child, .. } => {
1584                    let logical_end = path_offset + key.len();
1585                    if full_path.len() <= logical_end ||
1586                        full_path.slice(path_offset..logical_end) != *key
1587                    {
1588                        return Ok(LeafLookup::NonExistent);
1589                    }
1590                    match child {
1591                        ExtensionChild::Revealed(index) => current = *index,
1592                        ExtensionChild::Blinded(rlp_node) => {
1593                            return Err(LeafLookupError::BlindedNode {
1594                                path: full_path.slice(..logical_end),
1595                                hash: rlp_node
1596                                    .as_hash()
1597                                    .unwrap_or_else(|| keccak256(rlp_node.as_slice())),
1598                            })
1599                        }
1600                    }
1601                    path_offset = logical_end;
1602                }
1603                ArenaSparseNode::Branch(b) => {
1604                    if full_path.len() <= path_offset {
1605                        return Ok(LeafLookup::NonExistent);
1606                    }
1607
1608                    let child_nibble = full_path.get_unchecked(path_offset);
1609                    let Some(child_idx) = BranchChildIdx::new(b.state_mask, child_nibble) else {
1610                        return Ok(LeafLookup::NonExistent);
1611                    };
1612
1613                    let child = b.children[child_idx];
1614                    match child.revealed_index() {
1615                        None => {
1616                            let rlp_node = arena.blinded(child);
1617                            let hash = rlp_node
1618                                .as_hash()
1619                                .unwrap_or_else(|| keccak256(rlp_node.as_slice()));
1620                            let mut blinded_path = full_path.slice(..path_offset);
1621                            blinded_path.push_unchecked(child_nibble);
1622                            return Err(LeafLookupError::BlindedNode { path: blinded_path, hash });
1623                        }
1624                        Some(child_idx) => {
1625                            current = child_idx;
1626                            path_offset += 1;
1627                        }
1628                    }
1629                }
1630                ArenaSparseNode::Subtrie(subtrie) => {
1631                    return Self::find_leaf_in_arena(
1632                        &subtrie.arena,
1633                        subtrie.root,
1634                        full_path,
1635                        path_offset,
1636                        expected_value,
1637                    );
1638                }
1639            }
1640        }
1641    }
1642
1643    /// Encodes a leaf node's RLP and pushes it onto `rlp_node_buf`.
1644    ///
1645    /// If the leaf is already cached, its existing `RlpNode` is reused.
1646    fn encode_leaf(
1647        arena: &mut NodeArena,
1648        idx: Index,
1649        rlp_buf: &mut Vec<u8>,
1650        rlp_node_buf: &mut Vec<RlpNode>,
1651        new_epoch: TrieNodeEpoch,
1652    ) {
1653        let (key, value, state) = match &arena[idx] {
1654            ArenaSparseNode::Leaf { key, value, state } => (key, value, state),
1655            _ => unreachable!("encode_leaf called on non-Leaf node"),
1656        };
1657
1658        let epoch = match state {
1659            ArenaSparseNodeState::Cached { rlp_node, .. } => {
1660                rlp_node_buf.push(rlp_node.clone());
1661                return;
1662            }
1663            ArenaSparseNodeState::Revealed => TrieNodeEpoch::UNMODIFIED,
1664            ArenaSparseNodeState::Dirty => new_epoch,
1665        };
1666
1667        rlp_buf.clear();
1668        let rlp_node = LeafNodeRef { key, value }.rlp(rlp_buf);
1669
1670        *arena[idx].state_mut() =
1671            ArenaSparseNodeState::Cached { rlp_node: rlp_node.clone(), epoch };
1672        rlp_node_buf.push(rlp_node);
1673    }
1674
1675    /// Creates a new leaf and a new branch that splits an existing child from the new leaf at
1676    /// a divergence point. Returns the index of the new branch.
1677    ///
1678    /// `new_leaf_path` is the full remaining path for the new leaf (relative to the split
1679    /// point's parent).
1680    ///
1681    /// The old child's key (leaf) or extension key is truncated to the suffix after the
1682    /// divergence nibble and its state is set to dirty.
1683    ///
1684    /// The top of `stack` must be the leaf or branch being split. The top of stack will be the
1685    /// newly created branch once this returns.
1686    /// Returns `true` if the existing node was not already dirty (i.e., the split newly dirtied
1687    /// it).
1688    fn split_and_insert_leaf(
1689        arena: &mut NodeArena,
1690        cursor: &mut ArenaCursor,
1691        root: &mut Index,
1692        new_leaf_path: Nibbles,
1693        value: &[u8],
1694    ) -> bool {
1695        let old_child_idx = cursor.head().expect("cursor must have head").index;
1696        let old_child_short_key = arena[old_child_idx].short_key().expect("top of stack is a leaf");
1697        let diverge_len = new_leaf_path.common_prefix_length(old_child_short_key);
1698
1699        trace!(
1700            target: TRACE_TARGET,
1701            path = ?cursor.head_path(),
1702            ?new_leaf_path,
1703            ?old_child_short_key,
1704            diverge_len,
1705            "Splitting node and inserting new leaf",
1706        );
1707
1708        let old_child_nibble = old_child_short_key.get_unchecked(diverge_len);
1709        let old_child_suffix = old_child_short_key.slice(diverge_len + 1..);
1710
1711        // Truncate the old child's key/extension key and mark it dirty.
1712        // Track whether the existing node was not already dirty (a leaf that becomes newly dirty).
1713        let old_child = mem::replace(&mut arena[old_child_idx], ArenaSparseNode::TakenSubtrie);
1714        let newly_dirtied_existing = match old_child {
1715            ArenaSparseNode::Leaf { value, state, .. } => {
1716                let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
1717                arena[old_child_idx] = ArenaSparseNode::Leaf {
1718                    key: old_child_suffix,
1719                    value,
1720                    state: ArenaSparseNodeState::Dirty,
1721                };
1722                was_clean
1723            }
1724            ArenaSparseNode::Extension { child: ExtensionChild::Revealed(child), .. } => {
1725                if old_child_suffix.is_empty() {
1726                    let branch = arena.remove(child).expect("extension child exists");
1727                    arena[old_child_idx] = branch;
1728                    *arena[old_child_idx].state_mut() = ArenaSparseNodeState::Dirty;
1729                } else {
1730                    arena[old_child_idx] = ArenaSparseNode::Extension {
1731                        key: old_child_suffix,
1732                        child: ExtensionChild::Revealed(child),
1733                        state: ArenaSparseNodeState::Dirty,
1734                    };
1735                    *arena[child].state_mut() = ArenaSparseNodeState::Dirty;
1736                }
1737                // Branches don't contribute to num_dirty_leaves.
1738                false
1739            }
1740            _ => unreachable!("split_and_insert_leaf called on non-Leaf/Extension node"),
1741        };
1742
1743        let short_key = new_leaf_path.slice(..diverge_len);
1744        let new_leaf_nibble = new_leaf_path.get_unchecked(diverge_len);
1745        debug_assert_ne!(old_child_nibble, new_leaf_nibble);
1746
1747        let new_leaf_idx = arena.insert(ArenaSparseNode::Leaf {
1748            state: ArenaSparseNodeState::Dirty,
1749            key: new_leaf_path.slice(diverge_len + 1..),
1750            value: value.to_vec(),
1751        });
1752
1753        let (first_nibble, first_child, second_nibble, second_child) =
1754            if old_child_nibble < new_leaf_nibble {
1755                (old_child_nibble, old_child_idx, new_leaf_nibble, new_leaf_idx)
1756            } else {
1757                (new_leaf_nibble, new_leaf_idx, old_child_nibble, old_child_idx)
1758            };
1759
1760        let state_mask = TrieMask::from_nibble(first_nibble) | TrieMask::from_nibble(second_nibble);
1761        let mut children = SmallVec::new();
1762        children.push(BranchChild::revealed(first_child));
1763        children.push(BranchChild::revealed(second_child));
1764
1765        let branch_child_idx = arena.insert(ArenaSparseNode::Branch(ArenaSparseNodeBranch {
1766            state: ArenaSparseNodeState::Dirty,
1767            children,
1768            state_mask,
1769            branch_masks: BranchNodeMasks::default(),
1770        }));
1771        let new_branch_idx = if short_key.is_empty() {
1772            branch_child_idx
1773        } else {
1774            arena.insert(ArenaSparseNode::Extension {
1775                key: short_key,
1776                child: ExtensionChild::Revealed(branch_child_idx),
1777                state: ArenaSparseNodeState::Dirty,
1778            })
1779        };
1780
1781        cursor.replace_head_index(arena, root, new_branch_idx);
1782        newly_dirtied_existing
1783    }
1784
1785    /// Performs a leaf upsert using a pre-computed [`SeekResult`] from
1786    /// [`ArenaCursor::seek`].
1787    ///
1788    /// Handles three cases based on `find_result`:
1789    /// 1. `RevealedLeaf` — the cursor head is a leaf; update in place or split into a branch.
1790    /// 2. Diverged — the path diverges within an extension key, split it.
1791    /// 3. `NoChild` — the target nibble has no child, insert a new leaf.
1792    ///
1793    /// The caller must handle [`SeekResult::Blinded`] and
1794    /// [`SeekResult::RevealedSubtrie`] before calling this function.
1795    /// The cursor must be non-empty when called.
1796    ///
1797    /// Returns an [`UpsertLeafResult`] and [`SubtrieCounterDeltas`] so the caller can maintain
1798    /// aggregate counters and decide whether to wrap the result as a subtrie.
1799    #[instrument(level = "trace", target = TRACE_TARGET, skip_all, fields(full_path = ?full_path))]
1800    fn upsert_leaf(
1801        arena: &mut NodeArena,
1802        cursor: &mut ArenaCursor,
1803        root: &mut Index,
1804        full_path: &Nibbles,
1805        value: &[u8],
1806        find_result: SeekResult,
1807    ) -> (UpsertLeafResult, SubtrieCounterDeltas) {
1808        trace!(target: TRACE_TARGET, ?find_result, "Upserting leaf");
1809        let head = cursor.head().expect("cursor is non-empty");
1810
1811        match find_result {
1812            SeekResult::Blinded => {
1813                unreachable!("Blinded case must be handled by caller")
1814            }
1815            SeekResult::EmptyRoot => {
1816                let head_idx = head.index;
1817                arena[head_idx] = ArenaSparseNode::Leaf {
1818                    state: ArenaSparseNodeState::Dirty,
1819                    key: full_path.slice(cursor.head_path_len()..),
1820                    value: value.to_vec(),
1821                };
1822                (
1823                    UpsertLeafResult::NewLeaf,
1824                    SubtrieCounterDeltas { num_leaves_delta: 1, num_dirty_leaves_delta: 1 },
1825                )
1826            }
1827            SeekResult::RevealedLeaf => {
1828                // RevealedLeaf guarantees the leaf's full path matches the target exactly.
1829                let head_idx = head.index;
1830                let was_clean =
1831                    if let ArenaSparseNode::Leaf { value: v, state, .. } = &mut arena[head_idx] {
1832                        v.clear();
1833                        v.extend_from_slice(value);
1834                        let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
1835                        *state = ArenaSparseNodeState::Dirty;
1836                        was_clean
1837                    } else {
1838                        unreachable!("RevealedLeaf but cursor head is not a leaf")
1839                    };
1840                (
1841                    UpsertLeafResult::Updated,
1842                    SubtrieCounterDeltas {
1843                        num_leaves_delta: 0,
1844                        num_dirty_leaves_delta: was_clean as i64,
1845                    },
1846                )
1847            }
1848            SeekResult::Diverged => {
1849                let full_path_from_head = full_path.slice(cursor.head_path_len()..);
1850
1851                let split_dirtied_existing =
1852                    Self::split_and_insert_leaf(arena, cursor, root, full_path_from_head, value);
1853
1854                let result = if cursor.depth() >= 1 {
1855                    UpsertLeafResult::NewChild
1856                } else {
1857                    UpsertLeafResult::NewLeaf
1858                };
1859                (
1860                    result,
1861                    SubtrieCounterDeltas {
1862                        num_leaves_delta: 1,
1863                        num_dirty_leaves_delta: 1 + split_dirtied_existing as i64,
1864                    },
1865                )
1866            }
1867            SeekResult::NoChild { child_nibble } => {
1868                let head_idx = head.index;
1869
1870                let leaf_key = full_path.slice(cursor.head_logical_branch_path_len(arena) + 1..);
1871                let new_leaf = arena.insert(ArenaSparseNode::Leaf {
1872                    state: ArenaSparseNodeState::Dirty,
1873                    key: leaf_key,
1874                    value: value.to_vec(),
1875                });
1876
1877                *node_state_mut(arena, head_idx) = ArenaSparseNodeState::Dirty;
1878                let branch = branch_data_mut(arena, head_idx);
1879                branch.set_child(child_nibble, BranchChild::revealed(new_leaf));
1880
1881                // Re-seek to position the cursor on the newly inserted leaf.
1882                cursor.seek(arena, full_path);
1883
1884                (
1885                    UpsertLeafResult::NewChild,
1886                    SubtrieCounterDeltas { num_leaves_delta: 1, num_dirty_leaves_delta: 1 },
1887                )
1888            }
1889            SeekResult::RevealedSubtrie => {
1890                unreachable!("RevealedSubtrie must be handled by caller")
1891            }
1892        }
1893    }
1894
1895    /// Removes a leaf node from the trie using a pre-computed [`SeekResult`] from
1896    /// [`ArenaCursor::seek`].
1897    ///
1898    /// Only the `RevealedLeaf` case performs a removal — the leaf must exist and its full path
1899    /// must match `full_path`. All other cases (`Diverged`, `NoChild`) are no-ops since the leaf
1900    /// doesn't exist at that path.
1901    ///
1902    /// When removing a leaf from a branch, if the branch is left with only one remaining child,
1903    /// the branch is collapsed: the remaining child absorbs the extension key and child's nibble
1904    /// as a prefix to its own key or extension key, and replaces the branch in the parent.
1905    /// If the remaining child is blinded, the collapse cannot proceed and a
1906    /// [`RemoveLeafResult::NeedsProof`] is returned so the caller can request a proof.
1907    ///
1908    /// The caller must handle [`SeekResult::Blinded`] and
1909    /// [`SeekResult::RevealedSubtrie`] before calling this function.
1910    fn remove_leaf(
1911        arena: &mut NodeArena,
1912        cursor: &mut ArenaCursor,
1913        root: &mut Index,
1914        key: B256,
1915        full_path: &Nibbles,
1916        find_result: SeekResult,
1917        updates: &mut Option<SparseTrieUpdates>,
1918    ) -> (RemoveLeafResult, SubtrieCounterDeltas) {
1919        match find_result {
1920            SeekResult::Blinded | SeekResult::RevealedSubtrie => {
1921                unreachable!("Blinded/RevealedSubtrie must be handled by caller")
1922            }
1923            SeekResult::EmptyRoot | SeekResult::Diverged | SeekResult::NoChild { .. } => {
1924                (RemoveLeafResult::NotFound, SubtrieCounterDeltas::default())
1925            }
1926            SeekResult::RevealedLeaf => {
1927                // RevealedLeaf guarantees the leaf's full path matches the target exactly.
1928                let head_idx = cursor.head().expect("cursor is non-empty").index;
1929                let head_path = cursor.head_path();
1930
1931                trace!(
1932                    target: TRACE_TARGET,
1933                    path = ?head_path,
1934                    ?full_path,
1935                    "Removing leaf",
1936                );
1937
1938                // Before mutating, check if removing this leaf would leave the parent
1939                // branch with a single blinded sibling (requiring a proof to collapse).
1940                if let Some(parent_entry) = cursor.parent() {
1941                    let parent_idx = parent_entry.index;
1942                    let child_nibble = head_path.last().expect("non-root leaf");
1943                    let parent_branch = branch_data(arena, parent_idx);
1944
1945                    if parent_branch.state_mask.count_bits() == 2 &&
1946                        child_needs_collapse_proof(
1947                            arena,
1948                            parent_branch.sibling_child(child_nibble),
1949                        )
1950                    {
1951                        let sibling_nibble = parent_branch
1952                            .state_mask
1953                            .iter()
1954                            .find(|&n| n != child_nibble)
1955                            .expect("branch has two children");
1956                        let mut sibling_path = cursor.parent_logical_branch_path(arena);
1957                        sibling_path.push_unchecked(sibling_nibble);
1958                        extend_blinded_branch_path(
1959                            arena,
1960                            parent_branch.sibling_child(child_nibble),
1961                            &mut sibling_path,
1962                        );
1963                        trace!(target: TRACE_TARGET, ?full_path, ?sibling_path, "Removal would collapse branch onto blinded sibling, requesting proof");
1964                        #[cfg(all(feature = "fuzz", reth_sparse_trie_coverage))]
1965                        observe_proof_target(
1966                            arena,
1967                            Some((parent_idx, cursor.parent_logical_branch_path(arena).len())),
1968                            &sibling_path,
1969                            &[],
1970                        );
1971                        return (
1972                            RemoveLeafResult::NeedsProof {
1973                                key,
1974                                proof_key: Self::nibbles_to_padded_b256(&sibling_path),
1975                                parent: ProofV2TargetParent::new(
1976                                    cursor.parent_logical_branch_path(arena).len(),
1977                                ),
1978                            },
1979                            SubtrieCounterDeltas::default(),
1980                        );
1981                    }
1982                }
1983
1984                // Check if the removed leaf was dirty before removing it.
1985                let removed_was_dirty =
1986                    matches!(arena[head_idx].state_ref(), Some(ArenaSparseNodeState::Dirty));
1987
1988                if cursor.depth() == 0 {
1989                    // The leaf is the root — replace with EmptyRoot and reset the cursor
1990                    // so subsequent iterations can call seek normally.
1991                    arena.remove(head_idx);
1992                    *root = arena
1993                        .insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Dirty });
1994                    cursor.reset(arena, *root, head_path);
1995                    return (
1996                        RemoveLeafResult::Removed,
1997                        SubtrieCounterDeltas {
1998                            num_leaves_delta: -1,
1999                            num_dirty_leaves_delta: -(removed_was_dirty as i64),
2000                        },
2001                    );
2002                }
2003
2004                // Pop the leaf entry, propagating dirty state to the parent.
2005                cursor.pop(arena);
2006
2007                // The parent must be a branch. Remove the leaf from it.
2008                let parent_entry = cursor.head().expect("cursor is non-empty");
2009                let parent_idx = parent_entry.index;
2010                let child_nibble = head_path.last().expect("non-root leaf");
2011
2012                // Remove the leaf from the arena and from the parent's children.
2013                arena.remove(head_idx);
2014                *node_state_mut(arena, parent_idx) = ArenaSparseNodeState::Dirty;
2015                let parent_branch = branch_data_mut(arena, parent_idx);
2016                parent_branch.remove_child(child_nibble);
2017
2018                // If the branch now has only one child, collapse it. The blinded sibling
2019                // case was already handled above before any mutations.
2020                let collapse_dirtied_leaf = if parent_branch.state_mask.count_bits() == 1 {
2021                    Self::collapse_branch(arena, cursor, root, updates)
2022                } else {
2023                    false
2024                };
2025                (
2026                    RemoveLeafResult::Removed,
2027                    SubtrieCounterDeltas {
2028                        num_leaves_delta: -1,
2029                        num_dirty_leaves_delta: (collapse_dirtied_leaf as i64) -
2030                            (removed_was_dirty as i64),
2031                    },
2032                )
2033            }
2034        }
2035    }
2036
2037    /// Checks whether a subtrie receiving only removals would cause its parent branch to collapse
2038    /// onto a single blinded sibling. If so, returns the proof needed to reveal that blinded
2039    /// sibling so the caller can request it and skip the subtrie's updates.
2040    ///
2041    /// Returns `Some(proof)` for the blinded sibling when the edge-case applies, `None` otherwise.
2042    fn check_subtrie_collapse_needs_proof(
2043        arena: &NodeArena,
2044        cursor: &ArenaCursor,
2045        subtrie_updates: &[(B256, Nibbles, LeafUpdate)],
2046    ) -> Option<ArenaRequiredProof> {
2047        let num_removals = subtrie_updates
2048            .iter()
2049            .filter(|(_, _, u)| matches!(u, LeafUpdate::Changed(v) if v.is_empty()))
2050            .count() as u64;
2051
2052        // Touched is a no-op that doesn't alter trie structure, so it must be
2053        // excluded when deciding whether "all updates are removals". This mirrors
2054        // the `all_removals` / `might_empty_subtrie` filter in `update_leaves`.
2055        // Without this, a batch of removals + Touched entries
2056        // would fail the `num_removals != num_changed` check, skip the proof
2057        // request for the blinded sibling, and later panic in
2058        // `maybe_collapse_or_remove_branch` when the subtrie empties inline.
2059        let num_changed = subtrie_updates.iter().filter(|(_, _, u)| u.is_changed()).count() as u64;
2060
2061        if num_removals == 0 || num_removals != num_changed {
2062            return None;
2063        }
2064
2065        // The subtrie is the cursor head; its parent is the cursor's parent.
2066        let subtrie_entry = cursor.head()?;
2067        let subtrie_num_leaves = match &arena[subtrie_entry.index] {
2068            ArenaSparseNode::Subtrie(s) => s.num_leaves,
2069            _ => return None,
2070        };
2071        if num_removals < subtrie_num_leaves {
2072            return None;
2073        }
2074
2075        let child_nibble =
2076            cursor.head_last_nibble().expect("subtrie path must have at least one nibble");
2077
2078        let parent_entry = cursor.parent()?;
2079        let parent_branch = branch_data(arena, parent_entry.index);
2080        if parent_branch.state_mask.count_bits() != 2 {
2081            return None;
2082        }
2083
2084        if !child_needs_collapse_proof(arena, parent_branch.sibling_child(child_nibble)) {
2085            return None;
2086        }
2087
2088        let sibling_nibble = parent_branch
2089            .state_mask
2090            .iter()
2091            .find(|&n| n != child_nibble)
2092            .expect("branch has two children");
2093        let mut sibling_path = cursor.parent_logical_branch_path(arena);
2094        sibling_path.push_unchecked(sibling_nibble);
2095        extend_blinded_branch_path(
2096            arena,
2097            parent_branch.sibling_child(child_nibble),
2098            &mut sibling_path,
2099        );
2100
2101        #[cfg(all(feature = "fuzz", reth_sparse_trie_coverage))]
2102        observe_proof_target(
2103            arena,
2104            Some((parent_entry.index, cursor.parent_logical_branch_path(arena).len())),
2105            &sibling_path,
2106            &[],
2107        );
2108        Some(ArenaRequiredProof {
2109            key: Self::nibbles_to_padded_b256(&sibling_path),
2110            parent: ProofV2TargetParent::new(cursor.parent_logical_branch_path(arena).len()),
2111        })
2112    }
2113
2114    /// Collapses a branch node that has exactly one remaining revealed child. The branch's
2115    /// extension key, the remaining child's nibble, and the child's own key or extension key are
2116    /// concatenated to form the child's new key or extension key. The child then replaces the
2117    /// branch in the grandparent (or becomes the new root).
2118    ///
2119    /// The caller must verify that the remaining child is not blinded before calling this function.
2120    ///
2121    /// The branch being collapsed must be the current cursor head. The cursor head will be
2122    /// replaced with the remaining child which has taken its place.
2123    /// Returns `true` if the collapse dirtied a surviving leaf that was not already dirty.
2124    fn collapse_branch(
2125        arena: &mut NodeArena,
2126        cursor: &mut ArenaCursor,
2127        root: &mut Index,
2128        updates: &mut Option<SparseTrieUpdates>,
2129    ) -> bool {
2130        let branch_node_idx = cursor.head().expect("cursor is non-empty").index;
2131        let branch_child_idx = branch_idx(arena, branch_node_idx).expect("cursor head is a branch");
2132        let branch_path = cursor.head_path();
2133        let branch = arena[branch_child_idx].branch_ref();
2134        let remaining_nibble =
2135            branch.state_mask.iter().next().expect("branch has at least one child");
2136        let branch_short_key = arena[branch_node_idx].extension_key().copied().unwrap_or_default();
2137
2138        debug_assert_eq!(
2139            branch.state_mask.count_bits(),
2140            1,
2141            "collapse_branch requires exactly 1 child"
2142        );
2143        debug_assert!(
2144            !branch.children[0].is_blinded(),
2145            "collapse_branch called with a blinded remaining child"
2146        );
2147
2148        trace!(
2149            target: TRACE_TARGET,
2150            path = ?branch_path,
2151            short_key = ?branch_short_key,
2152            branch_masks = ?branch.branch_masks,
2153            ?remaining_nibble,
2154            "Collapsing single-child branch",
2155        );
2156
2157        // Record the collapsed branch's logical path for trie update tracking if it
2158        // was previously persisted in the DB trie.
2159        if let Some(trie_updates) = updates.as_mut() &&
2160            !branch.branch_masks.is_empty()
2161        {
2162            let logical_path = cursor.head_logical_branch_path(arena);
2163            if !logical_path.is_empty() {
2164                trie_updates.updated_nodes.remove(&logical_path);
2165                trie_updates.removed_nodes.insert(logical_path);
2166            }
2167        }
2168
2169        // Build the prefix: extension key + remaining child's nibble.
2170        let mut prefix = branch_short_key;
2171        prefix.push_unchecked(remaining_nibble);
2172
2173        let child_idx = branch.children[0].revealed_index().expect("remaining child is revealed");
2174
2175        // Prepend the prefix to the child's key or extension key and mark dirty.
2176        // Track whether a leaf was newly dirtied by this collapse.
2177        let child = mem::replace(&mut arena[child_idx], ArenaSparseNode::TakenSubtrie);
2178        let (replacement_idx, newly_dirtied_leaf) = match child {
2179            ArenaSparseNode::Leaf { key, value, state } => {
2180                let mut new_key = prefix;
2181                new_key.extend(&key);
2182                let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
2183                arena[child_idx] = ArenaSparseNode::Leaf {
2184                    key: new_key,
2185                    state: ArenaSparseNodeState::Dirty,
2186                    value,
2187                };
2188                (child_idx, was_clean)
2189            }
2190            ArenaSparseNode::Extension { key, child, .. } => {
2191                let mut new_key = prefix;
2192                new_key.extend(&key);
2193                if let Some(index) = child.revealed_index() {
2194                    *arena[index].state_mut() = ArenaSparseNodeState::Dirty;
2195                }
2196                arena[child_idx] = ArenaSparseNode::Extension {
2197                    key: new_key,
2198                    child,
2199                    state: ArenaSparseNodeState::Dirty,
2200                };
2201                (child_idx, false)
2202            }
2203            ArenaSparseNode::Branch(branch) => {
2204                let new_branch_idx = arena.insert(ArenaSparseNode::Branch(branch));
2205                *arena[new_branch_idx].state_mut() = ArenaSparseNodeState::Dirty;
2206                arena[child_idx] = ArenaSparseNode::Extension {
2207                    key: prefix,
2208                    child: ExtensionChild::Revealed(new_branch_idx),
2209                    state: ArenaSparseNodeState::Dirty,
2210                };
2211                (child_idx, false)
2212            }
2213            ArenaSparseNode::Subtrie(mut subtrie) => {
2214                subtrie.path = branch_path;
2215                let root = subtrie.root;
2216                let root_node =
2217                    mem::replace(&mut subtrie.arena[root], ArenaSparseNode::TakenSubtrie);
2218                match root_node {
2219                    ArenaSparseNode::Branch(branch) => {
2220                        let child = subtrie.arena.insert(ArenaSparseNode::Branch(branch));
2221                        subtrie.arena[root] = ArenaSparseNode::Extension {
2222                            key: prefix,
2223                            child: ExtensionChild::Revealed(child),
2224                            state: ArenaSparseNodeState::Dirty,
2225                        };
2226                        *subtrie.arena[child].state_mut() = ArenaSparseNodeState::Dirty;
2227                    }
2228                    ArenaSparseNode::Extension { key, child, .. } => {
2229                        let mut new_key = prefix;
2230                        new_key.extend(&key);
2231                        if let Some(index) = child.revealed_index() {
2232                            *subtrie.arena[index].state_mut() = ArenaSparseNodeState::Dirty;
2233                        }
2234                        subtrie.arena[root] = ArenaSparseNode::Extension {
2235                            key: new_key,
2236                            child,
2237                            state: ArenaSparseNodeState::Dirty,
2238                        };
2239                    }
2240                    ArenaSparseNode::Leaf { key, value, state } => {
2241                        let mut new_key = prefix;
2242                        new_key.extend(&key);
2243                        let was_clean = !matches!(state, ArenaSparseNodeState::Dirty);
2244                        subtrie.arena[root] = ArenaSparseNode::Leaf {
2245                            key: new_key,
2246                            value,
2247                            state: ArenaSparseNodeState::Dirty,
2248                        };
2249                        if was_clean {
2250                            subtrie.num_dirty_leaves += 1;
2251                        }
2252                    }
2253                    _ => {
2254                        unreachable!("subtrie root must be a Branch or Leaf during collapse_branch")
2255                    }
2256                }
2257                arena[child_idx] = ArenaSparseNode::Subtrie(subtrie);
2258                (child_idx, false)
2259            }
2260            _ => unreachable!("remaining child must be Leaf, Branch, Extension, or Subtrie"),
2261        };
2262
2263        // Replace the branch with the remaining child in the grandparent (or root).
2264        cursor.replace_head_index(arena, root, replacement_idx);
2265
2266        // Free the collapsed branch.
2267        arena.remove(branch_node_idx);
2268        if branch_node_idx != branch_child_idx {
2269            arena.remove(branch_child_idx);
2270        }
2271        newly_dirtied_leaf
2272    }
2273
2274    /// Counts the total leaves and dirty leaves in a subtree rooted at `idx`.
2275    fn count_leaves_and_dirty(arena: &NodeArena, idx: Index) -> (u64, u64) {
2276        match &arena[idx] {
2277            ArenaSparseNode::Leaf { state, .. } => {
2278                let dirty = matches!(state, ArenaSparseNodeState::Dirty) as u64;
2279                (1, dirty)
2280            }
2281            ArenaSparseNode::Branch(b) => {
2282                let mut leaves = 0u64;
2283                let mut dirty = 0u64;
2284                for c in &b.children {
2285                    if let Some(child_idx) = c.revealed_index() {
2286                        let (l, d) = Self::count_leaves_and_dirty(arena, child_idx);
2287                        leaves += l;
2288                        dirty += d;
2289                    }
2290                }
2291                (leaves, dirty)
2292            }
2293            ArenaSparseNode::Extension { child: ExtensionChild::Revealed(child), .. } => {
2294                Self::count_leaves_and_dirty(arena, *child)
2295            }
2296            _ => (0, 0),
2297        }
2298    }
2299
2300    /// Asserts that every node in the upper arena satisfies the subtrie structure invariant:
2301    /// - Nodes at `UPPER_TRIE_MAX_DEPTH` path length must be `Subtrie` (or `TakenSubtrie`).
2302    /// - Nodes at other depths must NOT be `Subtrie`.
2303    ///
2304    /// Uses the cursor to DFS the upper arena, checking each visited node's path length.
2305    #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
2306    #[cfg(all(debug_assertions, not(feature = "fuzz")))]
2307    fn debug_assert_subtrie_structure(&mut self) {
2308        let mut cursor = mem::take(&mut self.buffers.cursor);
2309        cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2310
2311        loop {
2312            let result = cursor.next(&mut self.upper_arena, |_, _| true);
2313            match result {
2314                NextResult::Done => break,
2315                NextResult::NonBranch | NextResult::Branch => {
2316                    let path_len = cursor.head_path_len();
2317                    let node = &self.upper_arena[cursor.head().expect("cursor is non-empty").index];
2318
2319                    if Self::should_be_subtrie(path_len) {
2320                        debug_assert!(
2321                            matches!(
2322                                node,
2323                                ArenaSparseNode::Subtrie(_) | ArenaSparseNode::TakenSubtrie
2324                            ),
2325                            "node at path_len={path_len} should be a Subtrie but is {node:?}",
2326                        );
2327                    } else {
2328                        debug_assert!(
2329                            !matches!(node, ArenaSparseNode::Subtrie(_)),
2330                            "node at path_len={path_len} should NOT be a Subtrie but is",
2331                        );
2332                    }
2333                }
2334            }
2335        }
2336
2337        self.buffers.cursor = cursor;
2338    }
2339
2340    /// Recursively migrates all nodes from `src` into `dst`, starting at `src_idx`.
2341    /// Branch children's `Revealed` indices are remapped to the new `dst` indices during
2342    /// the migration.
2343    ///
2344    /// If `dst_slot` is `Some(idx)`, the node at `src_idx` is placed into `dst[idx]`
2345    /// (overwriting); otherwise a new slot is allocated. Returns the `dst` index of the
2346    /// migrated node.
2347    fn migrate_nodes(
2348        dst: &mut NodeArena,
2349        src: &mut NodeArena,
2350        src_idx: Index,
2351        dst_slot: Option<Index>,
2352    ) -> Index {
2353        let mut node = src.remove(src_idx).expect("node exists in source arena");
2354
2355        // Recursively migrate children first so their new indices are known.
2356        Self::migrate_children(dst, src, &mut node);
2357
2358        if let Some(slot) = dst_slot {
2359            dst[slot] = node;
2360            slot
2361        } else {
2362            dst.insert(node)
2363        }
2364    }
2365
2366    /// Moves a node's children from `src` to `dst`: revealed children are migrated recursively
2367    /// with [`Self::migrate_nodes`], blinded children have their RLP moved into `dst`'s side
2368    /// table. `node` must already be detached from `src`.
2369    fn migrate_children(dst: &mut NodeArena, src: &mut NodeArena, node: &mut ArenaSparseNode) {
2370        match node {
2371            ArenaSparseNode::Extension { child: ExtensionChild::Revealed(child), .. } => {
2372                *child = Self::migrate_nodes(dst, src, *child, None);
2373            }
2374            ArenaSparseNode::Branch(branch) => {
2375                for child in &mut branch.children {
2376                    *child = match child.revealed_index() {
2377                        Some(child_idx) => {
2378                            BranchChild::revealed(Self::migrate_nodes(dst, src, child_idx, None))
2379                        }
2380                        None => dst.insert_blinded(src.take_blinded(*child)),
2381                    };
2382                }
2383            }
2384            _ => {}
2385        }
2386    }
2387
2388    /// Removes a pruned node from the arena and blinds the parent's child slot with the node's
2389    /// cached RLP.
2390    fn remove_pruned_node(arena: &mut NodeArena, cursor: &mut ArenaCursor) -> ArenaSparseNode {
2391        // Entry paths are derived from the cursor's path, so read the head path before popping.
2392        let path = cursor.head_path();
2393        let idx = cursor.head().expect("cursor is non-empty").index;
2394        let rlp_node = node_state_ref(arena, idx)
2395            .and_then(ArenaSparseNodeState::cached_rlp_node)
2396            .cloned()
2397            .expect("prune must run after hashing");
2398        cursor.pop(arena);
2399        let node = arena.remove(idx).expect("node must exist to be pruned");
2400        if let Some(child) = node.extension_child() {
2401            arena.remove(child).expect("extension child exists");
2402        }
2403        trace!(
2404            target: TRACE_TARGET,
2405            ?path,
2406            variant = %AsRef::<str>::as_ref(&node),
2407            cached_rlp_node = ?rlp_node,
2408            "pruning node",
2409        );
2410
2411        let parent_idx = cursor.head().expect("pruned child has parent").index;
2412        let child_nibble = path.last().expect("non-root child");
2413        let blinded = arena.insert_blinded(rlp_node);
2414        let parent_branch = branch_data_mut(arena, parent_idx);
2415        let child_idx = BranchChildIdx::new(parent_branch.state_mask, child_nibble)
2416            .expect("child nibble not found in parent state_mask");
2417        parent_branch.children[child_idx] = blinded;
2418
2419        node
2420    }
2421
2422    /// Reveals a single proof node using a pre-computed [`SeekResult`] from
2423    /// [`ArenaCursor::seek`].
2424    ///
2425    /// If the result is `Blinded`, the blinded child is replaced with the proof node (converted to
2426    /// an arena node with `Cached` state). All other cases (already revealed, no child, diverged,
2427    /// leaf head) are no-ops — the proof node is skipped.
2428    ///
2429    /// Returns the `Index` of the revealed node in the arena, if any was revealed.
2430    #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
2431    fn reveal_node(
2432        arena: &mut NodeArena,
2433        cursor: &ArenaCursor,
2434        node: &mut ProofTrieNode,
2435        extension_child: Option<ProofTrieNode>,
2436        find_result: SeekResult,
2437    ) -> Option<Index> {
2438        let SeekResult::Blinded = find_result else {
2439            // Already revealed, no child slot, or diverged — skip this proof node.
2440            return None;
2441        };
2442
2443        let head = cursor.head().expect("cursor is non-empty");
2444        let head_idx = head.index;
2445        if let ArenaSparseNode::Extension { child: ExtensionChild::Blinded(rlp_node), .. } =
2446            &arena[head_idx]
2447        {
2448            if node.path != cursor.head_logical_branch_path(arena) ||
2449                !matches!(node.node, TrieNode::Branch(_))
2450            {
2451                return None;
2452            }
2453            let state = ArenaSparseNodeState::Cached {
2454                rlp_node: rlp_node.clone(),
2455                epoch: TrieNodeEpoch::UNMODIFIED,
2456            };
2457            let proof = mem::replace(node, ProofTrieNode::empty());
2458            let mut branch = ArenaSparseNode::from_proof_node(arena, proof, None);
2459            *branch.state_mut() = state;
2460            let child_idx = arena.insert(branch);
2461            let ArenaSparseNode::Extension { child, .. } = &mut arena[head_idx] else {
2462                unreachable!()
2463            };
2464            *child = ExtensionChild::Revealed(child_idx);
2465            // Hydration does not change the extension's cached RLP or epoch.
2466            return None;
2467        }
2468        let head_branch_logical_path = cursor.head_logical_branch_path(arena);
2469
2470        debug_assert_eq!(
2471            node.path.len(),
2472            head_branch_logical_path.len() + 1,
2473            "proof node path {:?} is not a direct child of branch at {:?} (expected depth {})",
2474            node.path,
2475            head_branch_logical_path,
2476            head_branch_logical_path.len() + 1,
2477        );
2478
2479        let child_nibble = node.path.get_unchecked(head_branch_logical_path.len());
2480        let head_branch = branch_data(arena, head_idx);
2481        let dense_child_idx = BranchChildIdx::new(head_branch.state_mask, child_nibble)
2482            .expect("Blinded result but child nibble not in state_mask");
2483
2484        let child = head_branch.children[dense_child_idx];
2485        if !child.is_blinded() {
2486            return None;
2487        }
2488        let cached_rlp = arena.blinded(child).clone();
2489
2490        trace!(
2491            target: TRACE_TARGET,
2492            path = ?node.path,
2493            rlp_node = ?cached_rlp,
2494            "Revealing node",
2495        );
2496
2497        let proof_node = mem::replace(node, ProofTrieNode::empty());
2498        let node = ArenaSparseNode::from_proof_node(arena, proof_node, extension_child);
2499        let child_idx = arena.insert(node);
2500        *node_state_mut(arena, child_idx) =
2501            ArenaSparseNodeState::Cached { rlp_node: cached_rlp, epoch: TrieNodeEpoch::UNMODIFIED };
2502        branch_data_mut(arena, head_idx).children[dense_child_idx] =
2503            BranchChild::revealed(child_idx);
2504        arena.take_blinded(child);
2505
2506        Some(child_idx)
2507    }
2508
2509    #[cfg(all(debug_assertions, not(feature = "fuzz")))]
2510    fn collect_reachable_nodes(
2511        arena: &NodeArena,
2512        idx: Index,
2513        reachable: &mut alloy_primitives::map::HashSet<Index>,
2514    ) {
2515        if !reachable.insert(idx) {
2516            return;
2517        }
2518        match &arena[idx] {
2519            ArenaSparseNode::Extension { child: ExtensionChild::Revealed(child), .. } => {
2520                Self::collect_reachable_nodes(arena, *child, reachable);
2521            }
2522            ArenaSparseNode::Branch(b) => {
2523                for child in &b.children {
2524                    if let Some(child_idx) = child.revealed_index() {
2525                        Self::collect_reachable_nodes(arena, child_idx, reachable);
2526                    }
2527                }
2528            }
2529            _ => {}
2530        }
2531    }
2532
2533    #[cfg(all(debug_assertions, not(feature = "fuzz")))]
2534    fn assert_no_orphaned_nodes(arena: &NodeArena, root: Index, label: &str) {
2535        let mut reachable = alloy_primitives::map::HashSet::default();
2536        Self::collect_reachable_nodes(arena, root, &mut reachable);
2537        let all_indices: alloy_primitives::map::HashSet<Index> =
2538            arena.iter().map(|(idx, _)| idx).collect();
2539        let orphaned: Vec<_> = all_indices.difference(&reachable).collect();
2540        debug_assert!(
2541            orphaned.is_empty(),
2542            "{label} has {} orphaned node(s): {orphaned:?}",
2543            orphaned.len(),
2544        );
2545    }
2546}
2547
2548#[cfg(all(debug_assertions, not(feature = "fuzz")))]
2549impl Drop for ArenaParallelSparseTrie {
2550    fn drop(&mut self) {
2551        Self::assert_no_orphaned_nodes(&self.upper_arena, self.root, "upper arena");
2552
2553        for (_, node) in self.upper_arena.iter() {
2554            if let Some(subtrie) = node.as_subtrie() {
2555                Self::assert_no_orphaned_nodes(
2556                    &subtrie.arena,
2557                    subtrie.root,
2558                    &alloc::format!("subtrie {:?}", subtrie.path),
2559                );
2560            }
2561        }
2562    }
2563}
2564
2565impl Default for ArenaParallelSparseTrie {
2566    fn default() -> Self {
2567        let mut upper_arena = NodeArena::new();
2568        let root = upper_arena
2569            .insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Revealed });
2570        Self {
2571            upper_arena,
2572            root,
2573            buffers: ArenaTrieBuffers::default(),
2574            parallelism_thresholds: ArenaParallelismThresholds::default(),
2575        }
2576    }
2577}
2578
2579impl ArenaParallelSparseTrie {
2580    /// Hashes a subtrie at `head_idx` and collects its update actions.
2581    fn update_upper_subtrie(&mut self, head_idx: Index, new_epoch: TrieNodeEpoch) {
2582        let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[head_idx] else {
2583            unreachable!()
2584        };
2585
2586        if !node_state_ref(&subtrie.arena, subtrie.root)
2587            .is_some_and(|state| matches!(state, ArenaSparseNodeState::Cached { .. }))
2588        {
2589            subtrie.update_cached_rlp(new_epoch);
2590        }
2591
2592        Self::merge_subtrie_updates(&mut self.buffers.updates, &mut subtrie.buffers.updates);
2593    }
2594}
2595
2596impl SparseTrie for ArenaParallelSparseTrie {
2597    #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
2598    fn set_root(
2599        &mut self,
2600        nodes: &mut [ProofTrieNode],
2601        retain_updates: bool,
2602    ) -> SparseTrieResult<()> {
2603        debug_assert!(
2604            matches!(self.upper_arena[self.root], ArenaSparseNode::EmptyRoot { .. }),
2605            "set_root called on a trie that already has revealed nodes"
2606        );
2607
2608        let nodes = sort_proof_nodes(nodes);
2609        assert!(
2610            !nodes.is_empty() && nodes[0].path.is_empty(),
2611            "calculator root batch must contain the root at the empty path"
2612        );
2613        validate_extension_child(&nodes[0], nodes.get(1))?;
2614        let extension_child = take_extension_child(nodes, 0);
2615        let root = mem::replace(&mut nodes[0], ProofTrieNode::empty());
2616        self.upper_arena[self.root] =
2617            ArenaSparseNode::from_proof_node(&mut self.upper_arena, root, extension_child);
2618        self.set_updates(retain_updates);
2619        Ok(())
2620    }
2621
2622    fn set_updates(&mut self, retain_updates: bool) {
2623        if retain_updates {
2624            self.buffers.updates.get_or_insert_with(SparseTrieUpdates::default).clear();
2625        } else {
2626            self.buffers.updates = None;
2627        }
2628    }
2629
2630    #[instrument(level = "trace", target = TRACE_TARGET, skip_all, fields(num_nodes = nodes.len()))]
2631    fn reveal_nodes(&mut self, nodes: &mut [ProofTrieNode]) -> SparseTrieResult<()> {
2632        if nodes.is_empty() {
2633            return Ok(());
2634        }
2635
2636        if matches!(self.upper_arena[self.root], ArenaSparseNode::EmptyRoot { .. }) {
2637            trace!(target: TRACE_TARGET, "Skipping reveal_nodes on empty root");
2638            return Ok(());
2639        }
2640
2641        // Sort nodes lexicographically by path.
2642        let nodes = sort_proof_nodes(nodes);
2643        for (index, node) in nodes.iter().enumerate() {
2644            validate_extension_child(node, nodes.get(index + 1))?;
2645        }
2646
2647        let threshold = self.parallelism_thresholds.min_revealed_nodes;
2648
2649        // Take the cursor out to avoid borrow conflicts with `self`.
2650        let mut cursor = mem::take(&mut self.buffers.cursor);
2651        cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2652
2653        // Skip root node if present (set_root handles the root).
2654        let mut node_idx = if nodes[0].path.is_empty() { 1 } else { 0 };
2655
2656        // Walk the upper trie, revealing upper nodes inline and collecting subtrie work.
2657        // Subtries with enough nodes to reveal are taken for parallel processing; the rest
2658        // are revealed inline.
2659        let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>, Vec<ProofTrieNode>)> = Vec::new();
2660
2661        while node_idx < nodes.len() {
2662            let find_result = cursor.seek(&mut self.upper_arena, &nodes[node_idx].path);
2663
2664            match find_result {
2665                SeekResult::RevealedLeaf => {
2666                    trace!(target: TRACE_TARGET, path = ?nodes[node_idx].path, "Skipping reveal: leaf head");
2667                    node_idx += 1;
2668                }
2669                SeekResult::Blinded => {
2670                    // Save the proof node's path before reveal_node consumes it.
2671                    let child_path = nodes[node_idx].path;
2672                    let extension_child = take_extension_child(nodes, node_idx);
2673                    let next_idx = node_idx + 1 + usize::from(extension_child.is_some());
2674                    let child_idx = Self::reveal_node(
2675                        &mut self.upper_arena,
2676                        &cursor,
2677                        &mut nodes[node_idx],
2678                        extension_child,
2679                        SeekResult::Blinded,
2680                    );
2681                    node_idx = next_idx;
2682
2683                    if let Some(child_idx) = child_idx {
2684                        self.maybe_wrap_in_subtrie(child_idx, &child_path);
2685                    }
2686                }
2687                SeekResult::RevealedSubtrie => {
2688                    let child_idx = cursor.head().expect("cursor is non-empty").index;
2689                    let prefix = cursor.head_path();
2690
2691                    let subtrie_start = node_idx;
2692                    while node_idx < nodes.len() && nodes[node_idx].path.starts_with(&prefix) {
2693                        node_idx += 1;
2694                    }
2695                    let num_subtrie_nodes = node_idx - subtrie_start;
2696
2697                    if num_subtrie_nodes >= threshold {
2698                        // Take subtrie for parallel reveal.
2699                        trace!(target: TRACE_TARGET, ?prefix, num_subtrie_nodes, "Taking subtrie for parallel reveal");
2700                        let ArenaSparseNode::Subtrie(subtrie) = mem::replace(
2701                            &mut self.upper_arena[child_idx],
2702                            ArenaSparseNode::TakenSubtrie,
2703                        ) else {
2704                            unreachable!("RevealedSubtrie must point to a Subtrie node")
2705                        };
2706                        let node_vec: Vec<ProofTrieNode> = (subtrie_start..node_idx)
2707                            .map(|i| mem::replace(&mut nodes[i], ProofTrieNode::empty()))
2708                            .collect();
2709                        taken.push((child_idx, subtrie, node_vec));
2710                    } else {
2711                        // Reveal inline.
2712                        trace!(target: TRACE_TARGET, ?prefix, num_subtrie_nodes, "Revealing subtrie inline");
2713                        let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[child_idx]
2714                        else {
2715                            unreachable!("RevealedSubtrie must point to a Subtrie node")
2716                        };
2717                        let mut subtrie_nodes: Vec<ProofTrieNode> = (subtrie_start..node_idx)
2718                            .map(|i| mem::replace(&mut nodes[i], ProofTrieNode::empty()))
2719                            .collect();
2720                        subtrie.reveal_nodes(&mut subtrie_nodes)?;
2721                    }
2722                }
2723                _ => {
2724                    trace!(target: TRACE_TARGET, path = ?nodes[node_idx].path, ?find_result, "Skipping reveal: no blinded child");
2725                    node_idx += 1;
2726                }
2727            }
2728        }
2729
2730        // Drain remaining cursor entries from the upper-trie walk.
2731        cursor.drain(&mut self.upper_arena);
2732        self.buffers.cursor = cursor;
2733
2734        if taken.is_empty() {
2735            return Ok(());
2736        }
2737
2738        // Reveal taken subtries, in parallel if more than one.
2739        if taken.len() == 1 {
2740            let (_, subtrie, node_vec) = &mut taken[0];
2741            subtrie.reveal_nodes(node_vec)?;
2742        } else {
2743            let parent_span = tracing::Span::current();
2744            let results: Vec<SparseTrieResult<()>> = taken
2745                .par_iter_mut()
2746                .map(|(_, subtrie, node_vec)| {
2747                    let _guard = parent_span.enter();
2748                    subtrie.reveal_nodes(node_vec)
2749                })
2750                .collect();
2751
2752            if let Some(err) = results.into_iter().find(|r| r.is_err()) {
2753                // Restore before returning so we don't leave TakenSubtrie holes.
2754                for (idx, subtrie, _) in taken {
2755                    self.restore_taken_subtrie(idx, subtrie);
2756                }
2757                return err;
2758            }
2759        }
2760
2761        // Restore taken subtries into the upper arena.
2762        for (idx, subtrie, _) in taken {
2763            self.restore_taken_subtrie(idx, subtrie);
2764        }
2765
2766        #[cfg(all(debug_assertions, not(feature = "fuzz")))]
2767        self.debug_assert_subtrie_structure();
2768
2769        Ok(())
2770    }
2771
2772    #[instrument(level = "trace", target = TRACE_TARGET, skip_all, ret)]
2773    fn root(&mut self, new_epoch: TrieNodeEpoch) -> B256 {
2774        self.update_subtrie_hashes(new_epoch);
2775
2776        let rlp_node = Self::update_cached_rlp(
2777            &mut self.upper_arena,
2778            self.root,
2779            Nibbles::default(),
2780            &mut self.buffers,
2781            new_epoch,
2782        );
2783
2784        rlp_node.as_hash().expect("root RlpNode must be a hash")
2785    }
2786
2787    fn is_root_cached(&self) -> bool {
2788        matches!(
2789            node_state_ref(&self.upper_arena, self.root),
2790            Some(ArenaSparseNodeState::Cached { .. })
2791        )
2792    }
2793
2794    fn root_epoch(&self) -> Option<TrieNodeEpoch> {
2795        match node_state_ref(&self.upper_arena, self.root)? {
2796            ArenaSparseNodeState::Revealed => Some(TrieNodeEpoch::UNMODIFIED),
2797            ArenaSparseNodeState::Cached { epoch, .. } => Some(*epoch),
2798            ArenaSparseNodeState::Dirty => None,
2799        }
2800    }
2801
2802    #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
2803    fn update_subtrie_hashes(&mut self, new_epoch: TrieNodeEpoch) {
2804        trace!(target: TRACE_TARGET, "Updating subtrie hashes");
2805
2806        // Only descend if the root is a branch or extension; otherwise there are no subtries.
2807        if branch_idx(&self.upper_arena, self.root).is_none() {
2808            return;
2809        }
2810
2811        // Count total dirty leaves across all subtries to make one global parallelism decision.
2812        let mut total_dirty_leaves: u64 = 0;
2813        let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>)> = Vec::new();
2814        for (idx, node) in self.upper_arena.iter_mut() {
2815            let ArenaSparseNode::Subtrie(s) = node else { continue };
2816            if s.num_dirty_leaves == 0 {
2817                continue;
2818            }
2819            total_dirty_leaves += s.num_dirty_leaves;
2820            let ArenaSparseNode::Subtrie(subtrie) =
2821                mem::replace(node, ArenaSparseNode::TakenSubtrie)
2822            else {
2823                unreachable!()
2824            };
2825            taken.push((idx, subtrie));
2826        }
2827
2828        // Hash taken subtries in parallel if total dirty leaves meet the threshold.
2829        if !taken.is_empty() {
2830            if taken.len() == 1 || total_dirty_leaves < self.parallelism_thresholds.min_dirty_leaves
2831            {
2832                for (_, subtrie) in &mut taken {
2833                    subtrie.update_cached_rlp(new_epoch);
2834                }
2835            } else {
2836                let parent_span = tracing::Span::current();
2837                taken = taken
2838                    .into_par_iter()
2839                    .map(|(idx, mut subtrie)| {
2840                        let _guard = parent_span.enter();
2841                        subtrie.update_cached_rlp(new_epoch);
2842                        (idx, subtrie)
2843                    })
2844                    .collect();
2845            }
2846        }
2847
2848        // If the root branch is already cached and nothing was taken for parallel
2849        // hashing, there are no dirty subtries to process.
2850        if taken.is_empty() && self.is_root_cached() {
2851            return;
2852        }
2853
2854        // Walk the upper trie depth-first, restoring hashed subtries and inline-hashing
2855        // any remaining dirty subtries. Only descend into dirty branches; clean subtrees
2856        // cannot contain dirty subtries since dirty state propagates upward.
2857        taken.sort_unstable_by_key(|(_, b)| Reverse(b.path));
2858
2859        self.buffers.cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2860
2861        loop {
2862            let result = self.buffers.cursor.next(&mut self.upper_arena, |_, child| match child {
2863                ArenaSparseNode::Branch(_) |
2864                ArenaSparseNode::Extension { .. } |
2865                ArenaSparseNode::Subtrie(_) => !child.is_cached(),
2866                ArenaSparseNode::TakenSubtrie => true,
2867                _ => false,
2868            });
2869
2870            match result {
2871                NextResult::Done => break,
2872                NextResult::Branch => continue,
2873                NextResult::NonBranch => {}
2874            }
2875
2876            // Head may also be an extension whose backing branch is still blinded.
2877            let head_idx = self.buffers.cursor.head().expect("cursor is non-empty").index;
2878            if has_blinded_branch(&self.upper_arena, head_idx) &&
2879                !matches!(self.upper_arena[head_idx], ArenaSparseNode::Subtrie(_))
2880            {
2881                continue;
2882            }
2883
2884            if matches!(&self.upper_arena[head_idx], ArenaSparseNode::TakenSubtrie) {
2885                let (_, subtrie) = taken.pop().expect("taken subtries must not be exhausted");
2886                debug_assert_eq!(
2887                    subtrie.path,
2888                    self.buffers.cursor.head_path(),
2889                    "taken subtrie path mismatch",
2890                );
2891                self.upper_arena[head_idx] = ArenaSparseNode::Subtrie(subtrie);
2892            }
2893
2894            self.update_upper_subtrie(head_idx, new_epoch);
2895        }
2896    }
2897
2898    fn get_leaf_value(&self, full_path: &Nibbles) -> Option<&Vec<u8>> {
2899        Self::get_leaf_value_in_arena(&self.upper_arena, self.root, full_path, 0)
2900    }
2901
2902    fn find_leaf(
2903        &self,
2904        full_path: &Nibbles,
2905        expected_value: Option<&Vec<u8>>,
2906    ) -> Result<LeafLookup, LeafLookupError> {
2907        Self::find_leaf_in_arena(&self.upper_arena, self.root, full_path, 0, expected_value)
2908    }
2909
2910    fn updates_ref(&self) -> Cow<'_, SparseTrieUpdates> {
2911        self.buffers
2912            .updates
2913            .as_ref()
2914            .map_or(Cow::Owned(SparseTrieUpdates::default()), Cow::Borrowed)
2915    }
2916
2917    fn take_updates(&mut self) -> SparseTrieUpdates {
2918        match self.buffers.updates.take() {
2919            Some(updates) => {
2920                self.buffers.updates = Some(SparseTrieUpdates::with_capacity(
2921                    updates.updated_nodes.len(),
2922                    updates.removed_nodes.len(),
2923                ));
2924                updates
2925            }
2926            None => SparseTrieUpdates::default(),
2927        }
2928    }
2929
2930    #[instrument(level = "trace", target = TRACE_TARGET, skip_all)]
2931    fn clear(&mut self) {
2932        self.upper_arena = NodeArena::new();
2933        self.root = self
2934            .upper_arena
2935            .insert(ArenaSparseNode::EmptyRoot { state: ArenaSparseNodeState::Revealed });
2936        self.buffers.clear();
2937    }
2938
2939    #[instrument(
2940        level = "trace",
2941        target = TRACE_TARGET,
2942        skip_all,
2943        fields(prune_before = prune_before.get()),
2944    )]
2945    fn prune(&mut self, prune_before: TrieNodeEpoch) -> usize {
2946        assert!(self.root_epoch().is_some(), "prune cannot run on a dirty trie");
2947
2948        // Only branches and extensions can have pruneable children.
2949        if branch_idx(&self.upper_arena, self.root).is_none() {
2950            return 0;
2951        }
2952
2953        let threshold = self.parallelism_thresholds.min_leaves_for_prune;
2954
2955        let mut cursor = mem::take(&mut self.buffers.cursor);
2956        cursor.reset(&self.upper_arena, self.root, Nibbles::default());
2957
2958        // Subtries taken for parallel pruning.
2959        let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>)> = Vec::new();
2960
2961        let mut pruned = 0;
2962
2963        loop {
2964            let result = cursor.next(&mut self.upper_arena, |_, child| {
2965                matches!(
2966                    child,
2967                    ArenaSparseNode::Branch(_) |
2968                        ArenaSparseNode::Extension { .. } |
2969                        ArenaSparseNode::Subtrie(_) |
2970                        ArenaSparseNode::Leaf { .. }
2971                )
2972            });
2973
2974            if matches!(result, NextResult::Done) {
2975                break
2976            }
2977
2978            let head_idx = cursor.head().expect("cursor is non-empty").index;
2979
2980            match &self.upper_arena[head_idx] {
2981                ArenaSparseNode::Branch(_) |
2982                ArenaSparseNode::Extension { .. } |
2983                ArenaSparseNode::Leaf { .. } => {
2984                    // Don't prune the root.
2985                    if cursor.depth() == 0 {
2986                        continue;
2987                    }
2988
2989                    let node_epoch = node_state_ref(&self.upper_arena, head_idx)
2990                        .and_then(ArenaSparseNodeState::cached_epoch)
2991                        .expect("prune must run after hashing");
2992                    if !node_epoch.should_prune(prune_before) {
2993                        continue;
2994                    }
2995
2996                    let removed = Self::remove_pruned_node(&mut self.upper_arena, &mut cursor);
2997                    pruned += 1 + usize::from(removed.extension_child().is_some());
2998                }
2999                ArenaSparseNode::Subtrie(_) => {
3000                    let root_epoch = self.upper_arena[head_idx]
3001                        .state_ref()
3002                        .and_then(ArenaSparseNodeState::cached_epoch)
3003                        .expect("prune must run after hashing");
3004                    if root_epoch.should_prune(prune_before) {
3005                        let removed = Self::remove_pruned_node(&mut self.upper_arena, &mut cursor);
3006                        let ArenaSparseNode::Subtrie(s) = &removed else { unreachable!() };
3007                        pruned += s.arena.len();
3008                        self.recycle_subtrie(removed);
3009                        continue;
3010                    }
3011
3012                    let ArenaSparseNode::Subtrie(subtrie) = &self.upper_arena[head_idx] else {
3013                        unreachable!()
3014                    };
3015                    if subtrie.num_leaves >= threshold {
3016                        let ArenaSparseNode::Subtrie(subtrie) = mem::replace(
3017                            &mut self.upper_arena[head_idx],
3018                            ArenaSparseNode::TakenSubtrie,
3019                        ) else {
3020                            unreachable!()
3021                        };
3022                        taken.push((head_idx, subtrie));
3023                    } else {
3024                        let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[head_idx]
3025                        else {
3026                            unreachable!()
3027                        };
3028                        pruned += subtrie.prune(prune_before);
3029                    }
3030                }
3031                _ => unreachable!("prune walk must visit a subtrie, leaf, branch, or extension"),
3032            }
3033        }
3034
3035        self.buffers.cursor = cursor;
3036
3037        if !taken.is_empty() {
3038            // Prune taken subtries, in parallel if more than one.
3039            if taken.len() == 1 {
3040                let (_, ref mut subtrie) = taken[0];
3041                pruned += subtrie.prune(prune_before);
3042            } else {
3043                let parent_span = tracing::Span::current();
3044                pruned += taken
3045                    .par_iter_mut()
3046                    .map(|(_, subtrie)| {
3047                        let _guard = parent_span.enter();
3048                        let _span = tracing::trace_span!(
3049                            target: TRACE_TARGET,
3050                            "subtrie_prune",
3051                            subtrie = ?subtrie.path,
3052                        )
3053                        .entered();
3054
3055                        subtrie.prune(prune_before)
3056                    })
3057                    .sum::<usize>();
3058            }
3059
3060            // Restore taken subtries into the upper arena.
3061            for (child_idx, subtrie) in taken {
3062                self.restore_taken_subtrie(child_idx, subtrie);
3063            }
3064        }
3065
3066        if pruned > 0 {
3067            compact_arena(&mut self.upper_arena, &mut self.root);
3068        }
3069
3070        pruned
3071    }
3072
3073    #[instrument(
3074        level = "trace",
3075        target = TRACE_TARGET,
3076        skip_all,
3077        fields(num_updates = updates.len()),
3078    )]
3079    fn update_leaves(
3080        &mut self,
3081        updates: &mut B256Map<LeafUpdate>,
3082        mut proof_required_fn: impl FnMut(B256, ProofV2TargetParent),
3083    ) -> SparseTrieResult<()> {
3084        if updates.is_empty() {
3085            return Ok(());
3086        }
3087
3088        // Drain and sort updates lexicographically by nibbles path.
3089        let mut sorted: Vec<_> =
3090            updates.drain().map(|(key, update)| (key, Nibbles::unpack(key), update)).collect();
3091        sorted.sort_unstable_by_key(|entry| entry.1);
3092
3093        let threshold = self.parallelism_thresholds.min_updates;
3094        let parallelize_distributed_updates = sorted.len() >= threshold.saturating_mul(4);
3095
3096        let mut cursor = mem::take(&mut self.buffers.cursor);
3097        cursor.reset(&self.upper_arena, self.root, Nibbles::default());
3098
3099        // Subtries taken for parallel processing: (arena_index, subtrie, update_range).
3100        let mut taken: Vec<(Index, Box<ArenaSparseSubtrie>, core::ops::Range<usize>)> = Vec::new();
3101
3102        let mut update_idx = 0;
3103        while update_idx < sorted.len() {
3104            let (key, ref full_path, ref update) = sorted[update_idx];
3105
3106            let find_result = cursor.seek(&mut self.upper_arena, full_path);
3107            let needs_split_proof =
3108                split_needs_proof(&self.upper_arena, &cursor, &find_result, update);
3109            let find_result = if needs_split_proof { SeekResult::Blinded } else { find_result };
3110
3111            match find_result {
3112                // Blinded — request a proof regardless of update type.
3113                SeekResult::Blinded => {
3114                    #[cfg(all(feature = "fuzz", reth_sparse_trie_coverage))]
3115                    let logical_len = cursor.head_logical_branch_path_len(&self.upper_arena);
3116                    let parent = blinded_proof_parent(&self.upper_arena, &cursor);
3117                    let proof_key = if needs_split_proof {
3118                        Self::nibbles_to_padded_b256(
3119                            &cursor.head_logical_branch_path(&self.upper_arena),
3120                        )
3121                    } else {
3122                        key
3123                    };
3124                    trace!(target: TRACE_TARGET, ?key, ?parent, "Update hit blinded node, requesting proof");
3125                    #[cfg(all(feature = "fuzz", reth_sparse_trie_coverage))]
3126                    observe_proof_target(
3127                        &self.upper_arena,
3128                        cursor.head().map(|entry| (entry.index, logical_len)),
3129                        full_path,
3130                        &taken,
3131                    );
3132                    proof_required_fn(proof_key, parent);
3133                    updates.insert(key, update.clone());
3134                }
3135                // Subtrie — forward all consecutive updates under this subtrie's prefix.
3136                SeekResult::RevealedSubtrie => {
3137                    let child_idx = cursor.head().expect("cursor is non-empty").index;
3138                    let subtrie_root_path = cursor.head_path();
3139
3140                    let subtrie_start = update_idx;
3141                    while update_idx < sorted.len() &&
3142                        sorted[update_idx].1.starts_with(&subtrie_root_path)
3143                    {
3144                        update_idx += 1;
3145                    }
3146
3147                    let subtrie_updates = &sorted[subtrie_start..update_idx];
3148
3149                    // Edge-case: if all updates are removals that could empty the
3150                    // subtrie and collapse the parent onto a blinded sibling, request
3151                    // a proof for the sibling and skip the subtrie's updates.
3152                    if let Some(proof) = Self::check_subtrie_collapse_needs_proof(
3153                        &self.upper_arena,
3154                        &cursor,
3155                        subtrie_updates,
3156                    ) {
3157                        trace!(target: TRACE_TARGET, proof_key = ?proof.key, proof_parent = ?proof.parent, "Subtrie collapse would need blinded sibling, requesting proof");
3158                        proof_required_fn(proof.key, proof.parent);
3159                        for &(key, _, ref update) in subtrie_updates {
3160                            updates.insert(key, update.clone());
3161                        }
3162                        // Pop the subtrie entry before continuing.
3163                        continue;
3164                    }
3165
3166                    let num_subtrie_updates = update_idx - subtrie_start;
3167
3168                    // If all updates are removals and could empty the subtrie,
3169                    // force inline processing so the upper-arena collapse logic
3170                    // can detect blinded siblings and request proofs.
3171                    let all_removals = subtrie_updates
3172                        .iter()
3173                        // Filter out Touched, as they don't affect the structure of the trie. So an
3174                        // update set with 2 removals and one Touched could still result in an empty
3175                        // sub trie.
3176                        .filter(|(_, _, u)| u.is_changed())
3177                        .all(|(_, _, u)| matches!(u, LeafUpdate::Changed(v) if v.is_empty()));
3178                    let subtrie_num_leaves = match &self.upper_arena[child_idx] {
3179                        ArenaSparseNode::Subtrie(s) => s.num_leaves,
3180                        _ => 0,
3181                    };
3182                    let might_empty_subtrie =
3183                        all_removals && num_subtrie_updates as u64 >= subtrie_num_leaves;
3184
3185                    // Keep opaque extension roots visible to sibling collapse proof checks.
3186                    if (num_subtrie_updates >= threshold || parallelize_distributed_updates) &&
3187                        !might_empty_subtrie &&
3188                        !has_blinded_branch(&self.upper_arena, child_idx)
3189                    {
3190                        // Take subtrie for parallel update.
3191                        trace!(target: TRACE_TARGET, ?subtrie_root_path, num_subtrie_updates, "Taking subtrie for parallel update");
3192                        let ArenaSparseNode::Subtrie(subtrie) = mem::replace(
3193                            &mut self.upper_arena[child_idx],
3194                            ArenaSparseNode::TakenSubtrie,
3195                        ) else {
3196                            unreachable!()
3197                        };
3198                        taken.push((child_idx, subtrie, subtrie_start..update_idx));
3199                    } else {
3200                        // Update inline.
3201                        trace!(target: TRACE_TARGET, ?subtrie_root_path, num_subtrie_updates, "Updating subtrie inline");
3202                        let ArenaSparseNode::Subtrie(subtrie) = &mut self.upper_arena[child_idx]
3203                        else {
3204                            unreachable!()
3205                        };
3206
3207                        subtrie.update_leaves(subtrie_updates);
3208
3209                        for (target_idx, proof) in subtrie.required_proofs.drain(..) {
3210                            proof_required_fn(proof.key, proof.parent);
3211                            let (key, _, ref update) = subtrie_updates[target_idx];
3212                            updates.insert(key, update.clone());
3213                        }
3214
3215                        // Check if the subtrie's root became empty after updates.
3216                        self.maybe_unwrap_subtrie(&mut cursor);
3217                    }
3218
3219                    // Don't increment update_idx — already advanced past subtrie updates.
3220                    continue;
3221                }
3222                // EmptyRoot, leaf, diverged branch, or empty child slot — upsert directly.
3223                find_result @ (SeekResult::EmptyRoot |
3224                SeekResult::RevealedLeaf |
3225                SeekResult::Diverged |
3226                SeekResult::NoChild { .. }) => match update {
3227                    LeafUpdate::Changed(v) if !v.is_empty() => {
3228                        let (result, _deltas) = Self::upsert_leaf(
3229                            &mut self.upper_arena,
3230                            &mut cursor,
3231                            &mut self.root,
3232                            full_path,
3233                            v,
3234                            find_result,
3235                        );
3236                        match result {
3237                            UpsertLeafResult::NewChild => {
3238                                if Self::should_be_subtrie(cursor.head_path_len()) {
3239                                    // The new child itself sits at the subtrie
3240                                    // boundary — wrap it directly.
3241                                    let head_idx =
3242                                        cursor.head().expect("cursor is non-empty").index;
3243                                    self.maybe_wrap_in_subtrie(head_idx, &cursor.head_path());
3244                                } else {
3245                                    // The new child is above the boundary (e.g. a
3246                                    // split at depth 1 creates children at depth 2).
3247                                    // Wrap any of its children that land there.
3248                                    self.maybe_wrap_branch_children(&cursor);
3249                                }
3250                            }
3251                            UpsertLeafResult::NewLeaf => {
3252                                // A root-level split may create children at the
3253                                // subtrie boundary depth. Wrap them.
3254                                self.maybe_wrap_branch_children(&cursor);
3255                            }
3256                            UpsertLeafResult::Updated => {}
3257                        }
3258                    }
3259                    LeafUpdate::Changed(_) => {
3260                        let (result, _deltas) = Self::remove_leaf(
3261                            &mut self.upper_arena,
3262                            &mut cursor,
3263                            &mut self.root,
3264                            key,
3265                            full_path,
3266                            find_result,
3267                            &mut self.buffers.updates,
3268                        );
3269                        match result {
3270                            RemoveLeafResult::NeedsProof { key, proof_key, parent } => {
3271                                proof_required_fn(proof_key, parent);
3272                                let update =
3273                                    mem::replace(&mut sorted[update_idx].2, LeafUpdate::Touched);
3274                                updates.insert(key, update);
3275                            }
3276                            RemoveLeafResult::Removed => {
3277                                // remove_leaf may have called collapse_branch, which
3278                                // can leave structural invariants violated:
3279                                // 1. A branch with 0-1 children that needs further collapse or
3280                                //    removal.
3281                                // 2. A Subtrie at a depth shallower than UPPER_TRIE_MAX_DEPTH that
3282                                //    needs unwrapping.
3283                                // 3. A non-Subtrie node at UPPER_TRIE_MAX_DEPTH that needs
3284                                //    wrapping.
3285                                self.maybe_collapse_or_remove_branch(&mut cursor);
3286                                let head_idx = cursor
3287                                    .head()
3288                                    .expect("cursor always has root after collapse")
3289                                    .index;
3290                                self.maybe_wrap_in_subtrie(head_idx, &cursor.head_path());
3291                            }
3292                            RemoveLeafResult::NotFound => {}
3293                        }
3294                    }
3295                    LeafUpdate::Touched => {}
3296                },
3297            }
3298
3299            update_idx += 1;
3300        }
3301
3302        // Drain remaining cursor entries from the upper-trie walk.
3303        cursor.drain(&mut self.upper_arena);
3304        self.buffers.cursor = cursor;
3305
3306        if taken.is_empty() {
3307            #[cfg(all(debug_assertions, not(feature = "fuzz")))]
3308            self.debug_assert_subtrie_structure();
3309
3310            return Ok(());
3311        }
3312
3313        // Apply updates to taken subtries, in parallel if more than one.
3314        if taken.len() == 1 {
3315            let (_, ref mut subtrie, ref range) = taken[0];
3316            subtrie.update_leaves(&sorted[range.clone()]);
3317        } else {
3318            let parent_span = tracing::Span::current();
3319            taken.par_iter_mut().for_each(|(_, subtrie, range)| {
3320                let _guard = parent_span.enter();
3321                subtrie.update_leaves(&sorted[range.clone()]);
3322            });
3323        }
3324
3325        // Collect subtrie paths before consuming `taken`, then restore subtries and
3326        // process required proofs.
3327        let taken_paths: Vec<Nibbles> = taken.iter().map(|(_, s, _)| s.path).collect();
3328        for (child_idx, mut subtrie, range) in taken {
3329            let subtrie_updates = &sorted[range];
3330            for (target_idx, proof) in subtrie.required_proofs.drain(..) {
3331                proof_required_fn(proof.key, proof.parent);
3332                let (key, _, ref update) = subtrie_updates[target_idx];
3333                updates.insert(key, update.clone());
3334            }
3335
3336            // Restore the subtrie into the upper arena.
3337            self.restore_taken_subtrie(child_idx, subtrie);
3338        }
3339
3340        // Navigate to each taken subtrie via seek to propagate dirty state
3341        // through intermediate branches. Taken subtries are guaranteed not to
3342        // become EmptyRoot (the would-empty-subtrie check above forces those
3343        // inline), so we only need to handle sibling collapses that may have
3344        // occurred during inline processing while this subtrie was taken.
3345        {
3346            let mut cursor = mem::take(&mut self.buffers.cursor);
3347            cursor.reset(&self.upper_arena, self.root, Nibbles::default());
3348
3349            for path in &taken_paths {
3350                let find_result = cursor.seek(&mut self.upper_arena, path);
3351                match find_result {
3352                    SeekResult::RevealedSubtrie => {
3353                        debug_assert!(
3354                            {
3355                                let head_idx = cursor.head().expect("cursor is non-empty").index;
3356                                !matches!(
3357                                    &self.upper_arena[head_idx],
3358                                    ArenaSparseNode::Subtrie(s) if matches!(s.arena[s.root], ArenaSparseNode::EmptyRoot { .. })
3359                                )
3360                            },
3361                            "taken subtrie became EmptyRoot — should have been forced inline"
3362                        );
3363
3364                        cursor.pop(&mut self.upper_arena);
3365
3366                        // The parent branch (now at cursor top) may have had a sibling
3367                        // removed during inline processing while this subtrie was taken.
3368                        // Handle any necessary collapse or removal.
3369                        self.maybe_collapse_or_remove_branch(&mut cursor);
3370                    }
3371                    _ => {
3372                        // Subtrie was already unwrapped by a prior collapse; dirty state
3373                        // was propagated during that collapse. Nothing to do.
3374                    }
3375                }
3376            }
3377
3378            cursor.drain(&mut self.upper_arena);
3379            self.buffers.cursor = cursor;
3380        }
3381
3382        #[cfg(all(debug_assertions, not(feature = "fuzz")))]
3383        self.debug_assert_subtrie_structure();
3384
3385        Ok(())
3386    }
3387}
3388
3389#[cfg(test)]
3390mod tests {
3391    use super::*;
3392    use crate::{
3393        ArenaParallelSparseTrie, ArenaParallelismThresholds, LeafUpdate, SparseTrie, TrieNodeEpoch,
3394    };
3395    use alloy_primitives::{map::B256Map, B256, U256};
3396    use rand::{seq::SliceRandom, Rng, SeedableRng};
3397    use reth_trie::test_utils::TrieTestHarness;
3398    use reth_trie_common::{ProofV2Target, RlpNode};
3399    use std::collections::BTreeMap;
3400    use tracing::{info, trace};
3401
3402    const fn epoch(value: u64) -> TrieNodeEpoch {
3403        TrieNodeEpoch::new(value)
3404    }
3405
3406    #[test]
3407    fn pruning_pops_cursor_before_reusing_node_slot() {
3408        let mut arena = NodeArena::new();
3409        let rlp = RlpNode::word_rlp(&B256::repeat_byte(1));
3410        let state = ArenaSparseNodeState::Cached { rlp_node: rlp.clone(), epoch: epoch(0) };
3411        let leaf =
3412            ArenaSparseNode::Leaf { state: state.clone(), key: Default::default(), value: vec![1] };
3413        let first = arena.insert(leaf.clone());
3414        let second = arena.insert(leaf);
3415        let root = arena.insert(ArenaSparseNode::Branch(ArenaSparseNodeBranch {
3416            state: state.clone(),
3417            children: [BranchChild::revealed(first), BranchChild::revealed(second)]
3418                .into_iter()
3419                .collect(),
3420            state_mask: alloy_trie::TrieMask::new(3),
3421            branch_masks: Default::default(),
3422        }));
3423        let mut cursor = ArenaCursor::default();
3424        cursor.reset(&arena, root, Default::default());
3425        assert!(matches!(cursor.next(&mut arena, |_, _| true), NextResult::NonBranch));
3426        assert_eq!(cursor.head().unwrap().index, first);
3427
3428        ArenaParallelSparseTrie::remove_pruned_node(&mut arena, &mut cursor);
3429        assert_eq!(cursor.head().unwrap().index, root);
3430        let reused = arena.insert(ArenaSparseNode::Leaf {
3431            state: ArenaSparseNodeState::Dirty,
3432            key: Default::default(),
3433            value: vec![2],
3434        });
3435        assert_eq!(reused, first);
3436
3437        assert!(matches!(cursor.next(&mut arena, |_, _| true), NextResult::NonBranch));
3438        assert_eq!(cursor.head().unwrap().index, second);
3439        assert!(matches!(cursor.next(&mut arena, |_, _| true), NextResult::Branch));
3440        assert_eq!(arena[root].state_ref(), Some(&state));
3441        assert_eq!(arena.blinded(arena[root].branch_ref().children[0]), &rlp);
3442        assert!(matches!(cursor.next(&mut arena, |_, _| true), NextResult::Done));
3443    }
3444
3445    /// Test harness for proptest-based arena sparse trie testing.
3446    ///
3447    /// Wraps [`TrieTestHarness`] and adds `ArenaParallelSparseTrie`-specific helpers for
3448    /// the reveal-update loop and asserting that sparse trie updates match `StorageRoot`.
3449    struct ArenaTrieTestHarness {
3450        /// The inner general-purpose harness.
3451        inner: TrieTestHarness,
3452    }
3453
3454    impl std::ops::Deref for ArenaTrieTestHarness {
3455        type Target = TrieTestHarness;
3456        fn deref(&self) -> &Self::Target {
3457            &self.inner
3458        }
3459    }
3460
3461    impl std::ops::DerefMut for ArenaTrieTestHarness {
3462        fn deref_mut(&mut self) -> &mut Self::Target {
3463            &mut self.inner
3464        }
3465    }
3466
3467    impl ArenaTrieTestHarness {
3468        /// Creates a new test harness from a map of hashed storage slots to values.
3469        fn new(storage: BTreeMap<B256, U256>) -> Self {
3470            Self { inner: TrieTestHarness::new(storage) }
3471        }
3472
3473        /// Computes the new storage root and trie updates after applying the given changes
3474        /// using both `StorageRoot` and the provided `ArenaParallelSparseTrie`, then asserts
3475        /// they match.
3476        fn assert_changes(
3477            &self,
3478            apst: &mut ArenaParallelSparseTrie,
3479            changes: BTreeMap<B256, U256>,
3480        ) {
3481            // Compute expected root and trie updates via StorageRoot.
3482            let (expected_root, mut expected_trie_updates) = if changes.is_empty() {
3483                (self.original_root(), Default::default())
3484            } else {
3485                self.get_root_with_updates(&changes)
3486            };
3487
3488            self.minimize_trie_updates(&mut expected_trie_updates);
3489
3490            // Build leaf updates for the APST: non-zero values are upserts (RLP-encoded),
3491            // zero values are deletions (empty vec).
3492            let mut leaf_updates: B256Map<LeafUpdate> = changes
3493                .iter()
3494                .map(|(&slot, &value)| {
3495                    let rlp_value = if value.is_zero() {
3496                        Vec::new()
3497                    } else {
3498                        alloy_rlp::encode_fixed_size(&value).to_vec()
3499                    };
3500                    (slot, LeafUpdate::Changed(rlp_value))
3501                })
3502                .collect();
3503
3504            // Reveal-update loop: call update_leaves, collect required proofs, fetch them,
3505            // reveal, and repeat until no more proofs are needed.
3506            loop {
3507                let mut targets: Vec<ProofV2Target> = Vec::new();
3508                apst.update_leaves(&mut leaf_updates, |key, parent| {
3509                    targets.push(ProofV2Target::new(key).with_parent(parent));
3510                })
3511                .expect("update_leaves should succeed");
3512
3513                if targets.is_empty() {
3514                    break;
3515                }
3516
3517                let (mut proof_nodes, _) = self.proof_v2(&mut targets);
3518                apst.reveal_nodes(&mut proof_nodes).expect("reveal_nodes should succeed");
3519            }
3520
3521            // Compute root and take updates from the APST.
3522            let actual_root = apst.root(epoch(0));
3523            let mut actual_updates = apst.take_updates();
3524
3525            // Minimize sparse updates inline (can't use TrieTestHarness::minimize_sparse_updates
3526            // due to the crate's SparseTrieUpdates being a different type than reth-trie's copy).
3527            actual_updates.updated_nodes.retain(|path, node| {
3528                self.storage_trie_updates().storage_nodes.get(path) != Some(node)
3529            });
3530            actual_updates
3531                .removed_nodes
3532                .retain(|path| self.storage_trie_updates().storage_nodes.contains_key(path));
3533
3534            let mut expected_updated_nodes =
3535                expected_trie_updates.storage_nodes.into_iter().collect::<Vec<_>>();
3536            let mut actual_updated_nodes =
3537                actual_updates.updated_nodes.into_iter().collect::<Vec<_>>();
3538            expected_updated_nodes.sort();
3539            actual_updated_nodes.sort();
3540            pretty_assertions::assert_eq!(
3541                expected_updated_nodes,
3542                actual_updated_nodes,
3543                "updated nodes mismatch"
3544            );
3545
3546            let mut expected_removed_nodes =
3547                expected_trie_updates.removed_nodes.into_iter().collect::<Vec<_>>();
3548            let mut actual_removed_nodes =
3549                actual_updates.removed_nodes.into_iter().collect::<Vec<_>>();
3550            expected_removed_nodes.sort();
3551            actual_removed_nodes.sort();
3552            pretty_assertions::assert_eq!(
3553                expected_removed_nodes,
3554                actual_removed_nodes,
3555                "removed nodes mismatch"
3556            );
3557            assert_eq!(expected_root, actual_root, "storage root mismatch");
3558        }
3559    }
3560
3561    use proptest::prelude::*;
3562    use proptest_arbitrary_interop::arb;
3563
3564    /// Builds a changeset by mixing `new_keys` (fresh insertions) with a fraction of
3565    /// existing keys from `base` (updates/deletions).
3566    ///
3567    /// `overlap_pct` controls how many existing keys are included, and `delete_pct`
3568    /// controls how many of those become deletions (zero values). The remaining
3569    /// overlap keys get random non-zero values.
3570    fn build_changeset(
3571        base: &BTreeMap<B256, U256>,
3572        new_keys: BTreeMap<B256, U256>,
3573        overlap_pct: f64,
3574        delete_pct: f64,
3575        rng: &mut rand::rngs::StdRng,
3576    ) -> BTreeMap<B256, U256> {
3577        let num_overlap = (base.len() as f64 * overlap_pct) as usize;
3578        let num_delete = (num_overlap as f64 * delete_pct) as usize;
3579
3580        let mut all_keys: Vec<B256> = base.keys().copied().collect();
3581        all_keys.shuffle(rng);
3582        let overlap_keys = &all_keys[..num_overlap];
3583
3584        let mut changeset = new_keys;
3585        for (i, &key) in overlap_keys.iter().enumerate() {
3586            let value =
3587                if i < num_delete { U256::ZERO } else { U256::from(rng.random::<u64>() | 1) };
3588            changeset.entry(key).or_insert(value);
3589        }
3590        changeset
3591    }
3592
3593    proptest! {
3594        #![proptest_config(ProptestConfig::with_cases(1000))]
3595        #[reth_concurrency::test]
3596        fn arena_trie_proptest(
3597            initial in proptest::collection::btree_map(arb::<B256>(), arb::<U256>(), 0..=100usize),
3598            changeset1_new_keys in proptest::collection::btree_map(arb::<B256>(), arb::<U256>(), 0..=30usize),
3599            changeset2_new_keys in proptest::collection::btree_map(arb::<B256>(), arb::<U256>(), 0..=30usize),
3600            overlap_pct in 0.0..=0.5f64,
3601            delete_pct in 0.0..=0.33f64, // percent of overlapping changeset which are deletes
3602            shuffle_seed in arb::<u64>(),
3603        ) {
3604            reth_tracing::init_test_tracing();
3605            info!(target: TRACE_TARGET, ?shuffle_seed, "PROPTEST START");
3606
3607            // Filter out zero-valued entries from the initial dataset (zeros mean "absent").
3608            let initial: BTreeMap<B256, U256> = initial.into_iter()
3609            .filter(|(_, v)| !v.is_zero())
3610            .collect();
3611
3612            let mut rng = rand::rngs::StdRng::seed_from_u64(shuffle_seed);
3613
3614            let changeset1 = build_changeset(&initial, changeset1_new_keys, overlap_pct, delete_pct, &mut rng);
3615            for (i, (k, v)) in changeset1.iter().enumerate() {
3616            trace!(target: TRACE_TARGET, ?i, ?k, ?v, "Changeset 1 entry");
3617            }
3618
3619            let mut harness = ArenaTrieTestHarness::new(initial);
3620
3621            // Initialize the APST from the harness root node.
3622            let mut root_nodes = harness.root_nodes();
3623            let mut apst = ArenaParallelSparseTrie::default().with_parallelism_thresholds(
3624            ArenaParallelismThresholds {
3625                min_dirty_leaves: 3,
3626                min_revealed_nodes: 3,
3627                min_updates: 3,
3628                min_leaves_for_prune: 3,
3629            },
3630            );
3631            apst.set_root(&mut root_nodes, true).expect("set_root should succeed");
3632
3633            harness.assert_changes(&mut apst, changeset1.clone());
3634
3635            // Update the harness base dataset to reflect the first changeset.
3636            harness.apply_changeset(changeset1);
3637
3638            // All nodes were cached at epoch 0, so this maximally prunes the trie before the
3639            // second update round.
3640            apst.prune(epoch(1));
3641
3642            let changeset2 = build_changeset(harness.storage(), changeset2_new_keys, overlap_pct, delete_pct, &mut rng);
3643            for (i, (k, v)) in changeset2.iter().enumerate() {
3644            trace!(target: TRACE_TARGET, ?i, ?k, ?v, "Changeset 2 entry");
3645            }
3646
3647            harness.assert_changes(&mut apst, changeset2);
3648        }
3649    }
3650}