Skip to main content

reth_chain_state/
preserved_sparse_trie.rs

1//! Preserved sparse trie for reuse across payload validations.
2
3use alloy_primitives::{map::B256Map, B256};
4use reth_concurrency::sync::channel::mpsc::Receiver;
5use reth_trie_sparse::SparseStateTrie;
6use std::fmt;
7use tracing::debug;
8
9/// A preserved sparse trie that can be reused across payload validations.
10pub struct PreservedSparseTrie {
11    /// The finalized sparse trie and its revealed storage roots, which may still be pending.
12    trie: Receiver<SparseTrieWithStorageRoots>,
13    /// Hash of the block whose post-state this trie represents.
14    ///
15    /// Used to verify continuity: a new payload's parent hash must match this before the existing
16    /// sparse trie nodes can be reused.
17    block_hash: B256,
18    /// Parent block hash of the earliest overlay state covered by this trie.
19    anchor_hash: B256,
20}
21
22impl fmt::Debug for PreservedSparseTrie {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        f.debug_struct("PreservedSparseTrie")
25            .field("block_hash", &self.block_hash)
26            .field("anchor_hash", &self.anchor_hash)
27            .finish_non_exhaustive()
28    }
29}
30
31impl PreservedSparseTrie {
32    /// Associates a trie still being finalized with its completed block and pruning anchor.
33    pub const fn pending(
34        trie: Receiver<SparseTrieWithStorageRoots>,
35        block_hash: B256,
36        anchor_hash: B256,
37    ) -> Self {
38        Self { trie, block_hash, anchor_hash }
39    }
40
41    /// Returns the hash of the block whose post-state this trie represents.
42    pub const fn block_hash(&self) -> B256 {
43        self.block_hash
44    }
45
46    /// Returns the parent block hash of the earliest overlay state covered by this trie.
47    pub const fn anchor_hash(&self) -> B256 {
48        self.anchor_hash
49    }
50
51    /// Consumes self and returns the sparse trie and its revealed storage roots if reusable for
52    /// the parent block.
53    ///
54    /// If the parent block hash does not match the preserved trie's block hash, this drops the
55    /// trie and returns `None` so the caller can create a fresh sparse trie.
56    pub fn into_trie_for(
57        self,
58        parent_hash: B256,
59    ) -> Result<Option<SparseTrieWithStorageRoots>, PreservedSparseTrieError> {
60        if self.block_hash == parent_hash {
61            let trie = self.trie.recv().map_err(|_| PreservedSparseTrieError::ProducerDropped {
62                block_hash: self.block_hash,
63            })?;
64            debug!(
65                target: "engine::tree::payload_processor",
66                block_hash = %self.block_hash,
67                anchor_hash = %self.anchor_hash,
68                "Reusing anchored sparse trie for continuation payload"
69            );
70            Ok(Some(trie))
71        } else {
72            debug!(
73                target: "engine::tree::payload_processor",
74                block_hash = %self.block_hash,
75                anchor_hash = %self.anchor_hash,
76                %parent_hash,
77                "Dropping anchored sparse trie - parent hash mismatch"
78            );
79            Ok(None)
80        }
81    }
82}
83
84/// Error returned when consuming a preserved sparse trie.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub enum PreservedSparseTrieError {
87    /// The producer of a pending preserved sparse trie dropped before publishing it.
88    ProducerDropped {
89        /// The block hash the pending trie was expected to represent.
90        block_hash: B256,
91    },
92}
93
94impl fmt::Display for PreservedSparseTrieError {
95    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96        match self {
97            Self::ProducerDropped { block_hash } => {
98                write!(f, "pending preserved sparse trie producer dropped for {block_hash}")
99            }
100        }
101    }
102}
103
104impl std::error::Error for PreservedSparseTrieError {}
105
106/// A finalized sparse trie and its revealed storage roots for the next block's proof workers.
107#[derive(Debug, Default)]
108pub struct SparseTrieWithStorageRoots {
109    /// The sparse trie after finalization and pruning.
110    pub trie: SparseStateTrie,
111    /// Roots of all revealed storage tries before pruning, keyed by hashed account address.
112    pub storage_roots: B256Map<B256>,
113}
114
115#[cfg(test)]
116mod tests {
117    use super::*;
118    use reth_concurrency::sync::channel::mpsc;
119
120    #[reth_concurrency::test]
121    fn pending_trie_exposes_block_hash_before_completion() {
122        let block_hash = B256::with_last_byte(1);
123        let anchor_hash = B256::with_last_byte(2);
124        let (tx, rx) = mpsc::channel();
125        let preserved = PreservedSparseTrie::pending(rx, block_hash, anchor_hash);
126
127        assert_eq!(preserved.block_hash(), block_hash);
128        assert_eq!(preserved.anchor_hash(), anchor_hash);
129        tx.send(SparseTrieWithStorageRoots::default()).unwrap();
130        assert!(preserved.into_trie_for(block_hash).unwrap().is_some());
131    }
132
133    #[reth_concurrency::test]
134    fn pending_trie_with_mismatched_parent_does_not_wait() {
135        let block_hash = B256::with_last_byte(1);
136        let other_block_hash = B256::with_last_byte(2);
137        let anchor_hash = B256::with_last_byte(3);
138        let (tx, rx) = mpsc::channel();
139        let preserved = PreservedSparseTrie::pending(rx, block_hash, anchor_hash);
140
141        assert!(preserved.into_trie_for(other_block_hash).unwrap().is_none());
142        assert!(tx.send(SparseTrieWithStorageRoots::default()).is_err());
143    }
144}