Skip to main content

reth_trie_sparse/
state.rs

1use crate::{
2    traits::SparseTrie as SparseTrieTrait, ArenaParallelSparseTrie, RevealableSparseTrie,
3    TrieNodeEpoch,
4};
5use alloc::vec::Vec;
6use alloy_primitives::{map::B256Map, B256};
7use either::Either;
8use reth_execution_errors::{SparseStateTrieResult, SparseTrieErrorKind};
9use reth_trie_common::{
10    updates::{StorageTrieUpdates, TrieUpdates},
11    DecodedMultiProof, MultiProof, Nibbles, ProofTrieNode,
12};
13use tracing::instrument;
14
15#[cfg(feature = "std")]
16use reth_concurrency::sync::rayon::{
17    self,
18    iter::{IntoParallelIterator, IntoParallelRefMutIterator, ParallelIterator},
19};
20#[cfg(feature = "std")]
21use tracing::debug;
22
23/// Holds data that should be dropped after any locks are released.
24///
25/// This is used to defer expensive deallocations (like proof node buffers) until after final state
26/// root is calculated
27#[derive(Debug, Default)]
28pub struct DeferredDrops {
29    /// Each nodes reveal operation creates a new buffer, uses it, and pushes it here.
30    pub proof_nodes_bufs: Vec<Vec<ProofTrieNode>>,
31}
32
33#[derive(Debug)]
34/// Sparse state trie representing lazy-loaded Ethereum state trie.
35pub struct SparseStateTrie<
36    A = ArenaParallelSparseTrie, // Account trie implementation
37    S = ArenaParallelSparseTrie, // Storage trie implementation
38> {
39    /// Sparse account trie.
40    state: RevealableSparseTrie<A>,
41    /// State related to storage tries.
42    storage: StorageTries<S>,
43    /// Flag indicating whether trie updates should be retained.
44    retain_updates: bool,
45    /// Holds data that should be dropped after final state root is calculated.
46    deferred_drops: DeferredDrops,
47    /// Metrics for the sparse state trie.
48    #[cfg(feature = "metrics")]
49    metrics: crate::metrics::SparseStateTrieMetrics,
50}
51
52impl<A, S> Default for SparseStateTrie<A, S>
53where
54    A: Default,
55    S: Default,
56{
57    fn default() -> Self {
58        Self {
59            state: Default::default(),
60            storage: Default::default(),
61            retain_updates: false,
62            deferred_drops: DeferredDrops::default(),
63            #[cfg(feature = "metrics")]
64            metrics: Default::default(),
65        }
66    }
67}
68
69#[cfg(test)]
70impl SparseStateTrie {
71    /// Create state trie from state trie.
72    pub fn from_state(state: RevealableSparseTrie) -> Self {
73        Self { state, ..Default::default() }
74    }
75}
76
77impl<A, S> SparseStateTrie<A, S> {
78    /// Set the retention of branch node updates and deletions.
79    pub const fn set_updates(&mut self, retain_updates: bool) {
80        self.retain_updates = retain_updates;
81    }
82
83    /// Set the retention of branch node updates and deletions.
84    pub const fn with_updates(mut self, retain_updates: bool) -> Self {
85        self.set_updates(retain_updates);
86        self
87    }
88
89    /// Returns whether branch node updates and deletions are retained.
90    pub const fn retains_updates(&self) -> bool {
91        self.retain_updates
92    }
93
94    /// Set the accounts trie to the given `RevealableSparseTrie`.
95    pub fn set_accounts_trie(&mut self, trie: RevealableSparseTrie<A>) {
96        self.state = trie;
97    }
98
99    /// Set the accounts trie to the given `RevealableSparseTrie`.
100    pub fn with_accounts_trie(mut self, trie: RevealableSparseTrie<A>) -> Self {
101        self.set_accounts_trie(trie);
102        self
103    }
104
105    /// Set the default trie which will be cloned when creating new storage
106    /// [`RevealableSparseTrie`]s.
107    pub fn set_default_storage_trie(&mut self, trie: RevealableSparseTrie<S>) {
108        self.storage.default_trie = trie;
109    }
110
111    /// Set the default trie which will be cloned when creating new storage
112    /// [`RevealableSparseTrie`]s.
113    pub fn with_default_storage_trie(mut self, trie: RevealableSparseTrie<S>) -> Self {
114        self.set_default_storage_trie(trie);
115        self
116    }
117
118    /// Takes the data structures for deferred dropping.
119    ///
120    /// This allows the caller to drop the buffers later, avoiding expensive deallocations while
121    /// calculating the state root.
122    pub fn take_deferred_drops(&mut self) -> DeferredDrops {
123        core::mem::take(&mut self.deferred_drops)
124    }
125}
126
127impl SparseStateTrie {
128    /// Create new [`SparseStateTrie`] with the default trie implementation.
129    pub fn new() -> Self {
130        Self::default()
131    }
132}
133
134impl<A, S> SparseStateTrie<A, S>
135where
136    A: SparseTrieTrait + Default,
137    S: SparseTrieTrait + Default + Clone,
138{
139    /// Returns mutable reference to account trie.
140    pub const fn trie_mut(&mut self) -> &mut RevealableSparseTrie<A> {
141        &mut self.state
142    }
143
144    /// Returns `true` if the account path has been revealed in the sparse trie.
145    pub fn is_account_revealed(&self, account: B256) -> bool {
146        let path = Nibbles::unpack(account);
147        let trie = match self.state_trie_ref() {
148            Some(t) => t,
149            None => return false,
150        };
151
152        trie.find_leaf(&path, None).is_ok()
153    }
154
155    /// Was the storage-slot witness for (`address`,`slot`) complete?
156    pub fn check_valid_storage_witness(&self, address: B256, slot: B256) -> bool {
157        let path = Nibbles::unpack(slot);
158        let trie = match self.storage_trie_ref(&address) {
159            Some(t) => t,
160            None => return false,
161        };
162
163        trie.find_leaf(&path, None).is_ok()
164    }
165
166    /// Returns reference to bytes representing leaf value for the target account.
167    pub fn get_account_value(&self, account: &B256) -> Option<&Vec<u8>> {
168        self.state.as_revealed_ref()?.get_leaf_value(&Nibbles::unpack(account))
169    }
170
171    /// Returns reference to bytes representing leaf value for the target account and storage slot.
172    pub fn get_storage_slot_value(&self, account: &B256, slot: &B256) -> Option<&Vec<u8>> {
173        self.storage.tries.get(account)?.as_revealed_ref()?.get_leaf_value(&Nibbles::unpack(slot))
174    }
175
176    /// Returns reference to state trie if it was revealed.
177    pub const fn state_trie_ref(&self) -> Option<&A> {
178        self.state.as_revealed_ref()
179    }
180
181    /// Returns reference to storage trie if it was revealed.
182    pub fn storage_trie_ref(&self, address: &B256) -> Option<&S> {
183        self.storage.tries.get(address).and_then(|e| e.as_revealed_ref())
184    }
185
186    /// Returns mutable reference to storage sparse trie if it was revealed.
187    pub fn storage_trie_mut(&mut self, address: &B256) -> Option<&mut S> {
188        self.storage.tries.get_mut(address).and_then(|e| e.as_revealed_mut())
189    }
190
191    /// Returns mutable reference to storage tries.
192    pub const fn storage_tries_mut(&mut self) -> &mut B256Map<RevealableSparseTrie<S>> {
193        &mut self.storage.tries
194    }
195
196    /// Takes the storage trie for the provided address.
197    pub fn take_storage_trie(&mut self, address: &B256) -> Option<RevealableSparseTrie<S>> {
198        self.storage.tries.remove(address)
199    }
200
201    /// Takes the storage trie for the provided address, creating a blind one if it doesn't exist.
202    pub fn take_or_create_storage_trie(&mut self, address: &B256) -> RevealableSparseTrie<S> {
203        self.storage.tries.remove(address).unwrap_or_else(|| {
204            self.storage.cleared_tries.pop().unwrap_or_else(|| self.storage.default_trie.clone())
205        })
206    }
207
208    /// Inserts storage trie for the provided address.
209    pub fn insert_storage_trie(&mut self, address: B256, storage_trie: RevealableSparseTrie<S>) {
210        self.storage.tries.insert(address, storage_trie);
211    }
212
213    /// Returns mutable reference to storage sparse trie, creating a blind one if it doesn't exist.
214    pub fn get_or_create_storage_trie_mut(
215        &mut self,
216        address: B256,
217    ) -> &mut RevealableSparseTrie<S> {
218        self.storage.get_or_create_trie_mut(address)
219    }
220
221    /// Reveal unknown trie paths from multiproof.
222    /// NOTE: This method does not extensively validate the proof.
223    pub fn reveal_multiproof(&mut self, multiproof: MultiProof) -> SparseStateTrieResult<()> {
224        // first decode the multiproof
225        let decoded_multiproof = multiproof.try_into()?;
226
227        // then reveal the decoded multiproof
228        self.reveal_decoded_multiproof(decoded_multiproof)
229    }
230
231    /// Reveal unknown trie paths from decoded multiproof.
232    /// NOTE: This method does not extensively validate the proof.
233    #[instrument(level = "debug", target = "trie::sparse", skip_all)]
234    pub fn reveal_decoded_multiproof(
235        &mut self,
236        multiproof: DecodedMultiProof,
237    ) -> SparseStateTrieResult<()> {
238        self.reveal_decoded_multiproof_v2(multiproof.into())
239    }
240
241    /// Reveals a V2 decoded multiproof.
242    ///
243    /// V2 multiproofs use a simpler format where proof nodes are stored as vectors rather than
244    /// hashmaps, with masks already included in the `ProofTrieNode` structure.
245    #[instrument(level = "debug", target = "trie::sparse", skip_all)]
246    pub fn reveal_decoded_multiproof_v2(
247        &mut self,
248        multiproof: reth_trie_common::DecodedMultiProofV2,
249    ) -> SparseStateTrieResult<()> {
250        let reth_trie_common::DecodedMultiProofV2 { account_proofs, mut storage_proofs, .. } =
251            multiproof;
252
253        // Collect `(trie, proof_nodes)` pairs for both the account trie and every storage trie
254        // touched by this multiproof.
255        let mut targets = Vec::with_capacity(storage_proofs.len() + 1);
256
257        if !account_proofs.is_empty() {
258            #[cfg(feature = "metrics")]
259            self.metrics.increment_total_account_nodes(account_proofs.len() as u64);
260            targets.push((None, Either::Left(&mut self.state), account_proofs));
261        }
262
263        // Ensure a storage trie exists for every address whose proofs we're about to reveal
264        for &account in storage_proofs.keys() {
265            let _ = self.storage.get_or_create_trie_mut(account);
266        }
267
268        for (account, trie) in &mut self.storage.tries {
269            if let Some(nodes) = storage_proofs.remove(account) {
270                #[cfg(feature = "metrics")]
271                self.metrics.increment_total_storage_nodes(nodes.len() as u64);
272                targets.push((Some(*account), Either::Right(trie), nodes));
273            }
274        }
275
276        let retain_updates = self.retain_updates;
277
278        #[cfg(not(feature = "std"))]
279        let results: Vec<_> = targets
280            .into_iter()
281            .map(|(_, target, mut nodes)| {
282                let result = match target {
283                    Either::Left(trie) => trie.reveal_v2_proof_nodes(&mut nodes, retain_updates),
284                    Either::Right(trie) => trie.reveal_v2_proof_nodes(&mut nodes, retain_updates),
285                };
286                (result, nodes)
287            })
288            .collect();
289
290        #[cfg(feature = "std")]
291        let results: Vec<_> = {
292            let parent_span = tracing::Span::current();
293            targets
294                .into_par_iter()
295                .map(|(hashed_address, target, mut nodes)| {
296                    let _span = tracing::trace_span!(
297                        target: "trie::sparse",
298                        parent: &parent_span,
299                        "reveal_v2_proof_nodes",
300                        ?hashed_address,
301                    )
302                    .entered();
303
304                    let result = match target {
305                        Either::Left(trie) => {
306                            trie.reveal_v2_proof_nodes(&mut nodes, retain_updates)
307                        }
308                        Either::Right(trie) => {
309                            trie.reveal_v2_proof_nodes(&mut nodes, retain_updates)
310                        }
311                    };
312                    (result, nodes)
313                })
314                .collect()
315        };
316
317        // Accumulate the first error and defer dropping the proof node buffers.
318        let mut any_err = Ok(());
319        for (result, nodes) in results {
320            if result.is_err() && any_err.is_ok() {
321                any_err = result.map_err(Into::into);
322            }
323            self.deferred_drops.proof_nodes_bufs.push(nodes);
324        }
325
326        any_err
327    }
328
329    /// Reveals account trie proof nodes on the calling thread.
330    ///
331    /// Unlike [`Self::reveal_decoded_multiproof_v2`] this touches only the account trie, so a
332    /// caller that owns some of the storage tries itself can reveal the two halves separately.
333    pub fn reveal_account_proof_nodes(
334        &mut self,
335        mut nodes: Vec<ProofTrieNode>,
336    ) -> SparseStateTrieResult<()> {
337        if nodes.is_empty() {
338            return Ok(());
339        }
340
341        #[cfg(feature = "metrics")]
342        self.metrics.increment_total_account_nodes(nodes.len() as u64);
343
344        let result = self.state.reveal_v2_proof_nodes(&mut nodes, self.retain_updates);
345        self.deferred_drops.proof_nodes_bufs.push(nodes);
346
347        Ok(result?)
348    }
349
350    /// Records storage trie nodes that were revealed into a trie taken out of this state trie, so
351    /// the reveal metrics stay complete.
352    pub const fn record_revealed_storage_nodes(&mut self, nodes: usize) {
353        #[cfg(feature = "metrics")]
354        self.metrics.increment_total_storage_nodes(nodes as u64);
355        #[cfg(not(feature = "metrics"))]
356        let _ = nodes;
357    }
358
359    /// Calculates the hashes of subtries.
360    ///
361    /// If the trie has not been revealed, this function does nothing.
362    #[instrument(level = "debug", target = "trie::sparse", skip_all)]
363    pub fn calculate_subtries(&mut self, new_epoch: TrieNodeEpoch) {
364        if let RevealableSparseTrie::Revealed(trie) = &mut self.state {
365            trie.update_subtrie_hashes(new_epoch);
366        }
367    }
368
369    /// Returns storage sparse trie root if the trie has been revealed.
370    pub fn storage_root(&mut self, account: &B256, new_epoch: TrieNodeEpoch) -> Option<B256> {
371        self.storage.tries.get_mut(account).and_then(|trie| trie.root(new_epoch))
372    }
373
374    /// Returns the roots of all revealed storage tries, keyed by hashed account address.
375    ///
376    /// Dirty roots are computed at `new_epoch`; blind storage tries are omitted.
377    pub fn storage_roots(&mut self, new_epoch: TrieNodeEpoch) -> B256Map<B256> {
378        self.storage
379            .tries
380            .iter_mut()
381            .filter_map(|(address, trie)| trie.root(new_epoch).map(|root| (*address, root)))
382            .collect()
383    }
384
385    /// Returns mutable reference to the revealed account sparse trie.
386    fn revealed_trie_mut(&mut self) -> SparseStateTrieResult<&mut A> {
387        self.state.as_revealed_mut().ok_or_else(|| SparseTrieErrorKind::Blind.into())
388    }
389
390    /// Returns sparse trie root.
391    pub fn root(&mut self, new_epoch: TrieNodeEpoch) -> SparseStateTrieResult<B256> {
392        // record revealed node metrics
393        #[cfg(feature = "metrics")]
394        self.metrics.record();
395
396        Ok(self.revealed_trie_mut()?.root(new_epoch))
397    }
398
399    /// Returns sparse trie root and trie updates.
400    ///
401    /// Returns an error if the account trie is still blind.
402    #[instrument(level = "debug", target = "trie::sparse", skip_all)]
403    pub fn root_with_updates(
404        &mut self,
405        new_epoch: TrieNodeEpoch,
406    ) -> SparseStateTrieResult<(B256, TrieUpdates)> {
407        // record revealed node metrics
408        #[cfg(feature = "metrics")]
409        self.metrics.record();
410
411        let storage_tries = self.storage_trie_updates();
412        let revealed = self.revealed_trie_mut()?;
413
414        let (root, updates) = (revealed.root(new_epoch), revealed.take_updates());
415        let updates = TrieUpdates {
416            account_nodes: updates.updated_nodes,
417            removed_nodes: updates.removed_nodes,
418            storage_tries,
419        };
420        Ok((root, updates))
421    }
422
423    /// Returns storage trie updates for tries that have been revealed.
424    ///
425    /// Panics if any of the storage tries are not revealed.
426    pub fn storage_trie_updates(&mut self) -> B256Map<StorageTrieUpdates> {
427        self.storage
428            .tries
429            .iter_mut()
430            .map(|(address, trie)| {
431                let trie = trie.as_revealed_mut().unwrap();
432                let updates = trie.take_updates();
433                let updates = StorageTrieUpdates {
434                    storage_nodes: updates.updated_nodes,
435                    removed_nodes: updates.removed_nodes,
436                };
437                (*address, updates)
438            })
439            .filter(|(_, updates)| !updates.is_empty())
440            .collect()
441    }
442
443    /// Returns [`TrieUpdates`] by taking the updates from the revealed sparse tries.
444    ///
445    /// Returns `None` if the accounts trie is not revealed.
446    pub fn take_trie_updates(&mut self) -> Option<TrieUpdates> {
447        let storage_tries = self.storage_trie_updates();
448        self.state.as_revealed_mut().map(|state| {
449            let updates = state.take_updates();
450            TrieUpdates {
451                account_nodes: updates.updated_nodes,
452                removed_nodes: updates.removed_nodes,
453                storage_tries,
454            }
455        })
456    }
457}
458
459impl<A, S> SparseStateTrie<A, S>
460where
461    A: SparseTrieTrait + Default,
462    S: SparseTrieTrait + Default + Clone,
463{
464    /// Clears all trie data while preserving allocations for reuse.
465    ///
466    /// This resets the trie to an empty state but keeps the underlying memory allocations,
467    /// which can significantly reduce allocation overhead when the trie is reused.
468    pub fn clear(&mut self) {
469        self.state.clear();
470        self.storage.clear();
471    }
472
473    /// Returns the number of storage tries currently retained (active + cleared).
474    pub fn retained_storage_tries_count(&self) -> usize {
475        self.storage.tries.len() + self.storage.cleared_tries.len()
476    }
477
478    /// Prunes account and storage trie nodes last modified before `prune_before`.
479    ///
480    /// Storage tries whose root epochs predate the cutoff are fully evicted.
481    ///
482    /// # Preconditions
483    ///
484    /// Modified account and storage tries must already have computed hashes via `root()` /
485    /// `storage_root()` for their current state. Unmodified storage roots revealed only by
486    /// prewarming are treated as epoch zero.
487    #[cfg(feature = "std")]
488    #[instrument(
489        level = "debug",
490        name = "SparseStateTrie::prune",
491        target = "trie::sparse",
492        skip_all
493    )]
494    pub fn prune(&mut self, prune_before: TrieNodeEpoch) {
495        let total_storage_tries_before = self.storage.tries.len();
496
497        let parent_span = tracing::Span::current();
498        let account_parent_span = parent_span.clone();
499
500        // Prune account and storage tries in parallel using the same epoch cutoff.
501        let (account_nodes_pruned, storage_tries_evicted) = rayon::join(
502            || {
503                let hashed_address = Option::<B256>::None;
504                let _span = tracing::trace_span!(
505                    target: "trie::sparse",
506                    parent: &account_parent_span,
507                    "prune_trie",
508                    ?hashed_address,
509                )
510                .entered();
511
512                self.state.as_revealed_mut().map(|trie| trie.prune(prune_before)).unwrap_or(0)
513            },
514            || self.storage.prune(prune_before, &parent_span),
515        );
516
517        debug!(
518            target: "trie::sparse",
519            prune_before = prune_before.get(),
520            account_nodes_pruned,
521            storage_tries_evicted,
522            storage_tries_after = total_storage_tries_before - storage_tries_evicted,
523            "SparseStateTrie::prune completed"
524        );
525    }
526}
527
528/// The fields of [`SparseStateTrie`] related to storage tries. This is kept separate from the rest
529/// of [`SparseStateTrie`] to help enforce allocation re-use.
530#[derive(Debug, Default)]
531struct StorageTries<S = ArenaParallelSparseTrie> {
532    /// Sparse storage tries.
533    tries: B256Map<RevealableSparseTrie<S>>,
534    /// Cleared storage tries, kept for re-use.
535    cleared_tries: Vec<RevealableSparseTrie<S>>,
536    /// A default cleared trie instance, which will be cloned when creating new tries.
537    default_trie: RevealableSparseTrie<S>,
538}
539
540#[cfg(feature = "std")]
541impl<S: SparseTrieTrait> StorageTries<S> {
542    /// Prunes storage tries by epoch, returning fully old tries to the reuse pool.
543    fn prune(&mut self, prune_before: TrieNodeEpoch, parent_span: &tracing::Span) -> usize {
544        let addresses_to_evict: Vec<B256> = self
545            .tries
546            .par_iter_mut()
547            .filter_map(|(address, trie)| {
548                let hashed_address = Some(*address);
549                let _span = tracing::trace_span!(
550                    target: "trie::sparse",
551                    parent: parent_span,
552                    "prune_trie",
553                    ?hashed_address,
554                )
555                .entered();
556
557                let evict = trie.as_revealed_mut().is_none_or(|revealed| {
558                    // Avoid traversing and compacting a trie that will be immediately evicted.
559                    let root_epoch =
560                        revealed.root_epoch().expect("storage trie root must not be dirty");
561                    if !root_epoch.should_prune(prune_before) {
562                        revealed.prune(prune_before);
563                    }
564                    root_epoch.should_prune(prune_before)
565                });
566
567                evict.then(|| {
568                    trie.clear();
569                    *address
570                })
571            })
572            .collect();
573
574        let evicted = addresses_to_evict.len();
575        self.cleared_tries.reserve(evicted);
576        for address in addresses_to_evict {
577            if let Some(trie) = self.tries.remove(&address) {
578                self.cleared_tries.push(trie);
579            }
580        }
581
582        evicted
583    }
584}
585
586impl<S: SparseTrieTrait> StorageTries<S> {
587    /// Returns all fields to a cleared state, equivalent to the default state, keeping cleared
588    /// collections for re-use later when possible.
589    fn clear(&mut self) {
590        self.cleared_tries.extend(self.tries.drain().map(|(_, mut trie)| {
591            trie.clear();
592            trie
593        }));
594    }
595}
596
597impl<S: SparseTrieTrait + Clone> StorageTries<S> {
598    // Returns mutable reference to storage sparse trie, creating a blind one if it doesn't exist.
599    fn get_or_create_trie_mut(&mut self, address: B256) -> &mut RevealableSparseTrie<S> {
600        self.tries.entry(address).or_insert_with(|| {
601            self.cleared_tries.pop().unwrap_or_else(|| self.default_trie.clone())
602        })
603    }
604}
605
606#[cfg(test)]
607mod tests {
608    use super::*;
609    use crate::{ArenaParallelSparseTrie, LeafLookup, LeafUpdate};
610    use alloy_primitives::{
611        b256,
612        map::{HashMap, HashSet},
613        U256,
614    };
615    use arbitrary::Arbitrary;
616    use rand::{rngs::StdRng, Rng, SeedableRng};
617    use reth_concurrency::sync::Runtime;
618    use reth_execution_errors::{SparseStateTrieErrorKind, SparseTrieErrorKind};
619    use reth_primitives_traits::Account;
620    use reth_trie::{updates::StorageTrieUpdates, HashBuilder, MultiProof, EMPTY_ROOT_HASH};
621    use reth_trie_common::{
622        proof::{ProofNodes, ProofRetainer},
623        BranchNode, BranchNodeMasks, BranchNodeMasksMap, LeafNode, RlpNode, StorageMultiProof,
624        TrieAccount, TrieMask, TrieNode,
625    };
626
627    const fn epoch(value: u64) -> TrieNodeEpoch {
628        TrieNodeEpoch::new(value)
629    }
630
631    /// Create a leaf key (suffix) with given nibbles padded with zeros to reach `total_len`.
632    fn leaf_key(suffix: impl AsRef<[u8]>, total_len: usize) -> Nibbles {
633        let suffix = suffix.as_ref();
634        let mut nibbles = Nibbles::from_nibbles(suffix);
635        nibbles.extend(&Nibbles::from_nibbles_unchecked(vec![0; total_len - suffix.len()]));
636        nibbles
637    }
638
639    fn apply_account_update(sparse: &mut SparseStateTrie, address: B256, update: LeafUpdate) {
640        let mut updates = B256Map::from_iter([(address, update)]);
641        sparse.trie_mut().update_leaves(&mut updates, |_, _| {}).unwrap();
642        assert!(updates.is_empty());
643    }
644
645    #[reth_concurrency::test]
646    fn reveal_account_path_twice() {
647        let mut sparse = SparseStateTrie::<ArenaParallelSparseTrie>::default();
648
649        // Full 64-nibble paths
650        let full_path_0 = leaf_key([0x0], 64);
651        let _full_path_1 = leaf_key([0x1], 64);
652
653        let leaf_value = alloy_rlp::encode(TrieAccount::default());
654        // Leaf key is 63 nibbles (suffix after 1-nibble node path)
655        let leaf_1 =
656            alloy_rlp::encode(TrieNode::Leaf(LeafNode::new(leaf_key([], 63), leaf_value.clone())));
657        let leaf_2 =
658            alloy_rlp::encode(TrieNode::Leaf(LeafNode::new(leaf_key([], 63), leaf_value.clone())));
659
660        let multiproof = MultiProof {
661            account_subtree: ProofNodes::from_iter([
662                (
663                    Nibbles::default(),
664                    alloy_rlp::encode(TrieNode::Branch(BranchNode {
665                        stack: vec![RlpNode::from_rlp(&leaf_1), RlpNode::from_rlp(&leaf_2)],
666                        state_mask: TrieMask::new(0b11),
667                    }))
668                    .into(),
669                ),
670                (Nibbles::from_nibbles([0x0]), leaf_1.clone().into()),
671                (Nibbles::from_nibbles([0x1]), leaf_1.clone().into()),
672            ]),
673            ..Default::default()
674        };
675
676        // Reveal multiproof and check that the state trie contains the leaf node and value
677        sparse.reveal_decoded_multiproof(multiproof.try_into().unwrap()).unwrap();
678        assert!(matches!(
679            sparse.state_trie_ref().unwrap().find_leaf(&full_path_0, None),
680            Ok(LeafLookup::Exists)
681        ));
682        assert_eq!(
683            sparse.state_trie_ref().unwrap().get_leaf_value(&full_path_0),
684            Some(&leaf_value)
685        );
686
687        // Remove the leaf node and check that the state trie does not contain the leaf node and
688        // value
689        apply_account_update(&mut sparse, B256::ZERO, LeafUpdate::Changed(Vec::new()));
690        assert!(matches!(
691            sparse.state_trie_ref().unwrap().find_leaf(&full_path_0, None),
692            Ok(LeafLookup::NonExistent)
693        ));
694        assert!(sparse.state_trie_ref().unwrap().get_leaf_value(&full_path_0).is_none());
695    }
696
697    #[reth_concurrency::test]
698    fn reveal_storage_path_twice() {
699        let mut sparse = SparseStateTrie::<ArenaParallelSparseTrie>::default();
700
701        // Full 64-nibble path
702        let full_path_0 = leaf_key([0x0], 64);
703
704        let leaf_value = alloy_rlp::encode(TrieAccount::default());
705        let leaf_1 =
706            alloy_rlp::encode(TrieNode::Leaf(LeafNode::new(leaf_key([], 63), leaf_value.clone())));
707        let leaf_2 =
708            alloy_rlp::encode(TrieNode::Leaf(LeafNode::new(leaf_key([], 63), leaf_value.clone())));
709
710        let multiproof = MultiProof {
711            storages: HashMap::from_iter([(
712                B256::ZERO,
713                StorageMultiProof {
714                    root: B256::ZERO,
715                    subtree: ProofNodes::from_iter([
716                        (
717                            Nibbles::default(),
718                            alloy_rlp::encode(TrieNode::Branch(BranchNode {
719                                stack: vec![RlpNode::from_rlp(&leaf_1), RlpNode::from_rlp(&leaf_2)],
720                                state_mask: TrieMask::new(0b11),
721                            }))
722                            .into(),
723                        ),
724                        (Nibbles::from_nibbles([0x0]), leaf_1.clone().into()),
725                        (Nibbles::from_nibbles([0x1]), leaf_1.clone().into()),
726                    ]),
727                    branch_node_masks: Default::default(),
728                },
729            )]),
730            ..Default::default()
731        };
732
733        // Reveal multiproof and check that the storage trie contains the leaf node and value
734        sparse.reveal_decoded_multiproof(multiproof.try_into().unwrap()).unwrap();
735        assert!(matches!(
736            sparse.storage_trie_ref(&B256::ZERO).unwrap().find_leaf(&full_path_0, None),
737            Ok(LeafLookup::Exists)
738        ));
739        assert_eq!(
740            sparse.storage_trie_ref(&B256::ZERO).unwrap().get_leaf_value(&full_path_0),
741            Some(&leaf_value)
742        );
743
744        // Remove the leaf node and check that the storage trie does not contain the leaf node and
745        // value
746        let mut updates = B256Map::from_iter([(B256::ZERO, LeafUpdate::Changed(Vec::new()))]);
747        sparse
748            .storage_trie_mut(&B256::ZERO)
749            .unwrap()
750            .update_leaves(&mut updates, |_, _| {})
751            .unwrap();
752        assert!(updates.is_empty());
753        assert!(matches!(
754            sparse.storage_trie_ref(&B256::ZERO).unwrap().find_leaf(&full_path_0, None),
755            Ok(LeafLookup::NonExistent)
756        ));
757        assert!(sparse
758            .storage_trie_ref(&B256::ZERO)
759            .unwrap()
760            .get_leaf_value(&full_path_0)
761            .is_none());
762    }
763
764    #[reth_concurrency::test]
765    fn prune_uses_epochs_for_account_and_storage_tries() {
766        let mut sparse = SparseStateTrie::<ArenaParallelSparseTrie>::default();
767
768        let account = B256::ZERO;
769        let old_account =
770            b256!("0x1000000000000000000000000000000000000000000000000000000000000000");
771        let prewarmed_account =
772            b256!("0x2000000000000000000000000000000000000000000000000000000000000000");
773        let slot = B256::ZERO;
774        let account_path = leaf_key([0x0], 64);
775        let old_account_path = leaf_key([0x1], 64);
776        let storage_path = leaf_key([0x0], 64);
777
778        let leaf_value = alloy_rlp::encode(TrieAccount::default());
779        let leaf_0 =
780            alloy_rlp::encode(TrieNode::Leaf(LeafNode::new(leaf_key([], 63), leaf_value.clone())));
781        let leaf_1 = alloy_rlp::encode(TrieNode::Leaf(LeafNode::new(leaf_key([], 63), leaf_value)));
782
783        let subtree = || {
784            ProofNodes::from_iter([
785                (
786                    Nibbles::default(),
787                    alloy_rlp::encode(TrieNode::Branch(BranchNode {
788                        stack: vec![RlpNode::from_rlp(&leaf_0), RlpNode::from_rlp(&leaf_1)],
789                        state_mask: TrieMask::new(0b11),
790                    }))
791                    .into(),
792                ),
793                (Nibbles::from_nibbles([0x0]), leaf_0.clone().into()),
794                (Nibbles::from_nibbles([0x1]), leaf_1.clone().into()),
795            ])
796        };
797
798        let multiproof = MultiProof {
799            account_subtree: subtree(),
800            storages: HashMap::from_iter([
801                (
802                    account,
803                    StorageMultiProof {
804                        root: B256::ZERO,
805                        subtree: subtree(),
806                        branch_node_masks: Default::default(),
807                    },
808                ),
809                (
810                    old_account,
811                    StorageMultiProof {
812                        root: B256::ZERO,
813                        subtree: subtree(),
814                        branch_node_masks: Default::default(),
815                    },
816                ),
817                (
818                    prewarmed_account,
819                    StorageMultiProof {
820                        root: B256::ZERO,
821                        subtree: subtree(),
822                        branch_node_masks: Default::default(),
823                    },
824                ),
825            ]),
826            ..Default::default()
827        };
828
829        sparse.reveal_decoded_multiproof(multiproof.try_into().unwrap()).unwrap();
830
831        sparse.storage_root(&account, epoch(0)).unwrap();
832        sparse.storage_root(&old_account, epoch(0)).unwrap();
833        sparse.root(epoch(0)).unwrap();
834        assert!(!sparse.storage_trie_ref(&prewarmed_account).unwrap().is_root_cached());
835
836        let mut storage_updates = B256Map::from_iter([(
837            slot,
838            LeafUpdate::Changed(alloy_rlp::encode_fixed_size(&U256::from(2)).to_vec()),
839        )]);
840        sparse
841            .storage_trie_mut(&account)
842            .unwrap()
843            .update_leaves(&mut storage_updates, |_, _| {
844                panic!("fully revealed storage trie must not request proofs")
845            })
846            .unwrap();
847        assert!(storage_updates.is_empty());
848
849        let trie_account = TrieAccount {
850            storage_root: sparse.storage_root(&account, epoch(10)).unwrap(),
851            ..Default::default()
852        };
853        apply_account_update(
854            &mut sparse,
855            account,
856            LeafUpdate::Changed(alloy_rlp::encode(trie_account)),
857        );
858        let root_before = sparse.root(epoch(10)).unwrap();
859        sparse.prune(epoch(10));
860
861        assert!(matches!(
862            sparse.state_trie_ref().unwrap().find_leaf(&account_path, None),
863            Ok(LeafLookup::Exists)
864        ));
865        assert!(matches!(
866            sparse.storage_trie_ref(&account).unwrap().find_leaf(&storage_path, None),
867            Ok(LeafLookup::Exists)
868        ));
869        assert!(matches!(
870            sparse.state_trie_ref().unwrap().find_leaf(&old_account_path, None),
871            Err(crate::LeafLookupError::BlindedNode { .. })
872        ));
873        assert!(sparse.storage_trie_ref(&old_account).is_none());
874        assert!(sparse.storage_trie_ref(&prewarmed_account).is_none());
875        assert_eq!(sparse.root(epoch(10)).unwrap(), root_before);
876
877        // An intermediate storage root does not advance without another change, so the trie
878        // becomes eligible once the cutoff passes its last modification epoch.
879        sparse.prune(epoch(11));
880        assert!(sparse.storage_trie_ref(&account).is_none());
881        assert_eq!(sparse.root(epoch(11)).unwrap(), root_before);
882    }
883
884    #[reth_concurrency::test]
885    fn reveal_v2_proof_nodes() {
886        let mut sparse = SparseStateTrie::<ArenaParallelSparseTrie>::default();
887
888        // Full 64-nibble path
889        let full_path_0 = leaf_key([0x0], 64);
890
891        let leaf_value = alloy_rlp::encode(TrieAccount::default());
892        let leaf_1_node = TrieNode::Leaf(LeafNode::new(leaf_key([], 63), leaf_value.clone()));
893        let leaf_2_node = TrieNode::Leaf(LeafNode::new(leaf_key([], 63), leaf_value.clone()));
894
895        let branch_node = TrieNode::Branch(BranchNode {
896            stack: vec![
897                RlpNode::from_rlp(&alloy_rlp::encode(&leaf_1_node)),
898                RlpNode::from_rlp(&alloy_rlp::encode(&leaf_2_node)),
899            ],
900            state_mask: TrieMask::new(0b11),
901        });
902
903        // Create V2 proof nodes with masks already included
904        let v2_proof_nodes = vec![
905            ProofTrieNode {
906                path: Nibbles::default(),
907                node: branch_node,
908                masks: Some(BranchNodeMasks {
909                    hash_mask: TrieMask::default(),
910                    tree_mask: TrieMask::default(),
911                }),
912            },
913            ProofTrieNode { path: Nibbles::from_nibbles([0x0]), node: leaf_1_node, masks: None },
914            ProofTrieNode { path: Nibbles::from_nibbles([0x1]), node: leaf_2_node, masks: None },
915        ];
916
917        // Reveal V2 proof nodes
918        sparse
919            .reveal_decoded_multiproof_v2(reth_trie_common::DecodedMultiProofV2 {
920                account_proofs: v2_proof_nodes,
921                ..Default::default()
922            })
923            .unwrap();
924
925        // Check that the state trie contains the leaf node and value
926        assert!(matches!(
927            sparse.state_trie_ref().unwrap().find_leaf(&full_path_0, None),
928            Ok(LeafLookup::Exists)
929        ));
930        assert_eq!(
931            sparse.state_trie_ref().unwrap().get_leaf_value(&full_path_0),
932            Some(&leaf_value)
933        );
934
935        // Remove the leaf node
936        apply_account_update(&mut sparse, B256::ZERO, LeafUpdate::Changed(Vec::new()));
937        assert!(sparse.state_trie_ref().unwrap().get_leaf_value(&full_path_0).is_none());
938    }
939
940    #[reth_concurrency::test]
941    fn reveal_storage_v2_proof_nodes() {
942        let mut sparse = SparseStateTrie::<ArenaParallelSparseTrie>::default();
943
944        // Full 64-nibble path
945        let full_path_0 = leaf_key([0x0], 64);
946
947        let storage_value: Vec<u8> = alloy_rlp::encode_fixed_size(&U256::from(42)).to_vec();
948        let leaf_1_node = TrieNode::Leaf(LeafNode::new(leaf_key([], 63), storage_value.clone()));
949        let leaf_2_node = TrieNode::Leaf(LeafNode::new(leaf_key([], 63), storage_value.clone()));
950
951        let branch_node = TrieNode::Branch(BranchNode {
952            stack: vec![
953                RlpNode::from_rlp(&alloy_rlp::encode(&leaf_1_node)),
954                RlpNode::from_rlp(&alloy_rlp::encode(&leaf_2_node)),
955            ],
956            state_mask: TrieMask::new(0b11),
957        });
958
959        let v2_proof_nodes = vec![
960            ProofTrieNode { path: Nibbles::default(), node: branch_node, masks: None },
961            ProofTrieNode { path: Nibbles::from_nibbles([0x0]), node: leaf_1_node, masks: None },
962            ProofTrieNode { path: Nibbles::from_nibbles([0x1]), node: leaf_2_node, masks: None },
963        ];
964
965        // Reveal V2 storage proof nodes for account
966        sparse
967            .reveal_decoded_multiproof_v2(reth_trie_common::DecodedMultiProofV2 {
968                storage_proofs: B256Map::from_iter([(B256::ZERO, v2_proof_nodes)]),
969                ..Default::default()
970            })
971            .unwrap();
972
973        // Check that the storage trie contains the leaf node and value
974        assert!(matches!(
975            sparse.storage_trie_ref(&B256::ZERO).unwrap().find_leaf(&full_path_0, None),
976            Ok(LeafLookup::Exists)
977        ));
978        assert_eq!(
979            sparse.storage_trie_ref(&B256::ZERO).unwrap().get_leaf_value(&full_path_0),
980            Some(&storage_value)
981        );
982
983        // Remove the leaf node
984        let mut updates = B256Map::from_iter([(B256::ZERO, LeafUpdate::Changed(Vec::new()))]);
985        sparse
986            .storage_trie_mut(&B256::ZERO)
987            .unwrap()
988            .update_leaves(&mut updates, |_, _| {})
989            .unwrap();
990        assert!(updates.is_empty());
991        assert!(sparse
992            .storage_trie_ref(&B256::ZERO)
993            .unwrap()
994            .get_leaf_value(&full_path_0)
995            .is_none());
996    }
997
998    #[test]
999    fn root_on_blind_trie_returns_blind_error() {
1000        let mut sparse = SparseStateTrie::<ArenaParallelSparseTrie>::default();
1001
1002        let err = sparse.root(epoch(0)).unwrap_err();
1003
1004        assert!(matches!(err.kind(), SparseStateTrieErrorKind::Sparse(SparseTrieErrorKind::Blind)));
1005    }
1006
1007    #[test]
1008    #[allow(clippy::clone_on_copy)]
1009    fn take_trie_updates() {
1010        reth_tracing::init_test_tracing();
1011
1012        // let mut rng = generators::rng();
1013        let mut rng = StdRng::seed_from_u64(1);
1014
1015        let mut bytes = [0u8; 1024];
1016        rng.fill(bytes.as_mut_slice());
1017
1018        let slot_1 = b256!("0x1000000000000000000000000000000000000000000000000000000000000000");
1019        let slot_path_1 = Nibbles::unpack(slot_1);
1020        let value_1 = U256::from(rng.random::<u64>());
1021        let slot_2 = b256!("0x1100000000000000000000000000000000000000000000000000000000000000");
1022        let slot_path_2 = Nibbles::unpack(slot_2);
1023        let value_2 = U256::from(rng.random::<u64>());
1024        let slot_3 = b256!("0x2000000000000000000000000000000000000000000000000000000000000000");
1025        let value_3 = U256::from(rng.random::<u64>());
1026
1027        let account_1 = Account::arbitrary(&mut arbitrary::Unstructured::new(&bytes)).unwrap();
1028        let account_2 = Account::arbitrary(&mut arbitrary::Unstructured::new(&bytes)).unwrap();
1029
1030        Runtime::new().run(move || {
1031            let mut storage_hash_builder = HashBuilder::default()
1032                .with_proof_retainer(ProofRetainer::from_iter([slot_path_1, slot_path_2]));
1033            storage_hash_builder.add_leaf(slot_path_1, &alloy_rlp::encode_fixed_size(&value_1));
1034            storage_hash_builder.add_leaf(slot_path_2, &alloy_rlp::encode_fixed_size(&value_2));
1035
1036            let storage_root = storage_hash_builder.root();
1037            let storage_proof_nodes = storage_hash_builder.take_proof_nodes();
1038            let storage_branch_node_masks = BranchNodeMasksMap::from_iter([
1039                (
1040                    Nibbles::default(),
1041                    BranchNodeMasks {
1042                        hash_mask: TrieMask::new(0b010),
1043                        tree_mask: TrieMask::default(),
1044                    },
1045                ),
1046                (
1047                    Nibbles::from_nibbles([0x1]),
1048                    BranchNodeMasks {
1049                        hash_mask: TrieMask::new(0b11),
1050                        tree_mask: TrieMask::default(),
1051                    },
1052                ),
1053            ]);
1054
1055            let address_1 =
1056                b256!("0x1000000000000000000000000000000000000000000000000000000000000000");
1057            let address_path_1 = Nibbles::unpack(address_1);
1058            let mut trie_account_1 = account_1.clone().into_trie_account(storage_root);
1059            let address_2 =
1060                b256!("0x1100000000000000000000000000000000000000000000000000000000000000");
1061            let address_path_2 = Nibbles::unpack(address_2);
1062            let trie_account_2 = account_2.into_trie_account(EMPTY_ROOT_HASH);
1063
1064            let mut hash_builder = HashBuilder::default()
1065                .with_proof_retainer(ProofRetainer::from_iter([address_path_1, address_path_2]));
1066            hash_builder.add_leaf(address_path_1, &alloy_rlp::encode(trie_account_1.clone()));
1067            hash_builder.add_leaf(address_path_2, &alloy_rlp::encode(trie_account_2));
1068
1069            let root = hash_builder.root();
1070            let proof_nodes = hash_builder.take_proof_nodes();
1071            let mut sparse =
1072                SparseStateTrie::<ArenaParallelSparseTrie>::default().with_updates(true);
1073            sparse
1074                .reveal_decoded_multiproof(
1075                    MultiProof {
1076                        account_subtree: proof_nodes,
1077                        branch_node_masks: BranchNodeMasksMap::from_iter([(
1078                            Nibbles::from_nibbles([0x1]),
1079                            BranchNodeMasks {
1080                                hash_mask: TrieMask::new(0b00),
1081                                tree_mask: TrieMask::default(),
1082                            },
1083                        )]),
1084                        storages: HashMap::from_iter([
1085                            (
1086                                address_1,
1087                                StorageMultiProof {
1088                                    root,
1089                                    subtree: storage_proof_nodes.clone(),
1090                                    branch_node_masks: storage_branch_node_masks.clone(),
1091                                },
1092                            ),
1093                            (
1094                                address_2,
1095                                StorageMultiProof {
1096                                    root,
1097                                    subtree: storage_proof_nodes,
1098                                    branch_node_masks: storage_branch_node_masks,
1099                                },
1100                            ),
1101                        ]),
1102                    }
1103                    .try_into()
1104                    .unwrap(),
1105                )
1106                .unwrap();
1107
1108            assert_eq!(sparse.root(epoch(0)).unwrap(), root);
1109
1110            let address_3 =
1111                b256!("0x2000000000000000000000000000000000000000000000000000000000000000");
1112            let account_3 = Account { nonce: account_1.nonce + 1, ..account_1 };
1113            let trie_account_3 = account_3.into_trie_account(EMPTY_ROOT_HASH);
1114
1115            apply_account_update(
1116                &mut sparse,
1117                address_3,
1118                LeafUpdate::Changed(alloy_rlp::encode(trie_account_3)),
1119            );
1120
1121            let mut updates =
1122                B256Map::from_iter([(slot_3, LeafUpdate::Changed(alloy_rlp::encode(value_3)))]);
1123            sparse
1124                .storage_trie_mut(&address_1)
1125                .unwrap()
1126                .update_leaves(&mut updates, |_, _| {})
1127                .unwrap();
1128            assert!(updates.is_empty());
1129            trie_account_1.storage_root = sparse.storage_root(&address_1, epoch(0)).unwrap();
1130            apply_account_update(
1131                &mut sparse,
1132                address_1,
1133                LeafUpdate::Changed(alloy_rlp::encode(trie_account_1)),
1134            );
1135
1136            sparse.root(epoch(0)).unwrap();
1137
1138            let sparse_updates = sparse.take_trie_updates().unwrap();
1139            // TODO(alexey): assert against real state root calculation updates
1140            pretty_assertions::assert_eq!(
1141                sparse_updates,
1142                TrieUpdates {
1143                    account_nodes: HashMap::default(),
1144                    storage_tries: HashMap::from_iter([(
1145                        b256!("0x1000000000000000000000000000000000000000000000000000000000000000"),
1146                        StorageTrieUpdates {
1147                            storage_nodes: HashMap::default(),
1148                            removed_nodes: HashSet::from_iter([Nibbles::from_nibbles([0x1])])
1149                        }
1150                    )]),
1151                    removed_nodes: HashSet::default()
1152                }
1153            );
1154        });
1155    }
1156}