Skip to main content

reth_engine_tree/tree/state_root_strategy/
mod.rs

1//! State-root strategies for engine-tree block validation.
2//!
3//! A [`StateRootStrategy`] is installed once per node, via
4//! `BasicEngineValidator::with_state_root_strategy`, and consulted for every block that engine
5//! validation executes. For each block the strategy prepares a [`StateRootJob`] before execution
6//! starts, and validation finishes the job after execution to obtain the state root that is
7//! checked against the block header. On every FCU that carries payload attributes, the strategy
8//! is also asked through [`StateRootStrategy::prepare_payload_builder`] for an optional
9//! [`PayloadStateRootHandle`] that the payload builder uses while building a block.
10//!
11//! # Job lifecycle
12//!
13//! 1. [`StateRootStrategy::prepare`] runs before block execution. The job can spawn background work
14//!    here and can expose hooks that observe execution.
15//! 2. Execution runs. Jobs that observe execution receive updates through their hooks.
16//! 3. [`StateRootJob::finish`] runs after execution and returns the [`StateRootJobOutcome`]. It
17//!    must produce a result even if no execution updates were observed, since the full
18//!    [`BlockExecutionOutput`] is passed to it.
19//!
20//! Dropping a prepared job without calling `finish` aborts it. Implementations must treat
21//! channel disconnects from dropped hooks as cancellation and must not leak background work.
22//!
23//! # Stream delivery contract
24//!
25//! A prepared job exposes update-stream capabilities over its sink. `prepare` installs exactly
26//! one authoritative capability per block, matching the execution mode:
27//!
28//! - On the parallel BAL execution path, prewarm converts the block access list and delivers
29//!   pre-hashed updates through the hashed update stream, terminated by
30//!   [`StateRootUpdateStream::finish`].
31//! - On the serial execution path, per-transaction `StateUpdate`s arrive through the execution
32//!   hook, terminated when the hook is dropped after execution.
33//!
34//! Which path runs depends on runtime conditions (BAL present, caching and prewarming enabled),
35//! so a sink must handle both. Access hints from prewarming are best-effort: they may be
36//! missing, duplicated, or stale, and must not be treated as state updates.
37//!
38//! # Custom strategies
39//!
40//! Custom implementations can hold a [`DefaultStateRootStrategy`] and forward calls to it for
41//! blocks where the default behavior is wanted, for example before a fork activates. See
42//! `examples/custom-state-root` for the wiring.
43//!
44//! # Empty accounts
45//!
46//! The sparse-trie path treats an account with zero nonce, zero balance, empty bytecode, and an
47//! empty storage root as absent from the account trie. This relies on the post-Merge invariant
48//! established by EIP-7523 (<https://eips.ethereum.org/EIPS/eip-7523>): post-Merge state cannot
49//! contain empty accounts. A custom strategy that replays pre-Merge blocks through the Engine API
50//! must route those blocks to a state-root implementation that supports historical empty accounts.
51//!
52//! Returning empty trie updates in the outcome means the trie tables are no longer maintained:
53//! `eth_getProof` and anything else that reads the stored trie will not work for new blocks.
54//! Sparse-trie cache pruning uses node epochs to retain the in-memory block range.
55
56mod sparse_trie;
57
58use self::sparse_trie::{SparseTrieCacheTask, SparseTrieTaskMetrics};
59use crate::tree::{metrics::BlockValidationMetrics, EngineApiTreeState, ExecutionEnv, TreeConfig};
60use alloy_primitives::B256;
61use reth_chain_state::{ExecutedBlock, PreservedSparseTrie, SparseTrieWithStorageRoots};
62use reth_concurrency::sync::{
63    channel::{
64        self,
65        mpsc::{self, RecvTimeoutError},
66        Receiver,
67    },
68    thread,
69    time::FastInstant as Instant,
70};
71use reth_errors::ProviderResult;
72use reth_evm::ConfigureEvm;
73use reth_primitives_traits::{AlloyBlockHeader, NodePrimitives, RecoveredBlock, SealedHeader};
74use reth_provider::{
75    BlockExecutionOutput, BlockNumReader, ChangeSetReader, DatabaseProviderFactory,
76    DatabaseProviderROFactory, HashedPostStateProvider, ProviderError, PruneCheckpointReader,
77    StageCheckpointReader, StateRootProvider, StorageChangeSetReader, StorageSettingsCache,
78};
79use reth_storage_overlay::{OverlayManager, OverlayStateProviderFactory};
80use reth_tasks::utils::increase_thread_priority;
81use reth_trie::{updates::TrieUpdates, HashedPostState};
82use reth_trie_parallel::proof_task::{
83    metrics::ProofWorkerIdleMetrics, ProofTaskCtx, ProofWorkerCounts, ProofWorkerHandle,
84};
85pub use reth_trie_parallel::{
86    error::StateRootTaskError,
87    state_root_task::{
88        PayloadStateRootHandle, StateAccessHint, StateRootComputeOutcome, StateRootHandle,
89        StateRootHintStream, StateRootMessage, StateRootTaskCancelGuard, StateRootUpdateHook,
90        StateRootUpdateStream,
91    },
92};
93use reth_trie_sparse::{
94    ArenaParallelSparseTrie, RevealableSparseTrie, SparseStateTrie, TrieNodeEpoch,
95};
96use std::{fmt, sync::Arc, time::Duration};
97use tracing::{debug, debug_span, instrument, warn, Span};
98
99/// Handle to a [`HashedPostState`] computed on a background thread.
100pub type LazyHashedPostState = reth_tasks::LazyHandle<Arc<HashedPostState>>;
101
102/// Strategy used by engine-tree validation to prepare per-block state-root work.
103pub trait StateRootStrategy<N, P, Evm>: Send + Sync
104where
105    N: NodePrimitives,
106    Evm: ConfigureEvm<Primitives = N>,
107{
108    /// Prepares a per-block state-root job before execution starts.
109    ///
110    /// A custom strategy that maintains a reusable sparse trie is responsible for consuming the
111    /// pending prune request from the context when it starts the corresponding job.
112    fn prepare(
113        &self,
114        ctx: StateRootJobContext<'_, N, P, Evm>,
115    ) -> ProviderResult<PreparedStateRootJob<N>>;
116
117    /// Prepares the optional payload-builder state-root handle used for FCU-triggered block
118    /// building.
119    ///
120    /// This is consulted on every FCU that carries payload attributes. Returning `None` means the
121    /// payload builder computes the state root itself; the stock builders fall back to a
122    /// synchronous MPT state root. The default implementation returns `None`.
123    fn prepare_payload_builder(
124        &self,
125        _ctx: PayloadStateRootJobContext<'_, N, P>,
126    ) -> ProviderResult<Option<PayloadStateRootHandle>> {
127        Ok(None)
128    }
129}
130
131/// Data available while preparing one payload-builder state-root handle.
132pub struct PayloadStateRootJobContext<'a, N, P>
133where
134    N: NodePrimitives,
135{
136    executor: &'a reth_tasks::Runtime,
137    overlay_manager: &'a OverlayManager<N>,
138    parent_hash: B256,
139    parent_header: &'a N::BlockHeader,
140    timestamp: u64,
141    state: &'a mut EngineApiTreeState<N>,
142    state_provider_factory: OverlayStateProviderFactory<P, N>,
143    config: &'a TreeConfig,
144}
145
146impl<N, P> fmt::Debug for PayloadStateRootJobContext<'_, N, P>
147where
148    N: NodePrimitives,
149{
150    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
151        f.debug_struct("PayloadStateRootJobContext")
152            .field("parent_hash", &self.parent_hash)
153            .field("parent_state_root", &self.parent_state_root())
154            .field("timestamp", &self.timestamp)
155            .field("pending_sparse_trie_prune", &self.state.pending_sparse_trie_prune())
156            .finish_non_exhaustive()
157    }
158}
159
160impl<'a, N, P> PayloadStateRootJobContext<'a, N, P>
161where
162    N: NodePrimitives,
163{
164    /// Creates a payload-builder state-root job context.
165    #[expect(clippy::too_many_arguments)]
166    pub(crate) const fn new(
167        executor: &'a reth_tasks::Runtime,
168        overlay_manager: &'a OverlayManager<N>,
169        parent_hash: B256,
170        parent_header: &'a N::BlockHeader,
171        timestamp: u64,
172        state: &'a mut EngineApiTreeState<N>,
173        state_provider_factory: OverlayStateProviderFactory<P, N>,
174        config: &'a TreeConfig,
175    ) -> Self {
176        Self {
177            executor,
178            overlay_manager,
179            parent_hash,
180            parent_header,
181            timestamp,
182            state,
183            state_provider_factory,
184            config,
185        }
186    }
187
188    /// Returns the parent block hash for the payload being built.
189    pub const fn parent_hash(&self) -> B256 {
190        self.parent_hash
191    }
192
193    /// Returns the parent block header for the payload being built.
194    ///
195    /// This is the chain's concrete header type, so chain-specific strategies can read
196    /// chain-specific fields, and number-activated forks can dispatch on the parent number.
197    pub const fn parent_header(&self) -> &N::BlockHeader {
198        self.parent_header
199    }
200
201    /// Returns the parent state root for the payload being built.
202    pub fn parent_state_root(&self) -> B256 {
203        self.parent_header.state_root()
204    }
205
206    /// Returns the timestamp of the payload being built, taken from the payload attributes.
207    ///
208    /// Strategies that switch behavior at a fork activation can dispatch on this value.
209    pub const fn timestamp(&self) -> u64 {
210        self.timestamp
211    }
212
213    /// Returns the task runtime used by state-root work.
214    pub const fn executor(&self) -> &reth_tasks::Runtime {
215        self.executor
216    }
217
218    /// Consumes the pending sparse trie prune request as in-memory parent-chain blocks, if any.
219    ///
220    /// Custom strategies that maintain a reusable sparse trie should call this when starting the
221    /// corresponding job. Strategies that do not use the request should leave it pending.
222    pub fn take_sparse_trie_prune_blocks(&mut self) -> Option<Vec<ExecutedBlock<N>>> {
223        self.state.take_sparse_trie_prune_blocks(self.parent_hash)
224    }
225}
226
227/// Data available while preparing one state-root job.
228pub struct StateRootJobContext<'a, N, P, Evm>
229where
230    N: NodePrimitives,
231    Evm: ConfigureEvm<Primitives = N>,
232{
233    executor: &'a reth_tasks::Runtime,
234    overlay_manager: &'a OverlayManager<N>,
235    env: &'a ExecutionEnv<Evm>,
236    parent_header: &'a SealedHeader<N::BlockHeader>,
237    state_provider_factory: OverlayStateProviderFactory<P, N>,
238    config: &'a TreeConfig,
239    parallel_bal_execution: bool,
240    state: &'a mut EngineApiTreeState<N>,
241}
242
243impl<N, P, Evm> fmt::Debug for StateRootJobContext<'_, N, P, Evm>
244where
245    N: NodePrimitives,
246    Evm: ConfigureEvm<Primitives = N>,
247{
248    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
249        f.debug_struct("StateRootJobContext")
250            .field("parallel_bal_execution", &self.parallel_bal_execution)
251            .field("has_pending_sparse_trie_prune", &self.state.pending_sparse_trie_prune())
252            .finish_non_exhaustive()
253    }
254}
255
256impl<'a, N, P, Evm> StateRootJobContext<'a, N, P, Evm>
257where
258    N: NodePrimitives,
259    Evm: ConfigureEvm<Primitives = N>,
260{
261    /// Creates a new state-root job context.
262    #[expect(clippy::too_many_arguments)]
263    pub(crate) const fn new(
264        executor: &'a reth_tasks::Runtime,
265        overlay_manager: &'a OverlayManager<N>,
266        env: &'a ExecutionEnv<Evm>,
267        parent_header: &'a SealedHeader<N::BlockHeader>,
268        state_provider_factory: OverlayStateProviderFactory<P, N>,
269        config: &'a TreeConfig,
270        parallel_bal_execution: bool,
271        state: &'a mut EngineApiTreeState<N>,
272    ) -> Self {
273        Self {
274            executor,
275            overlay_manager,
276            env,
277            parent_header,
278            state_provider_factory,
279            config,
280            parallel_bal_execution,
281            state,
282        }
283    }
284
285    /// Returns the execution environment for the block.
286    pub const fn env(&self) -> &ExecutionEnv<Evm> {
287        self.env
288    }
289
290    /// Returns the sealed parent block header.
291    pub const fn parent_header(&self) -> &SealedHeader<N::BlockHeader> {
292        self.parent_header
293    }
294
295    /// Returns the task runtime used by state-root work.
296    pub const fn executor(&self) -> &reth_tasks::Runtime {
297        self.executor
298    }
299
300    /// Returns true when validation will use the parallel BAL execution path.
301    pub const fn parallel_bal_execution(&self) -> bool {
302        self.parallel_bal_execution
303    }
304
305    /// Consumes the pending sparse trie prune request as in-memory parent-chain blocks, if any.
306    ///
307    /// Custom strategies that maintain a reusable sparse trie should call this when starting the
308    /// corresponding job. Strategies that do not use the request should leave it pending.
309    pub fn take_sparse_trie_prune_blocks(&mut self) -> Option<Vec<ExecutedBlock<N>>> {
310        self.state.take_sparse_trie_prune_blocks(self.env.parent_hash)
311    }
312}
313
314/// Prepared per-block state-root work and its update-stream capabilities.
315///
316/// The capabilities are populated by the strategy's `prepare` according to the execution
317/// mode: the execution hook on the serial path, the hashed update stream on the parallel BAL
318/// path, never both. Each capability is taken once by the code that produces its messages
319/// and is not retained here, so the task's update channel closes when the producers are done.
320pub struct PreparedStateRootJob<N: NodePrimitives> {
321    job: Box<dyn StateRootJob<N>>,
322    execution_hook: Option<StateRootUpdateHook>,
323    hint_stream: Option<StateRootHintStream>,
324    hashed_update_stream: Option<StateRootUpdateStream>,
325    hashed_state_rx: Option<mpsc::Receiver<Arc<HashedPostState>>>,
326}
327
328impl<N: NodePrimitives> fmt::Debug for PreparedStateRootJob<N> {
329    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
330        f.debug_struct("PreparedStateRootJob")
331            .field("name", &self.job.name())
332            .field("has_execution_hook", &self.execution_hook.is_some())
333            .field("has_hint_stream", &self.hint_stream.is_some())
334            .field("has_hashed_update_stream", &self.hashed_update_stream.is_some())
335            .field("has_hashed_state_rx", &self.hashed_state_rx.is_some())
336            .finish()
337    }
338}
339
340impl<N: NodePrimitives> PreparedStateRootJob<N> {
341    /// Creates a prepared state-root job without update-stream capabilities.
342    pub const fn new(
343        job: Box<dyn StateRootJob<N>>,
344        hashed_state_rx: Option<mpsc::Receiver<Arc<HashedPostState>>>,
345    ) -> Self {
346        Self {
347            job,
348            execution_hook: None,
349            hint_stream: None,
350            hashed_update_stream: None,
351            hashed_state_rx,
352        }
353    }
354
355    /// Attaches the execution hook capability (serial execution path).
356    pub fn with_execution_hook(mut self, hook: StateRootUpdateHook) -> Self {
357        self.execution_hook = Some(hook);
358        self
359    }
360
361    /// Attaches the hint stream capability.
362    pub fn with_hint_stream(mut self, hint_stream: StateRootHintStream) -> Self {
363        self.hint_stream = Some(hint_stream);
364        self
365    }
366
367    /// Attaches the hashed update stream capability (parallel BAL path).
368    pub fn with_hashed_update_stream(mut self, stream: StateRootUpdateStream) -> Self {
369        self.hashed_update_stream = Some(stream);
370        self
371    }
372
373    /// Returns the job name used in logs.
374    pub fn name(&self) -> &'static str {
375        self.job.name()
376    }
377
378    /// Takes the execution hook, present only when the job wants normal execution updates.
379    pub const fn take_execution_hook(&mut self) -> Option<StateRootUpdateHook> {
380        self.execution_hook.take()
381    }
382
383    /// Takes the hint stream for transaction prewarming.
384    pub const fn take_hint_stream(&mut self) -> Option<StateRootHintStream> {
385        self.hint_stream.take()
386    }
387
388    /// Takes the hashed update stream, present only on the parallel BAL path.
389    pub const fn take_hashed_update_stream(&mut self) -> Option<StateRootUpdateStream> {
390        self.hashed_update_stream.take()
391    }
392
393    /// Takes the optional hashed-state receiver produced by the job.
394    ///
395    /// The sender behind a returned receiver must either deliver one value or be dropped;
396    /// validation blocks on it while hashing the post state, so a job that keeps the sender
397    /// alive without sending stalls block validation.
398    pub const fn take_hashed_state_rx(&mut self) -> Option<mpsc::Receiver<Arc<HashedPostState>>> {
399        self.hashed_state_rx.take()
400    }
401
402    /// Completes the job after execution.
403    pub fn finish(
404        &mut self,
405        block: &RecoveredBlock<N::Block>,
406        output: Arc<BlockExecutionOutput<N::Receipt>>,
407        hashed_state: &LazyHashedPostState,
408    ) -> ProviderResult<StateRootJobOutcome> {
409        self.job.finish(block, output, hashed_state)
410    }
411}
412
413/// Per-block state-root job prepared before execution and finished after execution.
414pub trait StateRootJob<N: NodePrimitives>: Send {
415    /// Human-readable strategy name used in logs.
416    fn name(&self) -> &'static str;
417
418    /// Completes the job after execution.
419    ///
420    /// Called at most once per prepared job; implementations may panic if called again.
421    fn finish(
422        &mut self,
423        block: &RecoveredBlock<N::Block>,
424        output: Arc<BlockExecutionOutput<N::Receipt>>,
425        hashed_state: &LazyHashedPostState,
426    ) -> ProviderResult<StateRootJobOutcome>;
427}
428
429/// Outcome of a per-block state-root job.
430#[derive(Debug)]
431pub struct StateRootJobOutcome {
432    /// Computed state root.
433    pub state_root: B256,
434    /// Trie updates associated with the computed state root.
435    pub trie_updates: Arc<TrieUpdates>,
436    /// Hashed post state recomputed by a fallback path.
437    ///
438    /// When set, the root was not derived from the streamed updates, so validation replaces its
439    /// streaming-derived hashed post state with this one and re-runs hashed-state checks.
440    pub hashed_state: Option<Arc<HashedPostState>>,
441}
442
443impl StateRootJobOutcome {
444    /// Creates a state-root job outcome.
445    pub const fn new(state_root: B256, trie_updates: Arc<TrieUpdates>) -> Self {
446        Self { state_root, trie_updates, hashed_state: None }
447    }
448
449    /// Sets the hashed post state recomputed by a fallback path.
450    pub fn with_hashed_state(mut self, hashed_state: Option<Arc<HashedPostState>>) -> Self {
451        self.hashed_state = hashed_state;
452        self
453    }
454}
455
456/// Receiver for the raced serial state-root fallback: root, trie updates, and the hashed
457/// post state the fallback recomputed.
458type SerialFallbackRx = mpsc::Receiver<ProviderResult<(B256, TrieUpdates, Arc<HashedPostState>)>>;
459
460/// Default state-root strategy used by engine-tree validation.
461///
462/// Covers the built-in modes: the sparse-trie state-root task, plus the skipped and
463/// synchronous modes selected by [`TreeConfig`].
464///
465/// Custom strategies can hold this type and delegate to it for blocks where they want the
466/// default behavior.
467#[derive(Default)]
468pub struct DefaultStateRootStrategy {
469    metrics: SparseTrieTaskMetrics,
470    proof_worker_metrics: ProofWorkerIdleMetrics,
471}
472
473impl fmt::Debug for DefaultStateRootStrategy {
474    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
475        f.debug_struct("DefaultStateRootStrategy").finish_non_exhaustive()
476    }
477}
478
479impl DefaultStateRootStrategy {
480    /// Transaction count at or below which a block gets a quarter of the proof worker pool, since
481    /// fewer transactions produce fewer state changes and most workers would be idle overhead.
482    const SMALL_BLOCK_PROOF_WORKER_TX_THRESHOLD: usize = 30;
483
484    /// Gas used at or above which a block gets the full proof worker pool.
485    ///
486    /// More workers help drain the proof queue on large blocks while storage reads are blocked.
487    const LARGE_BLOCK_PROOF_WORKER_GAS_THRESHOLD: u64 = 100_000_000;
488
489    /// Returns how many workers to spawn for the block being validated from one kind of proof
490    /// worker pool, given its capacity.
491    ///
492    /// Explicit counts take precedence. Otherwise, small transaction counts use a quarter of
493    /// the capacity, large gas usage uses all of it, and unknown or regular blocks use half.
494    /// The transaction threshold is checked first, regardless of gas usage.
495    const fn proof_worker_count(
496        pool_threads: usize,
497        configured_threads: Option<usize>,
498        transaction_count: Option<usize>,
499        gas_used: Option<u64>,
500    ) -> usize {
501        let count = if let Some(configured_threads) = configured_threads {
502            configured_threads
503        } else {
504            match (transaction_count, gas_used) {
505                (Some(count), _) if count <= Self::SMALL_BLOCK_PROOF_WORKER_TX_THRESHOLD => {
506                    pool_threads / 4
507                }
508                (_, Some(gas)) if gas >= Self::LARGE_BLOCK_PROOF_WORKER_GAS_THRESHOLD => {
509                    pool_threads
510                }
511                _ => pool_threads / 2,
512            }
513        };
514
515        // Pools can be smaller than two threads, and a pinned count can be zero; a block without
516        // workers stalls the proofs.
517        if count == 0 {
518            1
519        } else {
520            count
521        }
522    }
523
524    /// Spawns the default state-root computation pipeline.
525    ///
526    /// The authoritative update capability taken from the returned handle must be dropped or
527    /// explicitly finished after execution so the task observes the end of the update stream.
528    /// Publish the returned pending trie with [`publish_sparse_trie`] only after accepting the
529    /// matching block root. Dropping that receiver discards the reusable trie.
530    #[instrument(level = "debug", target = "engine::tree::payload_processor", skip_all)]
531    pub fn spawn_state_root<N, F>(
532        &self,
533        executor: &reth_tasks::Runtime,
534        multiproof_provider_factory: OverlayStateProviderFactory<F, N>,
535        options: StateRootTaskOptions<'_, N>,
536    ) -> (StateRootHandle, mpsc::Receiver<PendingSparseTrie>)
537    where
538        N: NodePrimitives,
539        F: DatabaseProviderFactory + Clone + 'static,
540        F::Provider: BlockNumReader
541            + PruneCheckpointReader
542            + StageCheckpointReader
543            + ChangeSetReader
544            + StorageChangeSetReader
545            + StorageSettingsCache
546            + 'static,
547    {
548        let StateRootTaskOptions {
549            parent_header,
550            preserved_sparse_trie,
551            transaction_count,
552            gas_used,
553            config,
554            pending_sparse_trie_prune_blocks,
555        } = options;
556        let (updates_tx, from_multi_proof) = channel::unbounded();
557        let (cancel_guard, cancel_rx) = StateRootTaskCancelGuard::channel();
558
559        let worker_counts = ProofWorkerCounts::new(
560            Self::proof_worker_count(
561                executor.proof_storage_worker_pool().num_threads(),
562                executor.proof_storage_worker_threads_override(),
563                transaction_count,
564                gas_used,
565            ),
566            Self::proof_worker_count(
567                executor.proof_account_worker_pool().num_threads(),
568                executor.proof_account_worker_threads_override(),
569                transaction_count,
570                gas_used,
571            ),
572        );
573        let (state_root_tx, state_root_rx) = mpsc::channel();
574        let (pending_trie_tx, pending_trie_rx) = mpsc::channel();
575        let (hashed_state_tx, hashed_state_rx) = mpsc::channel();
576        let parent_state_root = parent_header.state_root();
577
578        self.spawn_sparse_trie_task(
579            executor,
580            multiproof_provider_factory,
581            state_root_tx,
582            hashed_state_tx,
583            from_multi_proof,
584            cancel_rx,
585            SparseTrieTaskOptions {
586                parent_header,
587                preserved_sparse_trie,
588                pending_trie_tx,
589                chunk_size: config.multiproof_chunk_size(),
590                worker_counts,
591                #[cfg(feature = "trie-debug")]
592                proof_jitter: config.proof_jitter(),
593                pending_sparse_trie_prune_blocks: if config.disable_sparse_trie_cache_pruning() {
594                    None
595                } else {
596                    pending_sparse_trie_prune_blocks
597                },
598            },
599        );
600
601        (
602            StateRootHandle::new(
603                parent_state_root,
604                updates_tx,
605                cancel_guard,
606                state_root_rx,
607                hashed_state_rx,
608            ),
609            pending_trie_rx,
610        )
611    }
612
613    /// Spawns the sparse-trie task and hands off its pending trie for later publication.
614    #[expect(clippy::too_many_arguments)]
615    fn spawn_sparse_trie_task<N, F>(
616        &self,
617        executor: &reth_tasks::Runtime,
618        multiproof_provider_factory: OverlayStateProviderFactory<F, N>,
619        state_root_tx: mpsc::Sender<Result<StateRootComputeOutcome, StateRootTaskError>>,
620        hashed_state_tx: mpsc::Sender<Arc<HashedPostState>>,
621        from_multi_proof: Receiver<StateRootMessage>,
622        cancel_rx: Receiver<()>,
623        options: SparseTrieTaskOptions<N>,
624    ) where
625        N: NodePrimitives,
626        F: DatabaseProviderFactory + Clone + 'static,
627        F::Provider: BlockNumReader
628            + PruneCheckpointReader
629            + StageCheckpointReader
630            + ChangeSetReader
631            + StorageChangeSetReader
632            + StorageSettingsCache
633            + 'static,
634    {
635        let SparseTrieTaskOptions {
636            parent_header,
637            preserved_sparse_trie,
638            pending_trie_tx,
639            chunk_size,
640            worker_counts,
641            #[cfg(feature = "trie-debug")]
642            proof_jitter,
643            pending_sparse_trie_prune_blocks,
644        } = options;
645        let trie_metrics = self.metrics.clone();
646        let worker_metrics = self.proof_worker_metrics.clone();
647        let executor = executor.clone();
648
649        let parent_span = Span::current();
650        executor.clone().spawn_blocking_named("sparse-trie", move || {
651            reth_tasks::once!(increase_thread_priority);
652
653            let parent_hash = parent_header.hash();
654            let parent_state_root = parent_header.state_root();
655            let new_epoch = TrieNodeEpoch::new(parent_header.number().saturating_add(1));
656
657            let _enter = debug_span!(
658                target: "engine::tree::payload_processor",
659                parent: &parent_span,
660                "sparse_trie_task"
661            )
662            .entered();
663
664            let new_sparse_state_trie = || {
665                debug!(
666                    target: "engine::tree::payload_processor",
667                    "Creating new sparse trie - no preserved trie available"
668                );
669                let default_trie =
670                    RevealableSparseTrie::blind_from(ArenaParallelSparseTrie::default());
671                SparseStateTrie::default()
672                    .with_accounts_trie(default_trie.clone())
673                    .with_default_storage_trie(default_trie)
674                    .with_updates(true)
675            };
676
677            let mut sparse_trie_anchor_hash = parent_hash;
678            let mut reused_preserved_sparse_trie = false;
679            let mut known_storage_roots = Default::default();
680            let sparse_state_trie = match preserved_sparse_trie {
681                Some(preserved) => {
682                    let start = Instant::now();
683                    let preserved_anchor_hash = preserved.anchor_hash();
684                    let preserved = preserved.into_trie_for(parent_hash);
685                    trie_metrics
686                        .sparse_trie_cache_wait_duration_histogram
687                        .record(start.elapsed().as_secs_f64());
688
689                    match preserved {
690                        Ok(Some(SparseTrieWithStorageRoots { trie, storage_roots })) => {
691                            known_storage_roots = storage_roots;
692                            sparse_trie_anchor_hash = preserved_anchor_hash;
693                            reused_preserved_sparse_trie = true;
694                            trie
695                        }
696                        Ok(None) => new_sparse_state_trie(),
697                        Err(err) => {
698                            let _ = state_root_tx.send(Err(StateRootTaskError::Other(err.into())));
699                            return;
700                        }
701                    }
702                }
703                None => new_sparse_state_trie(),
704            };
705            let prune_target = sparse_trie_prune_target(
706                sparse_trie_anchor_hash,
707                reused_preserved_sparse_trie,
708                parent_header.num_hash(),
709                pending_sparse_trie_prune_blocks.as_deref(),
710            );
711            let factory = if reused_preserved_sparse_trie {
712                multiproof_provider_factory.with_skip_overlay_for_reused_sparse_trie(
713                    sparse_trie_anchor_hash,
714                    known_storage_roots,
715                )
716            } else {
717                multiproof_provider_factory
718            };
719            let task_ctx = ProofTaskCtx::new(factory);
720            #[cfg(feature = "trie-debug")]
721            let task_ctx = task_ctx.with_proof_jitter(proof_jitter);
722            let proof_worker_handle =
723                ProofWorkerHandle::new(&executor, task_ctx, worker_counts, worker_metrics);
724            let mut task = SparseTrieCacheTask::new_with_trie(
725                &executor,
726                from_multi_proof,
727                cancel_rx,
728                hashed_state_tx,
729                proof_worker_handle,
730                trie_metrics.clone(),
731                sparse_state_trie,
732                parent_state_root,
733                new_epoch,
734                chunk_size,
735            );
736
737            let result = task.run();
738            // Send the pending handle before the result so acceptance never waits for pruning.
739            let trie_completer = if let Ok(outcome) = &result {
740                let preserved_anchor_hash =
741                    prune_target.map_or(sparse_trie_anchor_hash, |(_, anchor_hash)| anchor_hash);
742                let (tx, rx) = mpsc::channel();
743                let pending = PendingSparseTrie {
744                    state_root: outcome.state_root,
745                    anchor_hash: preserved_anchor_hash,
746                    trie: rx,
747                };
748                pending_trie_tx.send(pending).is_ok().then_some(tx)
749            } else {
750                None
751            };
752
753            if state_root_tx.send(result).is_err() {
754                debug!(
755                    target: "engine::tree::payload_processor",
756                    "State root receiver dropped"
757                );
758            }
759            drop(pending_trie_tx);
760
761            let _enter =
762                debug_span!(target: "engine::tree::payload_processor", "preserve").entered();
763            let (trie_to_drop, deferred) = if let Some(completer) = trie_completer {
764                // Complete every handed-off handle, even if the root receiver was abandoned:
765                // a builder may have accepted the matching root through another strategy.
766                let start = Instant::now();
767                let (mut trie, deferred) = task.into_trie_for_reuse();
768                let storage_roots = trie.storage_roots(new_epoch);
769                if let Some((prune_before, _)) = prune_target {
770                    let prune_start = Instant::now();
771                    trie.prune(prune_before);
772                    trie_metrics
773                        .sparse_trie_prune_duration_histogram
774                        .record(prune_start.elapsed().as_secs_f64());
775                }
776                trie_metrics
777                    .into_trie_for_reuse_duration_histogram
778                    .record(start.elapsed().as_secs_f64());
779                trie_metrics
780                    .sparse_trie_retained_storage_tries
781                    .set(trie.retained_storage_tries_count() as f64);
782                (
783                    completer
784                        .send(SparseTrieWithStorageRoots { trie, storage_roots })
785                        .err()
786                        .map(|err| err.0.trie),
787                    deferred,
788                )
789            } else {
790                debug!(
791                    target: "engine::tree::payload_processor",
792                    "State root task has no reusable trie to publish, dropping trie"
793                );
794                let (trie, deferred) = task.into_cleared_trie();
795                (Some(trie), deferred)
796            };
797            if let Some(trie) = trie_to_drop {
798                executor.spawn_drop(trie);
799            }
800            executor.spawn_drop(deferred);
801        });
802    }
803}
804
805/// A computed trie whose finalization and pruning may still be running.
806#[derive(Debug)]
807pub struct PendingSparseTrie {
808    state_root: B256,
809    anchor_hash: B256,
810    trie: mpsc::Receiver<SparseTrieWithStorageRoots>,
811}
812
813/// Publishes a matching completed root for reuse after its block has been accepted.
814///
815/// Does nothing if the producer has not handed off a trie or its root differs.
816pub fn publish_sparse_trie<N: NodePrimitives>(
817    pending_trie_rx: &mpsc::Receiver<PendingSparseTrie>,
818    overlay_manager: &OverlayManager<N>,
819    block_hash: B256,
820    state_root: B256,
821) {
822    // Validation has already received the root. A builder using another strategy may finish
823    // before the sparse task; it must not wait for that task just to populate the cache.
824    if let Ok(pending) = pending_trie_rx.try_recv() &&
825        pending.state_root == state_root
826    {
827        overlay_manager.store_sparse_trie(PreservedSparseTrie::pending(
828            pending.trie,
829            block_hash,
830            pending.anchor_hash,
831        ));
832    }
833}
834
835struct SparseTrieTaskOptions<N: NodePrimitives> {
836    parent_header: SealedHeader<N::BlockHeader>,
837    preserved_sparse_trie: Option<PreservedSparseTrie>,
838    pending_trie_tx: mpsc::Sender<PendingSparseTrie>,
839    chunk_size: usize,
840    worker_counts: ProofWorkerCounts,
841    #[cfg(feature = "trie-debug")]
842    proof_jitter: Option<Duration>,
843    /// `None` disables pruning. `Some(Vec::new())` prunes nodes older than the current block.
844    pending_sparse_trie_prune_blocks: Option<Vec<ExecutedBlock<N>>>,
845}
846
847/// Inputs for starting one sparse-trie task and its proof workers.
848///
849/// Complete the returned handle's authoritative update stream before awaiting its result.
850#[derive(Debug)]
851pub struct StateRootTaskOptions<'a, N: NodePrimitives> {
852    /// Accepted parent whose post-state the proof workers must read.
853    pub parent_header: SealedHeader<N::BlockHeader>,
854    /// Previously accepted trie, or `None` for a cold start.
855    pub preserved_sparse_trie: Option<PreservedSparseTrie>,
856    /// Transaction count hint for proof-worker sizing, or `None` if unknown.
857    pub transaction_count: Option<usize>,
858    /// Gas the block claims to use, or `None` if unknown.
859    pub gas_used: Option<u64>,
860    /// Task and proof batching configuration.
861    pub config: &'a TreeConfig,
862    /// In-memory parent chain, newest first, when pruning is requested.
863    ///
864    /// `None` disables pruning; an empty chain means the parent is durable.
865    pub pending_sparse_trie_prune_blocks: Option<Vec<ExecutedBlock<N>>>,
866}
867
868fn sparse_trie_prune_target<N: NodePrimitives>(
869    current_anchor: B256,
870    reused_preserved_sparse_trie: bool,
871    parent: alloy_eips::BlockNumHash,
872    pending_blocks: Option<&[ExecutedBlock<N>]>,
873) -> Option<(TrieNodeEpoch, B256)> {
874    let blocks = pending_blocks?;
875    let Some(oldest) = blocks.last() else {
876        // Pruning the now-durable parent moves the proof source forward with it.
877        return Some((TrieNodeEpoch::new(parent.number.saturating_add(1)), parent.hash))
878    };
879    let anchor = if !reused_preserved_sparse_trie ||
880        blocks.iter().any(|block| block.recovered_block().hash() == current_anchor)
881    {
882        current_anchor
883    } else {
884        oldest.recovered_block().parent_hash()
885    };
886    Some((TrieNodeEpoch::new(oldest.recovered_block().number()), anchor))
887}
888
889impl<N, P, Evm> StateRootStrategy<N, P, Evm> for DefaultStateRootStrategy
890where
891    N: NodePrimitives,
892    P: DatabaseProviderFactory + Clone + 'static,
893    P::Provider: BlockNumReader
894        + PruneCheckpointReader
895        + StageCheckpointReader
896        + ChangeSetReader
897        + StorageChangeSetReader
898        + StorageSettingsCache
899        + 'static,
900    Evm: ConfigureEvm<Primitives = N> + 'static,
901{
902    fn prepare(
903        &self,
904        mut ctx: StateRootJobContext<'_, N, P, Evm>,
905    ) -> ProviderResult<PreparedStateRootJob<N>> {
906        if ctx.config.skip_state_root() {
907            return Ok(PreparedStateRootJob::new(Box::new(SkippedStateRootJob {}), None))
908        }
909
910        if !ctx.config.use_state_root_task() {
911            return Ok(PreparedStateRootJob::new(
912                Box::new(SynchronousStateRootJob {
913                    state_provider_factory: ctx.state_provider_factory,
914                }),
915                None,
916            ))
917        }
918
919        let pending_sparse_trie_prune_blocks = ctx.take_sparse_trie_prune_blocks();
920        let StateRootJobContext {
921            executor,
922            overlay_manager,
923            env,
924            parent_header,
925            state_provider_factory,
926            config,
927            parallel_bal_execution,
928            state: _,
929        } = ctx;
930
931        let preserved_sparse_trie = overlay_manager.take_sparse_trie();
932        let (mut handle, pending_trie_rx) = self.spawn_state_root(
933            executor,
934            state_provider_factory.clone(),
935            StateRootTaskOptions {
936                parent_header: parent_header.clone(),
937                preserved_sparse_trie,
938                transaction_count: Some(env.transaction_count),
939                gas_used: Some(env.gas_used),
940                config,
941                pending_sparse_trie_prune_blocks,
942            },
943        );
944
945        // The execution mode decides who finishes the update stream: the execution hook on
946        // the serial path, the BAL streamer on the parallel path. Both come from one slot in
947        // the handle, so only one of them can exist.
948        let (hashed_update_stream, execution_hook): (
949            Option<StateRootUpdateStream>,
950            Option<StateRootUpdateHook>,
951        ) = match parallel_bal_execution {
952            true => (Some(handle.take_hashed_update_stream()), None),
953            false => (None, Some(handle.take_execution_hook())),
954        };
955        let hint_stream = handle.take_hint_stream();
956
957        let hashed_state_rx = Some(handle.take_hashed_state_rx());
958
959        let mut prepared = PreparedStateRootJob::new(
960            Box::new(SparseTrieStateRootJob {
961                pending_trie_rx,
962                overlay_manager: overlay_manager.clone(),
963                handle,
964                state_provider_factory,
965                executor: executor.clone(),
966                timeout: config.state_root_task_timeout(),
967                metrics: BlockValidationMetrics::default(),
968            }),
969            hashed_state_rx,
970        )
971        .with_hint_stream(hint_stream);
972        if let Some(hook) = execution_hook {
973            prepared = prepared.with_execution_hook(hook);
974        }
975        if let Some(stream) = hashed_update_stream {
976            prepared = prepared.with_hashed_update_stream(stream);
977        }
978        Ok(prepared)
979    }
980
981    fn prepare_payload_builder(
982        &self,
983        mut ctx: PayloadStateRootJobContext<'_, N, P>,
984    ) -> ProviderResult<Option<PayloadStateRootHandle>> {
985        // Sharing the engine state-root task with the payload builder is opt-in, and needs a
986        // host that can run the task pipeline at all.
987        if !ctx.config.share_sparse_trie_with_payload_builder() ||
988            ctx.config.skip_state_root() ||
989            !ctx.config.has_enough_parallelism()
990        {
991            return Ok(None)
992        }
993
994        let pending_sparse_trie_prune_blocks = ctx.take_sparse_trie_prune_blocks();
995        let parent_header = SealedHeader::new(ctx.parent_header().clone(), ctx.parent_hash());
996        let preserved_sparse_trie = ctx.overlay_manager.take_sparse_trie();
997        let (handle, pending_trie_rx) = self.spawn_state_root(
998            ctx.executor,
999            ctx.state_provider_factory.clone(),
1000            StateRootTaskOptions {
1001                parent_header,
1002                preserved_sparse_trie,
1003                // Block built incrementally, so neither the tx count nor the gas is known at FCU
1004                // time: the payload builder uses half of each proof pool.
1005                transaction_count: None,
1006                gas_used: None,
1007                config: ctx.config,
1008                pending_sparse_trie_prune_blocks,
1009            },
1010        );
1011        let overlay_manager = ctx.overlay_manager.clone();
1012        Ok(Some(handle.into_payload_state_root_handle().with_on_payload_built(
1013            move |block_hash, state_root| {
1014                publish_sparse_trie(&pending_trie_rx, &overlay_manager, block_hash, state_root);
1015            },
1016        )))
1017    }
1018}
1019
1020#[derive(Debug)]
1021struct SkippedStateRootJob {}
1022
1023impl<N: NodePrimitives> StateRootJob<N> for SkippedStateRootJob {
1024    fn name(&self) -> &'static str {
1025        "skipped"
1026    }
1027
1028    fn finish(
1029        &mut self,
1030        block: &RecoveredBlock<N::Block>,
1031        _output: Arc<BlockExecutionOutput<N::Receipt>>,
1032        _hashed_state: &LazyHashedPostState,
1033    ) -> ProviderResult<StateRootJobOutcome> {
1034        Ok(StateRootJobOutcome::new(block.header().state_root(), Arc::new(TrieUpdates::default())))
1035    }
1036}
1037
1038#[derive(Debug)]
1039struct SynchronousStateRootJob<N: NodePrimitives, P> {
1040    state_provider_factory: OverlayStateProviderFactory<P, N>,
1041}
1042
1043impl<N, P> StateRootJob<N> for SynchronousStateRootJob<N, P>
1044where
1045    N: NodePrimitives,
1046    P: DatabaseProviderFactory + Clone + 'static,
1047    P::Provider: BlockNumReader
1048        + PruneCheckpointReader
1049        + StageCheckpointReader
1050        + ChangeSetReader
1051        + StorageChangeSetReader
1052        + StorageSettingsCache
1053        + 'static,
1054{
1055    fn name(&self) -> &'static str {
1056        "synchronous"
1057    }
1058
1059    fn finish(
1060        &mut self,
1061        _block: &RecoveredBlock<N::Block>,
1062        _output: Arc<BlockExecutionOutput<N::Receipt>>,
1063        hashed_state: &LazyHashedPostState,
1064    ) -> ProviderResult<StateRootJobOutcome> {
1065        let provider = self.state_provider_factory.database_provider_ro()?;
1066        let (state_root, trie_updates) =
1067            provider.state_root_with_updates(hashed_state.get().as_ref().clone())?;
1068        Ok(StateRootJobOutcome::new(state_root, Arc::new(trie_updates)))
1069    }
1070}
1071
1072#[derive(Debug)]
1073struct SparseTrieStateRootJob<N: NodePrimitives, P> {
1074    pending_trie_rx: mpsc::Receiver<PendingSparseTrie>,
1075    overlay_manager: OverlayManager<N>,
1076    handle: StateRootHandle,
1077    state_provider_factory: OverlayStateProviderFactory<P, N>,
1078    executor: reth_tasks::Runtime,
1079    timeout: Option<Duration>,
1080    metrics: BlockValidationMetrics,
1081}
1082
1083impl<N, P> SparseTrieStateRootJob<N, P>
1084where
1085    N: NodePrimitives,
1086    P: DatabaseProviderFactory + Clone + 'static,
1087    P::Provider: BlockNumReader
1088        + PruneCheckpointReader
1089        + StageCheckpointReader
1090        + ChangeSetReader
1091        + StorageChangeSetReader
1092        + StorageSettingsCache
1093        + 'static,
1094{
1095    fn serial_fallback(
1096        &self,
1097        output: Arc<BlockExecutionOutput<N::Receipt>>,
1098    ) -> ProviderResult<SerialFallbackRx> {
1099        let provider = self.state_provider_factory.database_provider_ro()?;
1100        let (fallback_tx, fallback_rx) = mpsc::channel();
1101        self.executor.spawn_blocking_named("serial-root", move || {
1102            let result = (|| {
1103                let hashed_state = Arc::new(provider.hashed_post_state(&output.state)?);
1104                let (root, updates) =
1105                    provider.state_root_with_updates(hashed_state.as_ref().clone())?;
1106                Ok((root, updates, hashed_state))
1107            })();
1108            let _ = fallback_tx.send(result);
1109        });
1110
1111        Ok(fallback_rx)
1112    }
1113
1114    /// Recomputes the state root serially from the execution output.
1115    ///
1116    /// Used when the state-root task failed or produced a wrong root, so the recomputed hashed
1117    /// post state is returned in the outcome for validation to re-check against.
1118    fn compute_serial(
1119        &self,
1120        output: &BlockExecutionOutput<N::Receipt>,
1121    ) -> ProviderResult<StateRootJobOutcome> {
1122        let provider = self.state_provider_factory.database_provider_ro()?;
1123        let hashed_state = Arc::new(provider.hashed_post_state(&output.state)?);
1124        let (state_root, trie_updates) =
1125            provider.state_root_with_updates(hashed_state.as_ref().clone())?;
1126        self.metrics.state_root_task_fallback_success_total.increment(1);
1127        Ok(StateRootJobOutcome::new(state_root, Arc::new(trie_updates))
1128            .with_hashed_state(Some(hashed_state)))
1129    }
1130
1131    /// Converts a task outcome into a job outcome, recomputing serially when the task returned
1132    /// a root that does not match the block header. A state-root-task bug then costs latency
1133    /// instead of marking a valid block invalid; if the serial root also mismatches, validation
1134    /// rejects the block.
1135    fn verified_sparse_outcome(
1136        &self,
1137        block: &RecoveredBlock<N::Block>,
1138        output: &BlockExecutionOutput<N::Receipt>,
1139        outcome: StateRootComputeOutcome,
1140    ) -> ProviderResult<StateRootJobOutcome> {
1141        let outcome = StateRootJobOutcome::new(outcome.state_root, outcome.trie_updates);
1142        if outcome.state_root == block.header().state_root() {
1143            publish_sparse_trie(
1144                &self.pending_trie_rx,
1145                &self.overlay_manager,
1146                block.hash(),
1147                outcome.state_root,
1148            );
1149            return Ok(outcome)
1150        }
1151        warn!(
1152            target: "engine::tree::state_root_strategy",
1153            state_root = ?outcome.state_root,
1154            block_state_root = ?block.header().state_root(),
1155            "State root task returned incorrect state root, recomputing serially"
1156        );
1157        self.compute_serial(output)
1158    }
1159}
1160
1161impl<N, P> StateRootJob<N> for SparseTrieStateRootJob<N, P>
1162where
1163    N: NodePrimitives,
1164    P: DatabaseProviderFactory + Clone + 'static,
1165    P::Provider: BlockNumReader
1166        + PruneCheckpointReader
1167        + StageCheckpointReader
1168        + ChangeSetReader
1169        + StorageChangeSetReader
1170        + StorageSettingsCache
1171        + 'static,
1172{
1173    fn name(&self) -> &'static str {
1174        "sparse-trie"
1175    }
1176
1177    fn finish(
1178        &mut self,
1179        block: &RecoveredBlock<N::Block>,
1180        output: Arc<BlockExecutionOutput<N::Receipt>>,
1181        _hashed_state: &LazyHashedPostState,
1182    ) -> ProviderResult<StateRootJobOutcome> {
1183        if self.timeout.is_none() {
1184            return match self.handle.state_root() {
1185                Ok(outcome) => self.verified_sparse_outcome(block, &output, outcome),
1186                Err(err) => {
1187                    debug!(target: "engine::tree::state_root_strategy", %err, "State root task failed, falling back to serial root");
1188                    self.compute_serial(&output)
1189                }
1190            }
1191        }
1192
1193        let timeout = self.timeout.expect("checked above");
1194        let task_rx = self.handle.take_state_root_rx();
1195        let fallback_rx = match task_rx.recv_timeout(timeout) {
1196            Ok(Ok(outcome)) => return self.verified_sparse_outcome(block, &output, outcome),
1197            Ok(Err(err)) => {
1198                debug!(target: "engine::tree::state_root_strategy", %err, "State root task failed, falling back to serial root");
1199                self.serial_fallback(output)?
1200            }
1201            Err(RecvTimeoutError::Timeout) => {
1202                warn!(target: "engine::tree::state_root_strategy", ?timeout, "State root task timed out, racing serial fallback");
1203                self.metrics.state_root_task_timeout_total.increment(1);
1204                self.serial_fallback(output)?
1205            }
1206            Err(RecvTimeoutError::Disconnected) => {
1207                debug!(target: "engine::tree::state_root_strategy", "State root task dropped, falling back to serial root");
1208                self.serial_fallback(output)?
1209            }
1210        };
1211
1212        loop {
1213            if let Ok(Ok(outcome)) = task_rx.try_recv() {
1214                let outcome = StateRootJobOutcome::new(outcome.state_root, outcome.trie_updates);
1215                if outcome.state_root == block.header().state_root() {
1216                    publish_sparse_trie(
1217                        &self.pending_trie_rx,
1218                        &self.overlay_manager,
1219                        block.hash(),
1220                        outcome.state_root,
1221                    );
1222                    return Ok(outcome)
1223                }
1224                // A wrong task root falls through to the serial fallback already racing below.
1225                warn!(
1226                    target: "engine::tree::state_root_strategy",
1227                    state_root = ?outcome.state_root,
1228                    block_state_root = ?block.header().state_root(),
1229                    "State root task returned incorrect state root, using serial fallback"
1230                );
1231            }
1232
1233            match fallback_rx.try_recv() {
1234                Ok(Ok((state_root, trie_updates, hashed_state))) => {
1235                    self.metrics.state_root_task_fallback_success_total.increment(1);
1236                    return Ok(StateRootJobOutcome::new(state_root, Arc::new(trie_updates))
1237                        .with_hashed_state(Some(hashed_state)))
1238                }
1239                Ok(Err(err)) => return Err(err),
1240                Err(mpsc::TryRecvError::Empty) => {}
1241                Err(mpsc::TryRecvError::Disconnected) => {
1242                    return Err(ProviderError::other(std::io::Error::other(
1243                        "serial state root fallback task dropped",
1244                    )))
1245                }
1246            }
1247
1248            thread::sleep(Duration::from_millis(1));
1249        }
1250    }
1251}
1252
1253#[cfg(test)]
1254mod tests {
1255    use super::*;
1256    use alloy_consensus::constants::KECCAK_EMPTY;
1257    use alloy_primitives::{map::HashMap, Address, U256};
1258    use evm2::evm::AccountInfo;
1259    use rand::Rng;
1260    use reth_chain_state::test_utils::TestBlockBuilder;
1261    use reth_chainspec::ChainSpec;
1262    use reth_concurrency::sync::{channel, thread};
1263    use reth_db_common::init::init_genesis;
1264    use reth_ethereum_primitives::EthPrimitives;
1265    use reth_evm::OnStateHook;
1266    use reth_evm_ethereum::EthEvmConfig;
1267    use reth_execution_types::{AccountUpdate, StateUpdate};
1268    use reth_primitives_traits::{Account, StorageEntry};
1269    use reth_provider::{
1270        providers::BlockchainProvider, test_utils::create_test_provider_factory_with_chain_spec,
1271        HashingWriter,
1272    };
1273    use reth_storage_overlay::{OverlayManager, OverlayStateProviderFactory};
1274    use reth_testing_utils::generators;
1275    use reth_trie::test_utils::state_root;
1276    use reth_trie_common::bundle_state::StorageSlot;
1277
1278    #[test]
1279    fn proof_worker_count_scales_with_block_gas() {
1280        let pool_threads = 64;
1281        let count = |transaction_count, gas_used| {
1282            DefaultStateRootStrategy::proof_worker_count(
1283                pool_threads,
1284                None,
1285                transaction_count,
1286                gas_used,
1287            )
1288        };
1289
1290        // Small blocks use a quarter of the pool, whatever their gas.
1291        assert_eq!(count(Some(30), Some(1_000_000)), 16);
1292        assert_eq!(count(Some(30), Some(300_000_000)), 16);
1293
1294        // Gas heavy blocks use the full pool.
1295        assert_eq!(count(Some(1_000), Some(100_000_000)), 64);
1296        assert_eq!(count(Some(1_000), Some(300_000_000)), 64);
1297
1298        // Everything else, including a block whose size is not known yet, uses half the pool.
1299        assert_eq!(count(Some(31), Some(99_999_999)), 32);
1300        assert_eq!(count(Some(1_000), Some(15_000_000)), 32);
1301        assert_eq!(count(None, None), 32);
1302
1303        // An explicitly configured count is used verbatim for every block.
1304        for (transaction_count, gas_used) in
1305            [(Some(30), Some(1_000_000)), (Some(1_000), Some(300_000_000)), (None, None)]
1306        {
1307            assert_eq!(
1308                DefaultStateRootStrategy::proof_worker_count(
1309                    48,
1310                    Some(48),
1311                    transaction_count,
1312                    gas_used
1313                ),
1314                48
1315            );
1316        }
1317
1318        // Pools smaller than two threads, and a pinned count of zero, still get a worker.
1319        assert_eq!(
1320            DefaultStateRootStrategy::proof_worker_count(1, None, Some(1), Some(1_000_000)),
1321            1
1322        );
1323        assert_eq!(DefaultStateRootStrategy::proof_worker_count(1, None, None, None), 1);
1324        assert_eq!(DefaultStateRootStrategy::proof_worker_count(1, Some(0), None, None), 1);
1325    }
1326
1327    #[reth_concurrency::test]
1328    fn finish_publishes_only_accepted_sparse_trie() {
1329        let factory = create_test_provider_factory_with_chain_spec(Arc::new(ChainSpec::default()));
1330        let genesis_hash = init_genesis(&factory).unwrap();
1331        let provider = BlockchainProvider::new(factory).unwrap();
1332        let runtime = reth_tasks::Runtime::test();
1333
1334        for timeout in [None, Some(Duration::from_secs(1))] {
1335            for (finish, matching_root) in [(false, true), (true, true), (true, false)] {
1336                let overlay_manager = OverlayManager::<EthPrimitives>::default();
1337                let block = RecoveredBlock::new_unhashed(
1338                    reth_ethereum_primitives::Block {
1339                        header: alloy_consensus::Header {
1340                            state_root: B256::with_last_byte(1),
1341                            ..Default::default()
1342                        },
1343                        ..Default::default()
1344                    },
1345                    Vec::new(),
1346                );
1347                let (completer, trie) = mpsc::channel();
1348                let (pending_trie_tx, pending_trie_rx) = mpsc::channel();
1349                pending_trie_tx
1350                    .send(PendingSparseTrie {
1351                        state_root: if matching_root { block.state_root } else { B256::ZERO },
1352                        anchor_hash: genesis_hash,
1353                        trie,
1354                    })
1355                    .unwrap();
1356                let (result_tx, result_rx) = mpsc::channel();
1357                result_tx
1358                    .send(Ok(StateRootComputeOutcome {
1359                        state_root: if matching_root { block.state_root } else { B256::ZERO },
1360                        trie_updates: Default::default(),
1361                        hashed_state: Default::default(),
1362                    }))
1363                    .unwrap();
1364                let mut job = SparseTrieStateRootJob {
1365                    pending_trie_rx,
1366                    overlay_manager: overlay_manager.clone(),
1367                    handle: StateRootHandle::new(
1368                        B256::ZERO,
1369                        channel::unbounded().0,
1370                        StateRootTaskCancelGuard::channel().0,
1371                        result_rx,
1372                        mpsc::channel().1,
1373                    ),
1374                    state_provider_factory: OverlayStateProviderFactory::new(
1375                        provider.clone(),
1376                        overlay_manager.overlay_builder(genesis_hash),
1377                    ),
1378                    executor: runtime.clone(),
1379                    timeout,
1380                    metrics: Default::default(),
1381                };
1382                assert!(overlay_manager.take_sparse_trie().is_none());
1383                if finish {
1384                    job.finish(
1385                        &block,
1386                        Arc::new(BlockExecutionOutput::default()),
1387                        &LazyHashedPostState::ready(Default::default()),
1388                    )
1389                    .unwrap();
1390                }
1391                drop(job);
1392                let preserved = overlay_manager.take_sparse_trie();
1393                assert_eq!(preserved.is_some(), finish && matching_root);
1394                // Publication must finish before trie finalization does.
1395                assert_eq!(
1396                    completer.send(SparseTrieWithStorageRoots::default()).is_ok(),
1397                    finish && matching_root
1398                );
1399                if let Some(preserved) = preserved {
1400                    assert!(preserved.into_trie_for(block.hash()).unwrap().is_some());
1401                }
1402            }
1403        }
1404    }
1405
1406    #[reth_concurrency::test]
1407    fn failed_parent_trie_closes_handoff_without_publishing() {
1408        let factory = create_test_provider_factory_with_chain_spec(Arc::new(ChainSpec::default()));
1409        let genesis_hash = init_genesis(&factory).unwrap();
1410        let runtime = reth_tasks::Runtime::test();
1411        {
1412            let (completer, trie) = mpsc::channel();
1413            let preserved = PreservedSparseTrie::pending(trie, genesis_hash, B256::ZERO);
1414            drop(completer);
1415            let (mut handle, pending_trie_rx) = DefaultStateRootStrategy::default()
1416                .spawn_state_root(
1417                    &runtime,
1418                    OverlayStateProviderFactory::new(
1419                        factory,
1420                        OverlayManager::<EthPrimitives>::default().overlay_builder(genesis_hash),
1421                    ),
1422                    StateRootTaskOptions::<EthPrimitives> {
1423                        parent_header: SealedHeader::new(Default::default(), genesis_hash),
1424                        preserved_sparse_trie: Some(preserved),
1425                        transaction_count: None,
1426                        gas_used: None,
1427                        config: &TreeConfig::default(),
1428                        pending_sparse_trie_prune_blocks: None,
1429                    },
1430                );
1431            assert!(handle.state_root().is_err());
1432            assert!(matches!(
1433                pending_trie_rx.recv_timeout(Duration::from_secs(5)),
1434                Err(RecvTimeoutError::Disconnected)
1435            ));
1436        }
1437        for name in ["sparse-trie", "storage-workers", "account-workers"] {
1438            runtime.spawn_blocking_named(name, || {}).get();
1439        }
1440    }
1441
1442    #[reth_concurrency::test]
1443    fn publication_does_not_wait_for_worker() {
1444        let (pending_trie_tx, pending_trie_rx) = mpsc::channel();
1445        let overlay_manager = OverlayManager::<EthPrimitives>::default();
1446        let (done_tx, done_rx) = mpsc::channel();
1447        let worker = thread::spawn(move || {
1448            publish_sparse_trie(&pending_trie_rx, &overlay_manager, B256::ZERO, B256::ZERO);
1449            assert!(overlay_manager.take_sparse_trie().is_none());
1450            done_tx.send(()).unwrap();
1451        });
1452        let result = done_rx.recv_timeout(Duration::from_secs(5));
1453        drop(pending_trie_tx);
1454        worker.join().unwrap();
1455        result.expect("publication should not wait for the root task");
1456    }
1457
1458    #[reth_concurrency::test]
1459    fn dropped_root_receiver_still_completes_pending_trie() {
1460        let factory = create_test_provider_factory_with_chain_spec(Arc::new(ChainSpec::default()));
1461        let genesis_hash = init_genesis(&factory).unwrap();
1462        let runtime = reth_tasks::Runtime::test();
1463        let (mut handle, pending_trie_rx) = DefaultStateRootStrategy::default().spawn_state_root(
1464            &runtime,
1465            OverlayStateProviderFactory::new(
1466                factory,
1467                OverlayManager::<EthPrimitives>::default().overlay_builder(genesis_hash),
1468            ),
1469            StateRootTaskOptions::<EthPrimitives> {
1470                parent_header: SealedHeader::new(Default::default(), genesis_hash),
1471                preserved_sparse_trie: None,
1472                transaction_count: None,
1473                gas_used: None,
1474                config: &TreeConfig::default(),
1475                pending_sparse_trie_prune_blocks: None,
1476            },
1477        );
1478        drop(handle.take_state_root_rx());
1479        drop(handle.take_execution_hook());
1480        let pending = pending_trie_rx.recv_timeout(Duration::from_secs(5)).unwrap();
1481        assert_eq!(pending.anchor_hash, genesis_hash);
1482        pending
1483            .trie
1484            .recv_timeout(Duration::from_secs(5))
1485            .expect("handed-off trie must be completed");
1486        drop(handle);
1487        for name in ["sparse-trie", "trie-hashing", "storage-workers", "account-workers", "drop"] {
1488            runtime.spawn_blocking_named(name, || {}).get();
1489        }
1490    }
1491
1492    #[test]
1493    fn sparse_trie_prune_target_uses_requested_range() {
1494        let parent = alloy_eips::BlockNumHash { hash: B256::with_last_byte(9), number: 9 };
1495        assert_eq!(
1496            sparse_trie_prune_target::<EthPrimitives>(B256::ZERO, false, parent, None),
1497            None
1498        );
1499        assert_eq!(
1500            sparse_trie_prune_target::<EthPrimitives>(B256::ZERO, false, parent, Some(&[])),
1501            Some((TrieNodeEpoch::new(10), parent.hash))
1502        );
1503
1504        let mut blocks: Vec<_> = TestBlockBuilder::eth().get_executed_blocks(7..10).collect();
1505        blocks.reverse();
1506
1507        let anchor = blocks[0].recovered_block().hash();
1508        assert_eq!(
1509            sparse_trie_prune_target(anchor, true, parent, Some(&blocks)),
1510            Some((TrieNodeEpoch::new(7), anchor))
1511        );
1512    }
1513
1514    #[test]
1515    fn sparse_trie_prune_target_advances_to_prune_anchor() {
1516        let blocks: Vec<_> = TestBlockBuilder::eth().get_executed_blocks(1..5).collect();
1517        let reused_anchor_hash = blocks[0].recovered_block().hash();
1518        let expected_prune_anchor = blocks[1].recovered_block().hash();
1519        let parent = blocks[3].recovered_block().num_hash();
1520        let prune_blocks: Vec<_> = blocks.into_iter().skip(2).rev().collect();
1521
1522        assert_eq!(
1523            sparse_trie_prune_target(reused_anchor_hash, true, parent, Some(&prune_blocks),),
1524            Some((TrieNodeEpoch::new(3), expected_prune_anchor))
1525        );
1526    }
1527
1528    #[test]
1529    fn sparse_trie_prune_target_keeps_parent_for_fresh_trie() {
1530        let mut blocks: Vec<_> = TestBlockBuilder::eth().get_executed_blocks(1..3).collect();
1531        blocks.reverse();
1532        let parent_hash = B256::with_last_byte(0xaa);
1533
1534        assert_eq!(
1535            sparse_trie_prune_target(
1536                parent_hash,
1537                false,
1538                blocks[0].recovered_block().num_hash(),
1539                Some(&blocks),
1540            ),
1541            Some((TrieNodeEpoch::new(1), parent_hash))
1542        );
1543    }
1544
1545    #[test]
1546    fn sparse_trie_prune_target_advances_reused_anchor_when_parent_becomes_durable() {
1547        let blocks: Vec<_> = TestBlockBuilder::eth().get_executed_blocks(1..4).collect();
1548        let old_anchor = blocks[1].recovered_block().hash();
1549        let parent = blocks[2].recovered_block().num_hash();
1550
1551        assert_eq!(
1552            sparse_trie_prune_target::<EthPrimitives>(old_anchor, true, parent, Some(&[])),
1553            Some((TrieNodeEpoch::new(4), parent.hash))
1554        );
1555    }
1556
1557    fn create_mock_state_updates(
1558        num_accounts: usize,
1559        updates_per_account: usize,
1560    ) -> Vec<StateUpdate> {
1561        let mut rng = generators::rng();
1562        let all_addresses: Vec<Address> = (0..num_accounts).map(|_| rng.random()).collect();
1563        let mut updates = Vec::with_capacity(updates_per_account);
1564
1565        for _ in 0..updates_per_account {
1566            let num_accounts_in_update = rng.random_range(1..=num_accounts);
1567            let mut state_update = StateUpdate::default();
1568
1569            for &address in &all_addresses[0..num_accounts_in_update] {
1570                let mut storage = HashMap::<_, _>::default();
1571                if rng.random_bool(0.7) {
1572                    for _ in 0..rng.random_range(1..10) {
1573                        let slot = U256::from(rng.random::<u64>());
1574                        storage.insert(
1575                            slot,
1576                            StorageSlot::new_changed(U256::ZERO, U256::from(rng.random::<u64>())),
1577                        );
1578                    }
1579                }
1580
1581                let info = AccountInfo {
1582                    balance: U256::from(rng.random::<u64>()),
1583                    nonce: rng.random::<u64>(),
1584                    code_hash: KECCAK_EMPTY,
1585                    code: Some(Default::default()),
1586                    ..Default::default()
1587                };
1588                state_update.accounts.push(AccountUpdate {
1589                    address,
1590                    original: Some(AccountInfo::default()),
1591                    current: Some(info),
1592                    created: false,
1593                    wiped: false,
1594                    storage: storage.into_iter().collect(),
1595                });
1596            }
1597
1598            updates.push(state_update);
1599        }
1600
1601        updates
1602    }
1603
1604    #[reth_concurrency::test]
1605    fn payload_builder_trie_matches_serial_root_and_can_be_reused() {
1606        reth_tracing::init_test_tracing();
1607
1608        let factory = create_test_provider_factory_with_chain_spec(Arc::new(ChainSpec::default()));
1609        let genesis_hash = init_genesis(&factory).unwrap();
1610        let state_updates = create_mock_state_updates(10, 10);
1611        let mut accumulated_state: HashMap<Address, (Account, HashMap<B256, U256>)> =
1612            HashMap::default();
1613
1614        {
1615            let provider_rw = factory.provider_rw().expect("failed to get provider");
1616            for update in &state_updates {
1617                let account_updates = update.accounts.iter().map(|account| {
1618                    (
1619                        account.address,
1620                        account.current.as_ref().map(reth_primitives_traits::Account::from),
1621                    )
1622                });
1623                provider_rw
1624                    .insert_account_for_hashing(account_updates)
1625                    .expect("failed to insert accounts");
1626
1627                let storage_updates = update.accounts.iter().map(|account| {
1628                    let storage_entries = account.storage.iter().map(|(slot, value)| {
1629                        StorageEntry { key: B256::from(*slot), value: value.present_value }
1630                    });
1631                    (account.address, storage_entries)
1632                });
1633                provider_rw
1634                    .insert_storage_for_hashing(storage_updates)
1635                    .expect("failed to insert storage");
1636            }
1637            provider_rw.commit().expect("failed to commit changes");
1638        }
1639
1640        for update in &state_updates {
1641            for account in &update.accounts {
1642                let storage: HashMap<B256, U256> = account
1643                    .storage
1644                    .iter()
1645                    .map(|(key, value)| (B256::from(*key), value.present_value))
1646                    .collect();
1647                let entry = accumulated_state.entry(account.address).or_default();
1648                entry.0 = reth_primitives_traits::Account::from(account.current.as_ref().unwrap());
1649                entry.1.extend(storage);
1650            }
1651        }
1652
1653        let provider_factory = BlockchainProvider::new(factory).unwrap();
1654        let runtime = reth_tasks::Runtime::test();
1655        let overlay_manager = OverlayManager::<EthPrimitives>::default();
1656        let config = TreeConfig::default()
1657            .with_has_enough_parallelism(true)
1658            .with_share_sparse_trie_with_payload_builder(true);
1659        let mut state = EngineApiTreeState::new(
1660            10,
1661            10,
1662            config.invalid_header_hit_eviction_threshold(),
1663            alloy_eips::BlockNumHash::new(0, genesis_hash),
1664            overlay_manager.clone(),
1665        );
1666        let mut root_from_regular = state_root(accumulated_state.clone());
1667        let mut preserved: Option<PreservedSparseTrie> = None;
1668        for (number, (reuse, return_payload, matching_root)) in [
1669            (false, false, true),
1670            (false, true, false),
1671            (false, true, true),
1672            (true, true, true),
1673            (true, false, true),
1674        ]
1675        .into_iter()
1676        .enumerate()
1677        {
1678            assert_eq!(preserved.is_some(), reuse);
1679            let parent_hash =
1680                preserved.as_ref().map_or(genesis_hash, PreservedSparseTrie::block_hash);
1681            let block_hash = B256::with_last_byte(number as u8 + 1);
1682            if let Some(preserved) = preserved.take() {
1683                overlay_manager.store_sparse_trie(preserved);
1684            }
1685            let parent_header = alloy_consensus::Header {
1686                number: number as u64,
1687                state_root: if reuse { root_from_regular } else { B256::ZERO },
1688                ..Default::default()
1689            };
1690            let mut state_root_handle = <DefaultStateRootStrategy as StateRootStrategy<
1691                EthPrimitives,
1692                _,
1693                EthEvmConfig,
1694            >>::prepare_payload_builder(
1695                &DefaultStateRootStrategy::default(),
1696                PayloadStateRootJobContext::new(
1697                    &runtime,
1698                    &overlay_manager,
1699                    parent_hash,
1700                    &parent_header,
1701                    1,
1702                    &mut state,
1703                    OverlayStateProviderFactory::new(
1704                        provider_factory.clone(),
1705                        overlay_manager.overlay_builder(genesis_hash),
1706                    ),
1707                    &config,
1708                ),
1709            )
1710            .unwrap()
1711            .unwrap();
1712            let on_payload_built = state_root_handle.take_on_payload_built().unwrap();
1713            let mut state_hook = state_root_handle.take_state_hook();
1714            if reuse {
1715                let mut update = state_updates.last().unwrap().clone();
1716                for account in &mut update.accounts {
1717                    let info = account.current.as_mut().unwrap();
1718                    info.nonce += number as u64;
1719                    accumulated_state.get_mut(&account.address).unwrap().0 =
1720                        reth_primitives_traits::Account::from(&*info);
1721                }
1722                state_hook.on_state(update);
1723                root_from_regular = state_root(accumulated_state.clone());
1724            } else {
1725                for update in &state_updates {
1726                    state_hook.on_state(update.clone());
1727                }
1728            }
1729            drop(state_hook);
1730
1731            let root_from_task = state_root_handle.state_root().expect("task failed").state_root;
1732            assert_eq!(root_from_task, root_from_regular);
1733            assert!(overlay_manager.take_sparse_trie().is_none());
1734            drop(state_root_handle);
1735            if return_payload {
1736                on_payload_built(
1737                    block_hash,
1738                    if matching_root { root_from_task } else { B256::ZERO },
1739                );
1740            } else {
1741                drop(on_payload_built);
1742            }
1743            preserved = overlay_manager.take_sparse_trie();
1744            assert_eq!(preserved.is_some(), return_payload && matching_root);
1745            if let Some(preserved) = &preserved {
1746                assert_eq!(preserved.block_hash(), block_hash);
1747                assert_eq!(preserved.anchor_hash(), genesis_hash);
1748            }
1749        }
1750        for name in ["sparse-trie", "trie-hashing", "storage-workers", "account-workers", "drop"] {
1751            runtime.spawn_blocking_named(name, || {}).get();
1752        }
1753    }
1754}