reth_trie_sparse/trie.rs
1use crate::{
2 ArenaParallelSparseTrie, LeafUpdate, SparseTrie as SparseTrieTrait, SparseTrieUpdates,
3 TrieNodeEpoch,
4};
5use alloc::boxed::Box;
6use alloy_primitives::{map::B256Map, B256};
7use reth_execution_errors::{SparseTrieErrorKind, SparseTrieResult};
8use reth_trie_common::{ProofTrieNode, ProofV2TargetParent};
9
10/// A sparse trie that is either in a "blind" state (no nodes are revealed, root node hash is
11/// unknown) or in a "revealed" state (root node has been revealed and the trie can be updated).
12///
13/// In blind mode the trie does not contain any decoded node data, which saves memory but
14/// prevents direct access to node contents. The revealed mode stores decoded nodes along
15/// with additional information such as values, allowing direct manipulation.
16///
17/// The sparse trie design is optimised for:
18/// 1. Memory efficiency - only revealed nodes are loaded into memory
19/// 2. Update tracking - changes to the trie structure can be tracked and selectively persisted
20/// 3. Incremental operations - nodes can be revealed as needed without loading the entire trie.
21/// This is what gives rise to the notion of a "sparse" trie.
22#[derive(PartialEq, Eq, Debug, Clone)]
23pub enum RevealableSparseTrie<T = ArenaParallelSparseTrie> {
24 /// The trie is blind -- no nodes have been revealed
25 ///
26 /// This is the default state. In this state, the trie cannot be directly queried or modified
27 /// until nodes are revealed.
28 ///
29 /// In this state the `RevealableSparseTrie` can optionally carry with it a cleared
30 /// sparse trie. This allows for reusing the trie's allocations between payload executions.
31 Blind(Option<Box<T>>),
32 /// Some nodes in the Trie have been revealed.
33 ///
34 /// In this state, the trie can be queried and modified for the parts
35 /// that have been revealed. Other parts remain blind and require revealing
36 /// before they can be accessed.
37 Revealed(Box<T>),
38}
39
40impl<T: Default> Default for RevealableSparseTrie<T> {
41 fn default() -> Self {
42 Self::Blind(None)
43 }
44}
45
46impl<T: SparseTrieTrait + Default> RevealableSparseTrie<T> {
47 /// Creates a new revealed but empty sparse trie.
48 pub fn revealed_empty() -> Self {
49 Self::Revealed(Box::default())
50 }
51
52 /// Reveals the root from a V2 calculator batch, converting a blind trie into a revealed one.
53 ///
54 /// `nodes` must contain the root. An extension's branch child may be revealed later.
55 /// The root and its branch may be consumed; other proof nodes are left for revelation.
56 /// The retention flag controls whether trie updates should be tracked.
57 ///
58 /// # Returns
59 ///
60 /// A mutable reference to the underlying [`RevealableSparseTrie`](SparseTrieTrait).
61 pub fn reveal_root(
62 &mut self,
63 nodes: &mut [ProofTrieNode],
64 retain_updates: bool,
65 ) -> SparseTrieResult<&mut T> {
66 // If `Blind`, initialize the revealed trie from the root batch, using a
67 // pre-allocated trie if available.
68 if self.is_blind() {
69 let mut revealed_trie = if let Self::Blind(Some(cleared_trie)) = core::mem::take(self) {
70 cleared_trie
71 } else {
72 Box::default()
73 };
74
75 revealed_trie.set_root(nodes, retain_updates)?;
76 *self = Self::Revealed(revealed_trie);
77 }
78
79 Ok(self.as_revealed_mut().unwrap())
80 }
81
82 /// Reveals a batch of V2 proof nodes into this trie.
83 ///
84 /// If `nodes` contains a node at the empty path it is used to reveal the root (transitioning
85 /// the trie from blind to revealed). Otherwise the trie must already be revealed.
86 pub fn reveal_v2_proof_nodes(
87 &mut self,
88 nodes: &mut [ProofTrieNode],
89 retain_updates: bool,
90 ) -> SparseTrieResult<()> {
91 let trie = if self.is_blind() && nodes.iter().any(|node| node.path.is_empty()) {
92 self.reveal_root(nodes, retain_updates)?
93 } else {
94 self.as_revealed_mut().ok_or(SparseTrieErrorKind::Blind)?
95 };
96 trie.reveal_nodes(nodes)?;
97
98 Ok(())
99 }
100}
101
102impl<T: SparseTrieTrait> RevealableSparseTrie<T> {
103 /// Creates a new blind sparse trie.
104 ///
105 /// # Examples
106 ///
107 /// ```
108 /// use reth_trie_sparse::RevealableSparseTrie;
109 ///
110 /// let trie = <RevealableSparseTrie>::blind();
111 /// assert!(trie.is_blind());
112 /// let trie = <RevealableSparseTrie>::default();
113 /// assert!(trie.is_blind());
114 /// ```
115 pub const fn blind() -> Self {
116 Self::Blind(None)
117 }
118
119 /// Creates a new blind sparse trie, clearing and later reusing the given
120 /// [`RevealableSparseTrie`](SparseTrieTrait).
121 pub fn blind_from(mut trie: T) -> Self {
122 trie.clear();
123 Self::Blind(Some(Box::new(trie)))
124 }
125
126 /// Returns `true` if the sparse trie has no revealed nodes.
127 pub const fn is_blind(&self) -> bool {
128 matches!(self, Self::Blind(_))
129 }
130
131 /// Returns `true` if the sparse trie is revealed.
132 pub const fn is_revealed(&self) -> bool {
133 matches!(self, Self::Revealed(_))
134 }
135
136 /// Returns an immutable reference to the underlying revealed sparse trie.
137 ///
138 /// Returns `None` if the trie is blinded.
139 pub const fn as_revealed_ref(&self) -> Option<&T> {
140 if let Self::Revealed(revealed) = self {
141 Some(revealed)
142 } else {
143 None
144 }
145 }
146
147 /// Returns a mutable reference to the underlying revealed sparse trie.
148 ///
149 /// Returns `None` if the trie is blinded.
150 pub fn as_revealed_mut(&mut self) -> Option<&mut T> {
151 if let Self::Revealed(revealed) = self {
152 Some(revealed)
153 } else {
154 None
155 }
156 }
157
158 /// Calculates the root hash of the trie.
159 ///
160 /// This will update any remaining dirty nodes before computing the root hash.
161 /// "dirty" nodes are nodes that need their hashes to be recomputed because one or more of their
162 /// children's hashes have changed.
163 ///
164 /// # Returns
165 ///
166 /// - `Some(B256)` with the calculated root hash if the trie is revealed.
167 /// - `None` if the trie is still blind.
168 pub fn root(&mut self, new_epoch: TrieNodeEpoch) -> Option<B256> {
169 Some(self.as_revealed_mut()?.root(new_epoch))
170 }
171
172 /// Returns true if the root node is cached and does not need any recomputation.
173 pub fn is_root_cached(&self) -> bool {
174 self.as_revealed_ref().is_some_and(|trie| trie.is_root_cached())
175 }
176
177 /// Returns the root hash along with any accumulated update information.
178 ///
179 /// This is useful for when you need both the root hash and information about
180 /// what nodes were modified, which can be used to efficiently update
181 /// an external database.
182 ///
183 /// # Returns
184 ///
185 /// An `Option` tuple consisting of:
186 /// - The trie root hash (`B256`).
187 /// - A [`SparseTrieUpdates`] structure containing information about updated nodes.
188 /// - `None` if the trie is still blind.
189 pub fn root_with_updates(
190 &mut self,
191 new_epoch: TrieNodeEpoch,
192 ) -> Option<(B256, SparseTrieUpdates)> {
193 let revealed = self.as_revealed_mut()?;
194 Some((revealed.root(new_epoch), revealed.take_updates()))
195 }
196
197 /// Clears this trie, setting it to a blind state.
198 ///
199 /// If this instance was revealed, or was itself a `Blind` with a pre-allocated
200 /// [`RevealableSparseTrie`](SparseTrieTrait), this will set to `Blind` carrying a cleared
201 /// pre-allocated [`RevealableSparseTrie`](SparseTrieTrait).
202 #[inline]
203 pub fn clear(&mut self) {
204 *self = match core::mem::replace(self, Self::blind()) {
205 s @ Self::Blind(_) => s,
206 Self::Revealed(mut trie) => {
207 trie.clear();
208 Self::Blind(Some(trie))
209 }
210 };
211 }
212}
213
214impl<T: SparseTrieTrait + Default> RevealableSparseTrie<T> {
215 /// Applies batch leaf updates to the sparse trie.
216 ///
217 /// For blind tries, all updates are kept in the map and proof targets are emitted
218 /// for every key (with no known parent since nothing is revealed).
219 ///
220 /// For revealed tries, delegates to the inner implementation which will:
221 /// - Apply updates where possible
222 /// - Keep blocked updates in the map
223 /// - Emit proof targets for blinded paths
224 pub fn update_leaves(
225 &mut self,
226 updates: &mut B256Map<LeafUpdate>,
227 mut proof_required_fn: impl FnMut(B256, ProofV2TargetParent),
228 ) -> SparseTrieResult<()> {
229 match self {
230 Self::Blind(_) => {
231 // Nothing is revealed - emit proof targets for all keys without a known parent.
232 for key in updates.keys() {
233 #[cfg(all(feature = "fuzz", reth_sparse_trie_coverage))]
234 crate::arena::observe_blind_root_proof_target();
235 proof_required_fn(*key, ProofV2TargetParent::NONE);
236 }
237 // All updates remain in the map for retry after proofs are fetched
238 Ok(())
239 }
240 Self::Revealed(trie) => trie.update_leaves(updates, proof_required_fn),
241 }
242 }
243}
244
245impl SparseTrieUpdates {
246 /// Clears the updates, but keeps the backing data structures allocated.
247 pub fn clear(&mut self) {
248 self.updated_nodes.clear();
249 self.removed_nodes.clear();
250 }
251
252 /// Extends the updates with another set of updates.
253 pub fn extend(&mut self, other: Self) {
254 self.updated_nodes.extend(other.updated_nodes);
255 self.removed_nodes.extend(other.removed_nodes);
256 }
257}