Skip to main content

reth_trie_common/
trie_data.rs

1//! Lazy initialization wrapper for trie data.
2//!
3//! Provides a no-std compatible [`LazyTrieData`] type for lazily initialized
4//! trie-related data containing sorted hashed state and trie updates.
5
6use crate::{
7    updates::{TrieUpdates, TrieUpdatesSorted},
8    HashedPostState, HashedPostStateSorted,
9};
10use alloc::sync::Arc;
11use core::fmt;
12use reth_concurrency::sync::OnceLock;
13
14#[cfg(feature = "rayon")]
15use reth_concurrency::sync::rayon;
16
17/// Container for sorted trie data: hashed state and trie updates.
18///
19/// This bundles both [`HashedPostStateSorted`] and [`TrieUpdatesSorted`] together
20/// for convenient passing and storage.
21#[derive(Clone, Debug, Default, PartialEq, Eq)]
22#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
23pub struct SortedTrieData {
24    /// Sorted hashed post-state produced by execution.
25    pub hashed_state: Arc<HashedPostStateSorted>,
26    /// Sorted trie updates produced by state root computation.
27    pub trie_updates: Arc<TrieUpdatesSorted>,
28}
29
30impl SortedTrieData {
31    /// Creates a new [`SortedTrieData`] with the given values.
32    pub const fn new(
33        hashed_state: Arc<HashedPostStateSorted>,
34        trie_updates: Arc<TrieUpdatesSorted>,
35    ) -> Self {
36        Self { hashed_state, trie_updates }
37    }
38}
39
40/// Lazily initialized trie data containing sorted hashed state and trie updates.
41///
42/// This is a no-std compatible wrapper that supports three modes:
43/// 1. **Ready mode**: Data is available immediately (created via `ready()`)
44/// 2. **Deferred mode**: Data is computed on first access (created via `deferred()`)
45/// 3. **Pending mode**: Access blocks until the caller-owned producer publishes the data (created
46///    via `pending()`). No task is spawned automatically.
47///
48/// In deferred mode, the computation runs on the first call to `get()`, `hashed_state()`,
49/// or `trie_updates()`, and results are cached for subsequent calls.
50///
51/// Cloning is cheap (Arc clone) and clones share the cached state.
52pub struct LazyTrieData {
53    /// Cached sorted trie data, computed on first access.
54    data: Arc<OnceLock<SortedTrieData>>,
55    // /// Optional deferred computation function.
56    // compute: Option<Arc<dyn Fn() -> SortedTrieData + Send + Sync>>,
57    /// Lazy mode.
58    mode: LazyTrieDataMode,
59}
60
61impl Clone for LazyTrieData {
62    fn clone(&self) -> Self {
63        Self { data: Arc::clone(&self.data), mode: self.mode.clone() }
64    }
65}
66
67impl fmt::Debug for LazyTrieData {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.debug_struct("LazyTrieData")
70            .field("data", &if self.data.get().is_some() { "initialized" } else { "pending" })
71            .finish()
72    }
73}
74
75impl PartialEq for LazyTrieData {
76    fn eq(&self, other: &Self) -> bool {
77        self.get() == other.get()
78    }
79}
80
81impl Eq for LazyTrieData {}
82
83impl LazyTrieData {
84    /// Creates a new [`LazyTrieData`] that is already initialized with the given values.
85    pub fn ready(sorted: SortedTrieData) -> Self {
86        Self { data: Arc::new(OnceLock::from(sorted)), mode: LazyTrieDataMode::Ready }
87    }
88
89    /// Creates a new [`LazyTrieData`] with a deferred computation function.
90    ///
91    /// The computation will run on the first call to `get()`, `hashed_state()`,
92    /// or `trie_updates()`. Results are cached for subsequent calls.
93    pub fn deferred(compute: impl Fn() -> SortedTrieData + Send + Sync + 'static) -> Self {
94        Self {
95            data: Arc::new(OnceLock::new()),
96            mode: LazyTrieDataMode::Deferred(Arc::new(compute)),
97        }
98    }
99
100    /// Creates a pending [`LazyTrieData`] and its producer without spawning a task.
101    ///
102    /// The caller must arrange for `LazyTrieDataProducer::compute_and_publish` to run before or
103    /// concurrently with access to the handle. Access blocks until publication; dropping the
104    /// producer without publishing leaves access blocked indefinitely.
105    #[cfg(feature = "std")]
106    pub fn pending(
107        hashed_state: Arc<HashedPostState>,
108        trie_updates: Arc<TrieUpdates>,
109    ) -> (Self, LazyTrieDataProducer) {
110        let value = Arc::new(OnceLock::new());
111        (
112            Self { data: Arc::clone(&value), mode: LazyTrieDataMode::Pending },
113            LazyTrieDataProducer { value, inputs: PendingInputs { hashed_state, trie_updates } },
114        )
115    }
116
117    /// Returns a reference to the sorted trie data.
118    ///
119    /// Deferred mode computes on first access. Pending mode blocks until the producer publishes
120    /// the result and can block indefinitely if publication never occurs.
121    ///
122    /// # Panics
123    ///
124    /// Panics if in ready state, but value has not been initialized.
125    pub fn get(&self) -> &SortedTrieData {
126        match &self.mode {
127            LazyTrieDataMode::Ready => self.data.get().expect("LazyTrieData must be initialized"),
128            LazyTrieDataMode::Deferred(compute) => self.data.get_or_init(|| compute.as_ref()()),
129            #[cfg(feature = "std")]
130            LazyTrieDataMode::Pending => self.data.wait(),
131        }
132    }
133
134    /// Returns a clone of the hashed state Arc.
135    ///
136    /// Calls [`Self::get`], computing deferred data or blocking until pending data is published.
137    pub fn hashed_state(&self) -> Arc<HashedPostStateSorted> {
138        Arc::clone(&self.get().hashed_state)
139    }
140
141    /// Returns a clone of the trie updates Arc.
142    ///
143    /// Calls [`Self::get`], computing deferred data or blocking until pending data is published.
144    pub fn trie_updates(&self) -> Arc<TrieUpdatesSorted> {
145        Arc::clone(&self.get().trie_updates)
146    }
147
148    /// Returns a clone of the [`SortedTrieData`].
149    ///
150    /// Calls [`Self::get`], computing deferred data or blocking until pending data is published.
151    pub fn sorted_trie_data(&self) -> SortedTrieData {
152        self.get().clone()
153    }
154}
155
156#[cfg(feature = "serde")]
157impl serde::Serialize for LazyTrieData {
158    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
159    where
160        S: serde::Serializer,
161    {
162        self.get().serialize(serializer)
163    }
164}
165
166#[cfg(feature = "serde")]
167impl<'de> serde::Deserialize<'de> for LazyTrieData {
168    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
169    where
170        D: serde::Deserializer<'de>,
171    {
172        let data = SortedTrieData::deserialize(deserializer)?;
173        Ok(Self::ready(data))
174    }
175}
176
177#[derive(Clone)]
178enum LazyTrieDataMode {
179    Ready,
180    Deferred(Arc<dyn Fn() -> SortedTrieData + Send + Sync>),
181    #[cfg(feature = "std")]
182    Pending,
183}
184
185impl fmt::Debug for LazyTrieDataMode {
186    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
187        match self {
188            Self::Ready => write!(f, "Ready"),
189            Self::Deferred(_) => write!(f, "Deferred(..)"),
190            #[cfg(feature = "std")]
191            Self::Pending => write!(f, "Pending"),
192        }
193    }
194}
195
196/// Producer that computes and publishes sorted trie data for a [`LazyTrieData`] handle.
197///
198/// The caller is responsible for running [`Self::compute_and_publish`]. Dropping the producer
199/// without publishing leaves pending accessors blocked indefinitely.
200#[must_use = "LazyTrieDataProducer must be consumed with compute_and_publish to wake trie data waiters"]
201pub struct LazyTrieDataProducer {
202    /// Shared result initialized exactly once by this producer.
203    value: Arc<OnceLock<SortedTrieData>>,
204    /// Unsorted inputs consumed when the producer computes trie data.
205    inputs: PendingInputs,
206}
207
208impl fmt::Debug for LazyTrieDataProducer {
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        f.debug_struct("LazyTrieDataProducer").field("inputs", &self.inputs).finish_non_exhaustive()
211    }
212}
213
214impl LazyTrieDataProducer {
215    /// Computes sorted trie data, publishes it to waiters, and returns it to the task owner.
216    pub fn compute_and_publish(self) -> SortedTrieData {
217        let Self { value, inputs } = self;
218        let computed = Self::sort(inputs.hashed_state, inputs.trie_updates);
219        let _ = value.set(computed.clone());
220        computed
221    }
222
223    /// Sorts block execution outputs.
224    pub fn sort(
225        hashed_state: Arc<HashedPostState>,
226        trie_updates: Arc<TrieUpdates>,
227    ) -> SortedTrieData {
228        #[cfg(feature = "rayon")]
229        let (sorted_hashed_state, sorted_trie_updates) = rayon::join(
230            || match Arc::try_unwrap(hashed_state) {
231                Ok(state) => state.into_sorted(),
232                Err(arc) => arc.clone_into_sorted(),
233            },
234            || match Arc::try_unwrap(trie_updates) {
235                Ok(updates) => updates.into_sorted(),
236                Err(arc) => arc.clone_into_sorted(),
237            },
238        );
239
240        #[cfg(not(feature = "rayon"))]
241        let (sorted_hashed_state, sorted_trie_updates) = (
242            match Arc::try_unwrap(hashed_state) {
243                Ok(state) => state.into_sorted(),
244                Err(arc) => arc.clone_into_sorted(),
245            },
246            match Arc::try_unwrap(trie_updates) {
247                Ok(updates) => updates.into_sorted(),
248                Err(arc) => arc.clone_into_sorted(),
249            },
250        );
251
252        SortedTrieData::new(Arc::new(sorted_hashed_state), Arc::new(sorted_trie_updates))
253    }
254}
255
256/// Inputs kept while a deferred trie computation is pending.
257#[derive(Clone, Debug)]
258struct PendingInputs {
259    /// Unsorted hashed post-state from execution.
260    hashed_state: Arc<HashedPostState>,
261    /// Unsorted trie updates from state root computation.
262    trie_updates: Arc<TrieUpdates>,
263}
264
265#[cfg(test)]
266mod tests {
267    use crate::HashedStorage;
268
269    use super::*;
270    use alloy_primitives::{B256, U256};
271    use reth_concurrency::sync::thread;
272    use reth_primitives_traits::Account;
273    use std::time::Duration;
274
275    fn empty_pending() -> (LazyTrieData, LazyTrieDataProducer) {
276        LazyTrieData::pending(
277            Arc::new(HashedPostState::default()),
278            Arc::new(TrieUpdates::default()),
279        )
280    }
281
282    #[test]
283    fn test_lazy_clone_shares_state() {
284        let lazy1 = LazyTrieData::ready(SortedTrieData::default());
285        let lazy2 = lazy1.clone();
286
287        // Both point to the same data
288        assert!(Arc::ptr_eq(&lazy1.hashed_state(), &lazy2.hashed_state()));
289        assert!(Arc::ptr_eq(&lazy1.trie_updates(), &lazy2.trie_updates()));
290    }
291
292    #[reth_concurrency::test]
293    fn test_lazy_deferred() {
294        let lazy = LazyTrieData::deferred(SortedTrieData::default);
295        assert!(lazy.hashed_state().is_empty());
296        assert!(lazy.trie_updates().is_empty());
297    }
298
299    #[reth_concurrency::test]
300    fn pending_wait_blocks_until_task_publishes() {
301        let (deferred, task) = empty_pending();
302
303        let handle = thread::spawn(move || deferred.get().clone());
304        thread::sleep(Duration::from_millis(20));
305        assert!(!handle.is_finished());
306
307        let published = task.compute_and_publish();
308        let result = handle.join().unwrap();
309
310        assert!(Arc::ptr_eq(&published.hashed_state, &result.hashed_state));
311        assert!(Arc::ptr_eq(&published.trie_updates, &result.trie_updates));
312    }
313
314    #[reth_concurrency::test]
315    fn concurrent_waits_share_published_result() {
316        let (deferred, task) = empty_pending();
317        let deferred2 = deferred.clone();
318
319        let handle = thread::spawn(move || deferred2.get().clone());
320        let published = task.compute_and_publish();
321        let result1 = deferred.get().clone();
322        let result2 = handle.join().unwrap();
323
324        assert!(Arc::ptr_eq(&published.hashed_state, &result1.hashed_state));
325        assert!(Arc::ptr_eq(&published.trie_updates, &result1.trie_updates));
326        assert!(Arc::ptr_eq(&result1.hashed_state, &result2.hashed_state));
327        assert!(Arc::ptr_eq(&result1.trie_updates, &result2.trie_updates));
328    }
329
330    #[reth_concurrency::test]
331    fn sorts_non_empty_inputs() {
332        let hashed_address = B256::with_last_byte(1);
333        let hashed_slot = B256::with_last_byte(2);
334        let hashed_state = HashedPostState::default()
335            .with_accounts([(hashed_address, Some(Account::default()))])
336            .with_storages([(
337                hashed_address,
338                HashedStorage::from_iter([(hashed_slot, U256::ONE)]),
339            )]);
340
341        let (deferred, task) =
342            LazyTrieData::pending(Arc::new(hashed_state), Arc::new(TrieUpdates::default()));
343        let _ = task.compute_and_publish();
344        let result = deferred.get().clone();
345
346        assert_eq!(result.hashed_state.total_len(), 2);
347        assert_eq!(result.trie_updates.total_len(), 0);
348    }
349}