Skip to main content

reth_engine_tree/tree/
payload_validator.rs

1//! Types and traits for validating blocks and payloads.
2//!
3//! # Payload validation flow
4//!
5//! [`BasicEngineValidator::validate_block_with_state`] is the engine-side entry point for an
6//! inserted block or an `engine_newPayload` payload. It overlaps payload conversion, transaction
7//! preparation, cache prewarming, receipt-root computation, state-root computation, and deferred
8//! trie input construction wherever those tasks do not depend on each other.
9//!
10//! ## Validation phases
11//!
12//! 1. Fetch the parent header and spawn `payload-convert`, which converts payloads into sealed
13//!    blocks and runs header, parent-header, and pre-execution consensus validation.
14//! 2. Build the parent state provider, EVM environment, transaction iterator, lazy ancestor
15//!    overlay, and optional decoded EIP-7928 block access list (BAL).
16//! 3. Prepare the per-block state-root job. The default strategy picks a skipped, synchronous, or
17//!    sparse-trie job from [`TreeConfig`].
18//! 4. Spawn the payload processor. This always prepares transaction conversion and prewarming; a
19//!    streaming state-root job can provide a sink for prewarm and execution updates.
20//! 5. Execute the block. BAL payloads use the parallel BAL execute path only when state caching and
21//!    BAL parallel execution are enabled. Otherwise the regular executor still builds and validates
22//!    the BAL before post-execution consensus uses the decoded BAL hash.
23//! 6. Stop prewarming, terminate execution caching, spawn `hash-post-state`, await
24//!    `payload-convert` and `receipt-root`, then run post-execution consensus validation.
25//! 7. Resolve the state root by finishing the prepared job. The sparse-trie job falls back to
26//!    serial computation when the state-root task fails to produce a usable root.
27//! 8. Verify the header state root, spawn deferred trie input computation, and return the executed
28//!    block without waiting for that deferred trie task on the hot path.
29//!
30//! ## Spawned background work
31//!
32//! | Work | Spawned when | Role | Completion point |
33//! | --- | --- | --- | --- |
34//! | `payload-convert` | parent is known | convert payloads, validate header and body roots | after execution, unless the gas sanity check awaits it earlier |
35//! | `tx-iterator` | payload processor setup | convert transactions, using rayon for larger blocks | consumed by regular and BAL execution |
36//! | `prewarm` | payload processor setup | warm execution caches; in BAL mode, stream BAL-derived trie targets | stopped after execution, then caching is terminated |
37//! | proof workers | sparse-trie task setup | fetch trie proofs for sparse trie updates | consumed by the sparse trie task |
38//! | `sparse-trie` | sparse-trie task setup | apply execution or BAL updates and compute the state root | awaited by the state-root job |
39//! | `receipt-root` | execution start | compute receipt root and logs bloom incrementally | awaited before post-execution consensus |
40//! | `hash-post-state` | after execution | hash changed accounts and storage from `BundleState` | awaited by post-execution validation and root computation |
41//! | `serial-root` | sparse trie timeout fallback | race serial state-root computation against the sparse trie task | polled by the sparse-trie job |
42//! | deferred trie task | after root verification | sort trie data | not awaited by the validation hot path |
43//!
44//! ```mermaid
45//! sequenceDiagram
46//!     autonumber
47//!     participant Main as validate_block_with_state
48//!     participant Convert as payload-convert
49//!     participant Tx as tx-iterator
50//!     participant Prewarm as prewarm
51//!     participant Exec as EVM execution
52//!     participant Receipt as receipt-root
53//!     participant Trie as sparse trie and proofs
54//!     participant Hash as hash-post-state
55//!     participant Deferred as deferred trie task
56//!
57//!     Main->>Convert: spawn convert and pre-execution validation
58//!     Main->>Main: parent provider, EVM env, optional BAL decode
59//!     Main->>Tx: spawn transaction conversion
60//!     alt sparse-trie job
61//!         Main->>Trie: spawn proof workers and sparse trie
62//!     end
63//!     Main->>Prewarm: spawn transaction, BAL, or skipped prewarm
64//!     Main->>Receipt: spawn receipt root task
65//!     alt BAL path eligible
66//!         Main->>Exec: execute_block_bal
67//!         Prewarm->>Trie: BAL-derived sparse trie updates
68//!     else regular execution
69//!         Tx-->>Exec: recovered transactions in block order
70//!         Main->>Exec: execute_block
71//!         Exec->>Receipt: stream receipts
72//!         Exec->>Trie: stream state hook updates
73//!         Exec->>Exec: rebuild and validate BAL when present
74//!     end
75//!     Main->>Prewarm: stop prewarming and terminate cache
76//!     Main->>Hash: spawn changed-state hashing
77//!     Convert-->>Main: sealed block
78//!     Receipt-->>Main: receipt root and logs bloom
79//!     Main->>Main: post-execution consensus and BAL hash check
80//!     Hash-->>Main: hashed post state
81//!     alt sparse-trie job
82//!         Trie-->>Main: state root and trie updates
83//!     else synchronous or fallback
84//!         Main->>Main: compute serial StateRoot
85//!     end
86//!     Main->>Main: verify header state root
87//!     Main->>Deferred: spawn trie input sorting
88//!     Main-->>Main: return ValidationOutput
89//! ```
90//!
91//! ## Payload attributes validation
92//!
93//! During `engine_forkchoiceUpdated`,
94//! [`PayloadValidator::validate_payload_attributes_against_header`] checks payload attributes
95//! before a payload build job starts. On failure, the engine returns
96//! `INVALID_PAYLOAD_ATTRIBUTES` without rolling back the forkchoice update.
97
98use crate::tree::{
99    error::{
100        BlockAccessListDecodeError, InsertBlockError, InsertBlockErrorKind, InsertPayloadError,
101    },
102    instrumented_state::{InstrumentedStateProvider, StateProviderMetrics, StateProviderStats},
103    metrics::PrewarmReuseStats,
104    payload_processor::{
105        reuse::{PrewarmResults, ReuseMiss},
106        PayloadProcessor,
107    },
108    txpool_prewarm,
109    types::{InsertPayloadResult, ValidationOutput},
110    CacheWaitDurations, CachedStateProvider, EngineApiMetrics, EngineApiTreeState, ExecutionEnv,
111    PayloadHandle, TreeConfig, WaitForCaches,
112};
113use alloy_consensus::{transaction::Either, Transaction as _};
114use alloy_eip7928::{
115    bal::{Bal, DecodedBal},
116    BlockAccessList,
117};
118use alloy_eips::{eip1898::BlockWithParent, eip4895::Withdrawal, NumHash};
119use alloy_primitives::{map::B256Set, B256};
120use reth_concurrency::sync::{
121    channel,
122    channel::{mpsc, Sender},
123    time::FastInstant as Instant,
124};
125use reth_tasks::LazyHandle;
126
127use crate::tree::{
128    payload_processor::receipt_root_task::{IndexedReceipt, ReceiptRootTaskHandle},
129    state_root_strategy::{
130        DefaultStateRootStrategy, LazyHashedPostState, PayloadStateRootHandle,
131        PayloadStateRootJobContext, StateRootHintStream, StateRootJobContext, StateRootStrategy,
132        StateRootUpdateHook, StateRootUpdateStream,
133    },
134};
135use alloy_primitives::Address;
136use evm2::evm::{AccountInfo, Bal as EvmBal};
137use reth_chain_state::{CanonicalInMemoryState, ExecutedBlock, ExecutionTimingStats};
138use reth_concurrency::sync::atomic::{AtomicUsize, Ordering};
139use reth_consensus::{ConsensusError, FullConsensus, ReceiptRootBloom};
140use reth_engine_primitives::{
141    ConfigureEngineEvm, ExecutableTxIterator, ExecutionPayload, InvalidBlockHook, PayloadValidator,
142};
143use reth_errors::{BlockExecutionError, BlockValidationError, ProviderResult};
144use reth_evm::{
145    database::StateProviderDatabase, precompile_cache::PrecompileCacheMap, BlockExecutor,
146    BlockExecutorFactory, BlockExecutorFor, BlockTransactionResult, ConfigureEvm, Evm as _,
147    EvmEnvFor, EvmTypesFor, ExecutableTxFor, ExecutionCtxFor, OnStateHook, SpecFor,
148};
149use reth_execution_cache::{CacheFillMode, CacheStats};
150use reth_execution_types::DecodedEvmBal;
151use reth_network_p2p::full_block::SealedBlockWithAccessList;
152use reth_payload_builder::{PayloadBuilderLease, PayloadBuilderResources};
153use reth_payload_primitives::{
154    BuiltPayload, BuiltPayloadExecutedBlock, InvalidPayloadAttributesError, NewPayloadError,
155    PayloadTypes,
156};
157use reth_primitives_traits::{
158    AlloyBlockHeader, BlockBody, BlockTy, GotExpected, NodePrimitives, RecoveredBlock, SealedBlock,
159    SealedHeader, SignerRecoverable, TxTy,
160};
161use reth_provider::{
162    BlockExecutionOutput, BlockReader, ChangeSetReader, DatabaseProviderFactory,
163    DatabaseProviderROFactory, EvmStateProvider, EvmStateProviderBox, HistoryReader, ProviderError,
164    PruneCheckpointReader, StageCheckpointReader, StateProvider, StateProviderFactory, StateReader,
165    StorageChangeSetReader, StorageSettingsCache,
166};
167use reth_storage_overlay::{OverlayManager, OverlayStateProviderFactory};
168use reth_trie::{updates::TrieUpdates, HashedPostState, KeccakKeyHasher, LazyTrieData};
169use reth_trie_common::bundle_state::BundleAccount;
170use std::{sync::Arc, time::Duration};
171use tracing::{debug, debug_span, error, info, instrument, trace, warn, Level, Span};
172
173pub use crate::tree::types::ValidationOutcome;
174
175/// Multiplier over the parent's gas limit beyond which a payload must pass pre-execution
176/// validation.
177const MAX_EXPECTED_GAS_LIMIT_MULTIPLIER: u64 = 2;
178
179/// Worker name for deferred trie data preparation.
180const DEFERRED_TRIE_WORKER_NAME: &str = "deferred-trie";
181
182type ReceiptRootSender<N> = Sender<IndexedReceipt<<N as NodePrimitives>::Receipt>>;
183type ReceiptRootReceiver = tokio::sync::oneshot::Receiver<(B256, alloy_primitives::Bloom)>;
184
185/// Context providing access to tree state during validation.
186///
187/// This context is provided to the [`EngineValidator`] and includes the state of the tree's
188/// internals
189pub struct TreeCtx<'a, N: NodePrimitives> {
190    /// The engine API tree state
191    state: &'a mut EngineApiTreeState<N>,
192    /// Reference to the canonical in-memory state
193    canonical_in_memory_state: &'a CanonicalInMemoryState<N>,
194}
195
196impl<'a, N: NodePrimitives> std::fmt::Debug for TreeCtx<'a, N> {
197    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
198        f.debug_struct("TreeCtx")
199            .field("state", &"EngineApiTreeState")
200            .field("canonical_in_memory_state", &self.canonical_in_memory_state)
201            .finish()
202    }
203}
204
205impl<'a, N: NodePrimitives> TreeCtx<'a, N> {
206    /// Creates a new tree context
207    pub const fn new(
208        state: &'a mut EngineApiTreeState<N>,
209        canonical_in_memory_state: &'a CanonicalInMemoryState<N>,
210    ) -> Self {
211        Self { state, canonical_in_memory_state }
212    }
213}
214
215impl<'a, N: NodePrimitives> TreeCtx<'a, N> {
216    /// Returns a reference to the engine tree state
217    pub const fn state(&self) -> &EngineApiTreeState<N> {
218        &*self.state
219    }
220
221    /// Returns a mutable reference to the engine tree state
222    pub const fn state_mut(&mut self) -> &mut EngineApiTreeState<N> {
223        self.state
224    }
225
226    /// Returns a reference to the canonical in-memory state
227    pub const fn canonical_in_memory_state(&self) -> &'a CanonicalInMemoryState<N> {
228        self.canonical_in_memory_state
229    }
230}
231
232/// Pauses JIT helper execution while validating imported payloads.
233///
234/// Validation still queues JIT work and can use resident compiled code, but helper execution is
235/// paused during validation to minimize latency. Queued work resumes when validation exits, so JIT
236/// compilation is biased toward idle periods instead of competing with payload validation.
237struct JitPauseGuard<Evm: ConfigureEvm>(Evm);
238
239impl<Evm: ConfigureEvm> JitPauseGuard<Evm> {
240    fn new(evm_config: &Evm) -> Self {
241        if let Some(jit_backend) = evm_config.jit_backend() {
242            jit_backend.pause();
243        }
244        Self(evm_config.clone())
245    }
246}
247
248impl<Evm: ConfigureEvm> Drop for JitPauseGuard<Evm> {
249    fn drop(&mut self) {
250        if let Some(jit_backend) = self.0.jit_backend() {
251            jit_backend.resume();
252        }
253    }
254}
255
256/// A helper type that provides reusable payload validation logic for network-specific validators.
257///
258/// This type satisfies [`EngineValidator`] and is responsible for executing blocks/payloads.
259///
260/// This type contains common validation, execution, and state root computation logic that can be
261/// used by network-specific payload validators (e.g., Ethereum, Optimism). It is not meant to be
262/// used as a standalone component, but rather as a building block for concrete implementations.
263#[derive(derive_more::Debug)]
264pub struct BasicEngineValidator<P, Evm, V>
265where
266    Evm: ConfigureEvm,
267{
268    /// Provider for database access.
269    provider: P,
270    /// Consensus implementation for validation.
271    consensus: Arc<dyn FullConsensus<Evm::Primitives>>,
272    /// EVM configuration.
273    evm_config: Evm,
274    /// Configuration for the tree.
275    config: TreeConfig,
276    /// Payload processor for transaction conversion, prewarming, and execution caching.
277    payload_processor: PayloadProcessor<Evm>,
278    /// Precompile cache map, shared with the payload processor's prewarm EVMs.
279    precompile_cache_map: PrecompileCacheMap<SpecFor<Evm>>,
280    /// Hook to call when invalid blocks are encountered.
281    #[debug(skip)]
282    invalid_block_hook: Box<dyn InvalidBlockHook<Evm::Primitives>>,
283    /// Metrics for the engine api.
284    metrics: EngineApiMetrics,
285    /// Validator for the payload.
286    validator: V,
287    /// Task runtime for spawning parallel work.
288    runtime: reth_tasks::Runtime,
289    /// Shared overlay manager.
290    overlay_manager: OverlayManager<Evm::Primitives>,
291    /// State-root strategy used to prepare per-block commitment tasks.
292    #[debug(skip)]
293    state_root_strategy: Arc<dyn StateRootStrategy<Evm::Primitives, P, Evm>>,
294    /// Persistent txpool prewarming worker and its latest immutable snapshot.
295    ///
296    /// None if txpool prewarming is disabled.
297    #[debug(skip)]
298    txpool_prewarm: Option<txpool_prewarm::Handle<Evm::Primitives, P, Evm>>,
299    /// Scratch buffer reused for BAL hash encoding across validated blocks.
300    bal_hash_buf: Vec<u8>,
301}
302
303impl<N, P, Evm, V> BasicEngineValidator<P, Evm, V>
304where
305    N: NodePrimitives,
306    P: DatabaseProviderFactory<
307            Provider: BlockReader
308                          + StageCheckpointReader
309                          + PruneCheckpointReader
310                          + ChangeSetReader
311                          + StorageChangeSetReader
312                          + StorageSettingsCache
313                          + HistoryReader
314                          + 'static,
315        > + BlockReader<Header = N::BlockHeader>
316        + ChangeSetReader
317        + StateProviderFactory
318        + StateReader
319        + Clone
320        + 'static,
321    Evm: ConfigureEvm<Primitives = N> + 'static,
322{
323    /// Creates a new `TreePayloadValidator`.
324    #[expect(clippy::too_many_arguments)]
325    pub fn new(
326        provider: P,
327        consensus: Arc<dyn FullConsensus<N>>,
328        evm_config: Evm,
329        validator: V,
330        config: TreeConfig,
331        invalid_block_hook: Box<dyn InvalidBlockHook<N>>,
332        overlay_manager: OverlayManager<N>,
333        runtime: reth_tasks::Runtime,
334    ) -> Self {
335        let precompile_cache_map = PrecompileCacheMap::default();
336        let payload_processor = PayloadProcessor::new(
337            runtime.clone(),
338            evm_config.clone(),
339            &config,
340            precompile_cache_map.clone(),
341        );
342        Self {
343            provider,
344            consensus,
345            evm_config,
346            payload_processor,
347            precompile_cache_map,
348            config,
349            invalid_block_hook,
350            metrics: EngineApiMetrics::default(),
351            validator,
352            runtime,
353            overlay_manager,
354            state_root_strategy: Arc::new(DefaultStateRootStrategy::default()),
355            txpool_prewarm: None,
356            bal_hash_buf: Vec::new(),
357        }
358    }
359
360    /// Sets the state-root strategy used by payload validation.
361    pub fn with_state_root_strategy(
362        mut self,
363        state_root_strategy: Arc<dyn StateRootStrategy<N, P, Evm>>,
364    ) -> Self {
365        self.state_root_strategy = state_root_strategy;
366        self
367    }
368
369    /// Installs the txpool source and starts the persistent cache-prewarming worker.
370    pub fn with_txpool_prewarming(
371        mut self,
372        source: impl crate::tree::TxPoolPrewarmSource<N> + 'static,
373    ) -> Self {
374        self.txpool_prewarm = Some(txpool_prewarm::Handle::spawn(
375            &self.runtime,
376            Arc::new(source),
377            self.evm_config.clone(),
378            self.evm_config.reuses_prewarm_results() && self.config.prewarm_reuse(),
379        ));
380        self
381    }
382
383    /// Converts a [`BlockOrPayload`] to a recovered block.
384    #[instrument(level = "debug", target = "engine::tree::payload_validator", skip_all)]
385    pub fn convert_to_block<T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>>(
386        &self,
387        input: BlockOrPayload<T>,
388    ) -> Result<SealedBlock<N::Block>, NewPayloadError>
389    where
390        V: PayloadValidator<T, Block = N::Block>,
391    {
392        match input {
393            BlockOrPayload::Payload(payload) => {
394                self.validator.convert_payload_to_block(payload).map(Arc::unwrap_or_clone)
395            }
396            BlockOrPayload::Block(block) => Ok(block.split().0),
397        }
398    }
399
400    /// Returns EVM environment for the given payload or block.
401    pub fn evm_env_for<T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>>(
402        &self,
403        input: &BlockOrPayload<T>,
404    ) -> Result<EvmEnvFor<Evm>, Evm::Error>
405    where
406        V: PayloadValidator<T, Block = N::Block>,
407        Evm: ConfigureEngineEvm<T::ExecutionData, Primitives = N>,
408    {
409        match input {
410            BlockOrPayload::Payload(payload) => Ok(self.evm_config.evm_env_for_payload(payload)?),
411            BlockOrPayload::Block(block) => Ok(self.evm_config.evm_env(block.header())?),
412        }
413    }
414
415    /// Returns [`ExecutableTxIterator`] for the given payload or block.
416    pub fn tx_iterator_for<'a, T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>>(
417        &'a self,
418        input: &'a BlockOrPayload<T>,
419    ) -> Result<impl ExecutableTxIterator<Evm>, NewPayloadError>
420    where
421        V: PayloadValidator<T, Block = N::Block>,
422        Evm: ConfigureEngineEvm<T::ExecutionData, Primitives = N>,
423    {
424        Ok(match input {
425            BlockOrPayload::Payload(payload) => {
426                let iter = self
427                    .evm_config
428                    .tx_iterator_for_payload(payload)
429                    .map_err(NewPayloadError::other)?;
430                Either::Left(iter)
431            }
432            BlockOrPayload::Block(block) => {
433                let txs = block.body().clone_transactions();
434                let convert = |tx: N::SignedTx| tx.try_into_recovered();
435                Either::Right((txs, convert))
436            }
437        })
438    }
439
440    /// Returns a [`ExecutionCtxFor`] for the given payload or block.
441    pub fn execution_ctx_for<'a, T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>>(
442        &self,
443        input: &'a BlockOrPayload<T>,
444    ) -> Result<ExecutionCtxFor<'a, Evm>, Evm::Error>
445    where
446        V: PayloadValidator<T, Block = N::Block>,
447        Evm: ConfigureEngineEvm<T::ExecutionData, Primitives = N>,
448    {
449        match input {
450            BlockOrPayload::Payload(payload) => Ok(self.evm_config.context_for_payload(payload)?),
451            BlockOrPayload::Block(block) => Ok(self.evm_config.context_for_block(block)?),
452        }
453    }
454
455    /// Validates a block that has already been converted from a payload.
456    ///
457    /// This method performs:
458    /// - Consensus validation
459    /// - Block execution
460    /// - State root computation
461    /// - Fork detection
462    #[instrument(
463        level = "debug",
464        target = "engine::tree::payload_validator",
465        skip_all,
466        fields(
467            parent = ?input.parent_hash(),
468            type_name = ?input.type_name(),
469        )
470    )]
471    pub fn validate_block_with_state<T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>>(
472        &mut self,
473        input: BlockOrPayload<T>,
474        mut ctx: TreeCtx<'_, N>,
475    ) -> InsertPayloadResult<N>
476    where
477        V: PayloadValidator<T, Block = N::Block> + Clone,
478        Evm: ConfigureEngineEvm<T::ExecutionData, Primitives = N>,
479    {
480        let parent_hash = input.parent_hash();
481        let _txpool_pause = self.txpool_prewarm.as_ref().map(txpool_prewarm::Handle::pause);
482        let txpool_snapshot =
483            self.txpool_prewarm.as_ref().and_then(|prewarmer| prewarmer.snapshot(parent_hash));
484        let _jit_pause = JitPauseGuard::new(&self.evm_config);
485
486        // Fetch parent block. This goes to memory most of the time unless the parent block is
487        // beyond the in-memory buffer.
488        let parent_block = match self.sealed_header_by_hash(parent_hash, ctx.state()) {
489            Ok(Some(parent_block)) => parent_block,
490            Ok(None) => {
491                return Err(InsertBlockError::new(
492                    self.convert_to_block(input)?,
493                    ProviderError::HeaderNotFound(parent_hash.into()).into(),
494                )
495                .into())
496            }
497            Err(e) => {
498                return Err(InsertBlockError::new(self.convert_to_block(input)?, e.into()).into())
499            }
500        };
501
502        // Spawn payload conversion and basic validation on a background thread so it runs
503        // concurrently with the rest of the function (setup + execution). For payloads this
504        // overlaps the cost of RLP decoding + header hashing.
505        let validated_block = self.spawn_convert_and_validate(&input, parent_block.clone());
506
507        /// A helper macro that returns the block in case there was an error
508        /// This macro is used for early returns before block conversion
509        macro_rules! ensure_ok {
510            ($expr:expr) => {
511                match $expr {
512                    Ok(val) => val,
513                    Err(e) => {
514                        let block = validated_block.try_into_inner().expect("sole handle")?;
515                        return Err(
516                            InsertBlockError::new(Arc::unwrap_or_clone(block), e.into()).into()
517                        )
518                    }
519                }
520            };
521        }
522
523        /// A helper macro for handling errors after the input has been converted to a block
524        macro_rules! ensure_ok_post_block {
525            ($expr:expr, $block:expr) => {
526                match $expr {
527                    Ok(val) => val,
528                    Err(e) => {
529                        return Err(
530                            InsertBlockError::new($block.into_sealed_block(), e.into()).into()
531                        )
532                    }
533                }
534            };
535        }
536
537        // If the gas limit is multiple times higher than the parent's, be cautious and block on
538        // pre-execution checks of the block.
539        if input.gas_limit() >
540            parent_block.gas_limit().saturating_mul(MAX_EXPECTED_GAS_LIMIT_MULTIPLIER)
541        {
542            // Call `.get()` to await the pre-execution checks and exit early if they fail.
543            if validated_block.get().is_err() {
544                return Err(validated_block
545                    .try_into_inner()
546                    .expect("sole handle")
547                    .expect_err("Err result checked"))
548            }
549        }
550
551        trace!(target: "engine::tree::payload_validator", "Fetching block state provider");
552        let _enter =
553            debug_span!(target: "engine::tree::payload_validator", "state_provider").entered();
554        let Some(state_provider_factory) =
555            ensure_ok!(self.overlay_state_provider_factory(parent_hash, ctx.state()))
556        else {
557            // this is pre-validated in the tree
558            return Err(InsertBlockError::new(
559                Arc::unwrap_or_clone(validated_block.try_into_inner().expect("sole handle")?),
560                ProviderError::HeaderNotFound(parent_hash.into()).into(),
561            )
562            .into())
563        };
564        drop(_enter);
565
566        let evm_env = debug_span!(target: "engine::tree::payload_validator", "evm_env")
567            .in_scope(|| self.evm_env_for(&input))
568            .map_err(NewPayloadError::other)?;
569        let pool_seeds = self
570            .txpool_prewarm
571            .as_ref()
572            .and_then(|prewarmer| prewarmer.seeds(parent_hash, &evm_env));
573
574        // Extract the decoded BAL, if present. Undecodable block access list bytes invalidate the
575        // payload.
576        let decoded_bal =
577            ensure_ok!(input.try_decoded_access_list().map_err(BlockAccessListDecodeError::new))
578                .map(Arc::new);
579
580        if let Some(decoded_bal) = decoded_bal.as_deref() {
581            // Reject oversized BAL sidecars before executing the block.
582            ensure_ok!(decoded_bal
583                .as_bal()
584                .validate_gas_limit(input.gas_limit())
585                .map_err(ConsensusError::from));
586        }
587
588        let env = ExecutionEnv {
589            evm_env,
590            hash: input.hash(),
591            parent_hash: input.parent_hash(),
592            parent_state_root: parent_block.state_root(),
593            transaction_count: input.transaction_count(),
594            gas_used: input.gas_used(),
595            withdrawals: input.withdrawals().map(|w| w.to_vec()),
596            decoded_bal: decoded_bal.as_ref().map(Arc::clone),
597            txpool_snapshot: txpool_snapshot.clone(),
598            pool_seeds,
599        };
600
601        // Get an iterator over the transactions in the payload
602        let txs = self.tx_iterator_for(&input)?;
603
604        let sequential_reason = ensure_ok!(self.bal_path_eligible(env.decoded_bal.as_deref()));
605        let parallel_bal_execution = sequential_reason.is_none();
606
607        // Prepare the state-root job before execution so it can provide streaming hooks.
608        let mut state_root_job =
609            ensure_ok!(self.state_root_strategy.prepare(StateRootJobContext::new(
610                &self.runtime,
611                &self.overlay_manager,
612                &env,
613                &parent_block,
614                state_provider_factory.clone(),
615                &self.config,
616                parallel_bal_execution,
617                ctx.state_mut(),
618            )));
619        let state_root_job_name = state_root_job.name();
620
621        debug!(
622            target: "engine::tree::payload_validator",
623            strategy = state_root_job_name,
624            "Prepared state root job"
625        );
626
627        // The hook exists only when `prepare` installed it (serial path); on the parallel BAL
628        // path the authoritative capability went to the hashed update stream instead.
629        let execution_state_hook = state_root_job.take_execution_hook();
630        // The prewarm capabilities go to the code that produces their messages and are not
631        // retained anywhere else, so the task's update channel closes when producers finish.
632        let hint_stream = state_root_job.take_hint_stream();
633        let hashed_update_stream = state_root_job.take_hashed_update_stream();
634
635        // Spawn transaction conversion and prewarming.
636        let mut handle = ensure_ok!(self.spawn_payload_processor(
637            env.clone(),
638            txs,
639            state_provider_factory.clone(),
640            hint_stream,
641            hashed_update_stream,
642            parallel_bal_execution,
643        ));
644
645        // Create optional cache stats for detailed block logging
646        let slow_block_enabled = self.config.slow_block_threshold().is_some();
647        let cache_stats = slow_block_enabled.then(|| Arc::new(CacheStats::default()));
648        let instrument_state_provider = slow_block_enabled || self.config.state_provider_metrics();
649        let state_provider_metrics =
650            instrument_state_provider.then(|| StateProviderMetrics::with_source("engine"));
651        let state_provider_stats =
652            instrument_state_provider.then(|| Arc::new(StateProviderStats::default()));
653        let execution_cache = handle.caches().map(|caches| (caches, handle.cache_metrics()));
654
655        // This state provider factory is parametrized by:
656        //
657        // 1. fill_on_miss?
658        // 2. instrument_state_provider?
659        //
660        // `fill_on_miss` controls whether the loaded value after a cache miss will be inserted
661        // back into the cache. On a glance it seems to be always useful to do this. However,
662        // in practice, for the serial/non-BAL execution, it's not needed and is net negative:
663        //
664        // - It's not necessary because the revm machinery provides layer of caching itself. That
665        //   means a value for a miss will be recorded in revm's cache.
666        // - Inserting back into the cache is not free.
667        // - After execution, the execution post-state will be dumped into the execution cache as
668        //   whole anyway.
669        //
670        // Therefore, there `fill_on_miss` is going to be false for those paths.
671        //
672        // The second parameter `instrument_state_provider` controls whether we should
673        // instrument the state provider with metrics.
674        let make_state_provider = |fill_on_miss: bool| -> ProviderResult<EvmStateProviderBox> {
675            let provider = state_provider_factory.database_provider_ro()?.into_evm_state_provider();
676            let provider: EvmStateProviderBox =
677                if let Some((caches, cache_metrics)) = &execution_cache {
678                    let fill_mode = if fill_on_miss {
679                        CacheFillMode::FillOnMiss
680                    } else {
681                        CacheFillMode::LookupOnly
682                    };
683                    Box::new(
684                        CachedStateProvider::new_with_mode(
685                            provider,
686                            caches.clone(),
687                            fill_mode,
688                            cache_metrics.clone(),
689                            cache_stats.clone(),
690                        )
691                        .with_txpool_snapshot(txpool_snapshot.clone()),
692                    )
693                } else {
694                    Box::new(provider)
695                };
696
697            let provider: EvmStateProviderBox = if instrument_state_provider {
698                let stats = state_provider_stats
699                    .as_ref()
700                    .expect("instrumented state provider requires shared stats");
701                let metrics = state_provider_metrics
702                    .as_ref()
703                    .expect("instrumented state provider requires metrics");
704                Box::new(InstrumentedStateProvider::with_stats(
705                    provider,
706                    metrics.clone(),
707                    Arc::clone(stats),
708                ))
709            } else {
710                provider
711            };
712
713            Ok(provider)
714        };
715
716        // Execute the block and handle any execution errors.
717        // The receipt root task is spawned before execution and receives receipts incrementally
718        // as transactions complete, allowing parallel computation during execution.
719        let path = if parallel_bal_execution { "parallel" } else { "sequential" };
720        let reason = sequential_reason.unwrap_or_default();
721        let NumHash { number, hash } = input.num_hash();
722        debug!(target: "engine::tree::bal_execution_path", block = number, %hash, path, reason, "Executing block");
723        let execute_block_start = Instant::now();
724        let execution_result = if parallel_bal_execution {
725            self.execute_block_bal(env, &input, &handle, &make_state_provider)
726        } else {
727            let state_provider = make_state_provider(false);
728            match state_provider {
729                Ok(state_provider) => self.execute_block(
730                    state_provider,
731                    env,
732                    &input,
733                    &mut handle,
734                    execution_state_hook,
735                ),
736                Err(err) => Err(err.into()),
737            }
738        };
739        let execution_duration = execute_block_start.elapsed();
740        if let (Some(metrics), Some(stats)) = (&state_provider_metrics, &state_provider_stats) {
741            metrics.record_totals(stats);
742        }
743        let (output, senders, receipt_root_rx, executed_bal) = ensure_ok!(execution_result);
744        let (built_bal, evm_bal) =
745            executed_bal.map(|ExecutedBal { alloy, evm }| (alloy, evm)).unzip();
746
747        // After executing the block we can stop prewarming transactions
748        handle.stop_prewarming_execution();
749
750        // Create ExecutionOutcome early so we can terminate caching before validation and state
751        // root computation. Using Arc allows sharing with both the caching task and the deferred
752        // trie task without cloning the expensive BundleState.
753        let output = Arc::new(output);
754
755        // Terminate caching task early since execution is complete and caching is no longer
756        // needed. This frees up resources while state root computation continues.
757        let valid_block_tx = handle.terminate_caching(Some(output.clone()));
758
759        // Spawn hashed post state computation in background so it runs concurrently with
760        // block conversion and receipt root computation. This is a pure CPU-bound task
761        // (keccak256 hashing of all changed addresses and storage slots).
762        let hashed_state_output = output.clone();
763        let mut hashed_state_rx = state_root_job.take_hashed_state_rx();
764        let parent_span = Span::current();
765        let mut hashed_state: LazyHashedPostState =
766            self.runtime.spawn_blocking_named("hash-post-state", move || {
767                let _span = debug_span!(
768                    target: "engine::tree::payload_validator",
769                    parent: &parent_span,
770                    "hashed_post_state",
771                )
772                .entered();
773                if let Some(Ok(state)) = hashed_state_rx.as_mut().map(|rx| rx.recv()) {
774                    state
775                } else {
776                    Arc::new(HashedPostState::from_bundle_state::<KeccakKeyHasher>(
777                        hashed_state_output.state.state(),
778                    ))
779                }
780            });
781
782        // Release the payload's handle so the block can be unwrapped instead of cloned.
783        drop(input);
784        let block = validated_block.try_into_inner().expect("sole handle")?;
785        let block = Arc::unwrap_or_clone(block).with_senders(senders);
786
787        // Wait for the receipt root computation to complete.
788        let receipt_root_bloom = {
789            let _enter = debug_span!(
790                target: "engine::tree::payload_validator",
791                "wait_receipt_root",
792            )
793            .entered();
794
795            receipt_root_rx
796                .blocking_recv()
797                .inspect_err(|_| {
798                    tracing::error!(
799                        target: "engine::tree::payload_validator",
800                        "Receipt root task dropped sender without result, receipt root calculation likely aborted"
801                    );
802                })
803                .ok()
804        };
805
806        ensure_ok_post_block!(
807            self.validate_post_execution(
808                &block,
809                &parent_block,
810                &output,
811                &mut ctx,
812                receipt_root_bloom,
813                built_bal
814            ),
815            block
816        );
817
818        let mut hashed_state_validate_result = debug_span!(
819            target: "engine::tree::payload_validator",
820            "validate_block_post_execution_with_hashed_state"
821        )
822        .in_scope(|| {
823            self.validator.validate_block_post_execution_with_hashed_state(
824                || hashed_state.get(),
825                &block,
826                &parent_block,
827                || {
828                    state_provider_factory
829                        .database_provider_ro()
830                        .map(|provider| Box::new(provider) as _)
831                },
832            )
833        });
834
835        let root_start = Instant::now();
836        let root_outcome = ensure_ok_post_block!(
837            state_root_job.finish(&block, output.clone(), &hashed_state),
838            block
839        );
840        let root_elapsed = root_start.elapsed();
841
842        info!(
843            target: "engine::tree::payload_validator",
844            strategy = state_root_job_name,
845            state_root = ?root_outcome.state_root,
846            elapsed = ?root_elapsed,
847            "State root job finished"
848        );
849
850        let state_root = root_outcome.state_root;
851        let trie_output = root_outcome.trie_updates;
852
853        // A fallback path recomputed the hashed post state. Replace the streaming-derived one
854        // and re-run hashed-state validation against it, since a failed state-root task may
855        // have produced an inconsistent byproduct.
856        if let Some(refreshed) = root_outcome.hashed_state {
857            hashed_state = LazyHandle::ready(refreshed);
858            hashed_state_validate_result = debug_span!(
859                target: "engine::tree::payload_validator",
860                "validate_block_post_execution_with_hashed_state"
861            )
862            .in_scope(|| {
863                self.validator.validate_block_post_execution_with_hashed_state(
864                    || hashed_state.get(),
865                    &block,
866                    &parent_block,
867                    || {
868                        state_provider_factory
869                            .database_provider_ro()
870                            .map(|provider| Box::new(provider) as _)
871                    },
872                )
873            });
874        }
875
876        if let Err(err) = hashed_state_validate_result {
877            if err.is_validation_error() {
878                self.on_invalid_block(&parent_block, &block, &output, None, ctx.state_mut());
879            }
880            return Err(InsertBlockError::new(block.into_sealed_block(), err).into())
881        }
882
883        self.metrics.block_validation.record_state_root(&trie_output, root_elapsed.as_secs_f64());
884        self.metrics
885            .record_state_root_gas_bucket(block.header().gas_used(), root_elapsed.as_secs_f64());
886        debug!(target: "engine::tree::payload_validator", ?root_elapsed, "Calculated state root");
887
888        // ensure state root matches
889        if state_root != block.header().state_root() {
890            // call post-block hook
891            self.on_invalid_block(
892                &parent_block,
893                &block,
894                &output,
895                Some((&trie_output, state_root)),
896                ctx.state_mut(),
897            );
898            let block_state_root = block.header().state_root();
899            return Err(InsertBlockError::new(
900                block.into_sealed_block(),
901                ConsensusError::BodyStateRootDiff(
902                    GotExpected { got: state_root, expected: block_state_root }.into(),
903                )
904                .into(),
905            )
906            .into())
907        }
908
909        let timing_stats = state_provider_stats.filter(|_| slow_block_enabled).map(|stats| {
910            self.calculate_timing_stats(
911                &block,
912                stats,
913                cache_stats,
914                &output,
915                execution_duration,
916                root_elapsed,
917            )
918        });
919
920        if let Some(valid_block_tx) = valid_block_tx {
921            let _ = valid_block_tx.send(());
922        }
923
924        // The payload's raw bytes are already bound to this header: payload-to-block conversion
925        // and downloaded-sidecar verification both check their hash against it, so pairing them
926        // with the BAL this execution produced is sound. The zip leaves the BAL unset for a
927        // downloaded block that carried only a BAL hash and no sidecar.
928        let bal = evm_bal.zip(decoded_bal).map(|(evm_bal, decoded_bal)| {
929            Arc::new(DecodedEvmBal::with_raw_bal(evm_bal, decoded_bal.as_raw_bal().clone()))
930        });
931        let executed_block = self
932            .spawn_deferred_trie_task(Arc::new(block), output, hashed_state, trie_output)
933            .with_bal(bal);
934        Ok(ValidationOutput::new(executed_block, timing_stats))
935    }
936
937    /// Spawns a background task to convert a [`BlockOrPayload`] into a [`SealedBlock`] and perform
938    /// basic consensus validations on it.
939    #[expect(clippy::type_complexity)]
940    pub fn spawn_convert_and_validate<T>(
941        &self,
942        input: &BlockOrPayload<T>,
943        parent: SealedHeader<N::BlockHeader>,
944    ) -> LazyHandle<Result<Arc<SealedBlock<N::Block>>, InsertPayloadError<N::Block>>>
945    where
946        T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>,
947        V: PayloadValidator<T, Block = N::Block> + Clone,
948    {
949        let input = input.clone();
950        let validator = self.validator.clone();
951        let consensus = self.consensus.clone();
952        let parent_span = Span::current();
953        self.runtime.spawn_blocking_named("payload-convert", move || {
954            let _span = debug_span!(
955                target: "engine::tree::payload_validator",
956                parent: &parent_span,
957                "convert_and_validate",
958            )
959            .entered();
960            let block = match input {
961                BlockOrPayload::Block(block) => Arc::new(block.split().0),
962                BlockOrPayload::Payload(payload) => {
963                    validator.convert_payload_to_block(payload)?
964                }
965            };
966
967            if let Err(e) = consensus.validate_header(block.sealed_header()) {
968                error!(target: "engine::tree::payload_validator", block = ?block.block_with_parent(), %e, "Failed to validate header");
969                return Err(InsertBlockError::consensus_error(e, Arc::unwrap_or_clone(block)).into())
970            }
971
972            // now validate against the parent
973            let _enter = debug_span!(target: "engine::tree::payload_validator", "validate_header_against_parent").entered();
974            if let Err(e) = consensus.validate_header_against_parent(block.sealed_header(), &parent)
975            {
976                warn!(target: "engine::tree::payload_validator", block = ?block.block_with_parent(), %e, "Failed to validate header against parent");
977                return Err(InsertBlockError::consensus_error(e, Arc::unwrap_or_clone(block)).into())
978            }
979            drop(_enter);
980
981            if let Err(e) =
982                consensus.validate_block_pre_execution_with_tx_root(&block, None)
983            {
984                error!(target: "engine::tree::payload_validator", block = ?block.block_with_parent(), %e, "Failed to validate block");
985                return Err(InsertBlockError::consensus_error(e, Arc::unwrap_or_clone(block)).into())
986            }
987
988            Ok(block)
989        })
990    }
991
992    /// Return sealed block header from database or in-memory state by hash.
993    fn sealed_header_by_hash(
994        &self,
995        hash: B256,
996        state: &EngineApiTreeState<N>,
997    ) -> ProviderResult<Option<SealedHeader<N::BlockHeader>>> {
998        // check memory first
999        let header = state.tree_state.sealed_header_by_hash(&hash);
1000
1001        if header.is_some() {
1002            Ok(header)
1003        } else {
1004            self.provider.sealed_header_by_hash(hash)
1005        }
1006    }
1007
1008    /// Executes a block with the given state provider.
1009    ///
1010    /// This method orchestrates block execution:
1011    /// 1. Sets up the EVM with state database and precompile caching
1012    /// 2. Spawns a background task for incremental receipt root computation
1013    /// 3. Executes transactions with metrics collection via state hooks
1014    /// 4. Merges state transitions and records execution metrics
1015    #[instrument(level = "debug", target = "engine::tree::payload_validator", skip_all)]
1016    #[expect(clippy::type_complexity)]
1017    fn execute_block<S, Err, T>(
1018        &self,
1019        state_provider: S,
1020        env: ExecutionEnv<Evm>,
1021        input: &BlockOrPayload<T>,
1022        handle: &mut PayloadHandle<impl ExecutableTxFor<Evm>, Err, N::Receipt, EvmTypesFor<Evm>>,
1023        state_hook: Option<StateRootUpdateHook>,
1024    ) -> Result<
1025        (BlockExecutionOutput<N::Receipt>, Vec<Address>, ReceiptRootReceiver, Option<ExecutedBal>),
1026        InsertBlockErrorKind,
1027    >
1028    where
1029        S: EvmStateProvider + Send,
1030        Err: core::error::Error + Send + Sync + 'static,
1031        V: PayloadValidator<T, Block = N::Block>,
1032        T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>,
1033        Evm: ConfigureEngineEvm<T::ExecutionData, Primitives = N>,
1034    {
1035        debug!(target: "engine::tree::payload_validator", "Executing block");
1036
1037        let transaction_count = input.transaction_count();
1038        let (receipt_tx, result_rx) = self.spawn_receipt_root_task(transaction_count);
1039        let executed_tx_index = Arc::clone(handle.executed_tx_index());
1040        // Reuse validation reads must not alter a block's access list.
1041        let prewarm_results = handle.prewarm_results().filter(|_| !input.has_block_access_list());
1042        let execution_start = Instant::now();
1043        let evm_config = self.evm_config.clone().with_jit_support();
1044        let execution_ctx = self.execution_ctx_for(input).map_err(BlockExecutionError::other)?;
1045
1046        let (output, senders, built_bal) = debug_span!(target: "engine::tree", "execute_block")
1047            .in_scope(|| {
1048                let db = StateProviderDatabase::new(state_provider);
1049                let evm = if self.config.precompile_cache_disabled() {
1050                    evm_config.evm_with_env(db, env.evm_env)
1051                } else {
1052                    evm_config.evm_with_precompile_cache(
1053                        db,
1054                        env.evm_env,
1055                        self.precompile_cache_map.clone(),
1056                        true,
1057                    )
1058                };
1059                let mut executor =
1060                    evm_config.block_executor_factory().create_executor(evm, execution_ctx);
1061                if input.has_block_access_list() {
1062                    executor.enable_block_access_list_builder();
1063                }
1064                if let Some(mut state_hook) = state_hook {
1065                    executor.set_state_hook(move |state| state_hook.on_state(state));
1066                }
1067                let senders = self.execute_transactions(
1068                    &mut executor,
1069                    transaction_count,
1070                    handle.iter_transactions(),
1071                    &receipt_tx,
1072                    &executed_tx_index,
1073                    prewarm_results.as_deref(),
1074                )?;
1075
1076                let post_exec_start = Instant::now();
1077                let (output, built_bal) = executor.finish_with_prepared_block_access_list()?;
1078                self.metrics.record_post_execution(post_exec_start.elapsed());
1079                Ok::<_, BlockExecutionError>((output, senders, built_bal))
1080            })?;
1081        drop(receipt_tx);
1082        // Free stale results off the execution path.
1083        if let Some(results) = prewarm_results {
1084            self.runtime.spawn_drop(results);
1085        }
1086        let built_bal =
1087            built_bal.map(|bal| ExecutedBal { alloy: (&bal).into(), evm: Arc::new(bal) });
1088
1089        let execution_duration = execution_start.elapsed();
1090        self.metrics.record_block_execution(&output, execution_duration);
1091        self.metrics.record_block_execution_gas_bucket(output.result.gas_used, execution_duration);
1092        debug!(target: "engine::tree::payload_validator", elapsed = ?execution_duration, "Executed block");
1093
1094        Ok((output, senders, result_rx, built_bal))
1095    }
1096
1097    /// Returns `None` when the BAL execute path should be used for this block, or else the first
1098    /// gate that rules it out: `no-access-list` or `disabled`.
1099    // TODO: extend with stronger gating before enabling on mainnet:
1100    //   - Fork check: `Amsterdam.active_at_timestamp(env.evm_env.timestamp)`. Today a BAL only
1101    //     exists post-Amsterdam, so the BAL-presence check is a sufficient proxy. It is a proxy,
1102    //     not a guarantee.
1103    //   - Tx-count threshold (`bal_execute_path_min_tx_count`): below the parallelism break-even
1104    //     point, provider setup and worker scheduling overhead can exceed the gain. Tune
1105    //     empirically once workers are parallel; meaningless while the commit loop is sequential.
1106    fn bal_path_eligible(
1107        &self,
1108        bal: Option<&DecodedBal>,
1109    ) -> Result<Option<&'static str>, InsertBlockErrorKind> {
1110        if bal.is_none() {
1111            return Ok(Some("no-access-list"))
1112        }
1113        if self.config.disable_bal_parallel_execution() {
1114            return Ok(Some("disabled"))
1115        }
1116        if self.config.disable_bal_parallel_state_root() {
1117            return Err(InsertBlockErrorKind::Other(
1118                "disabling parallel state root is impossible when parallel execution is enabled"
1119                    .into(),
1120            ));
1121        }
1122
1123        Ok(None)
1124    }
1125
1126    /// Executes the block on the BAL path. Mirrors the return shape of [`Self::execute_block`]
1127    /// so the dispatch site stays uniform.
1128    ///
1129    /// Inside, this:
1130    /// 1. Creates a shared parent-state cache handle for provider-backed workers.
1131    /// 2. Relies on BAL prewarm to stream state-root updates and optional state prefetches.
1132    /// 3. Spawns the receipt-root task.
1133    /// 4. Calls [`crate::tree::payload_processor::bal::execute_block`].
1134    /// 5. Returns the rebuilt BAL for post-execution consensus validation, paired with the evm2
1135    ///    representation the workers consumed.
1136    #[instrument(level = "debug", target = "engine::tree::payload_validator", skip_all)]
1137    #[expect(clippy::type_complexity)]
1138    fn execute_block_bal<Tx, Err, MakeStateProvider, T>(
1139        &self,
1140        env: ExecutionEnv<Evm>,
1141        input: &BlockOrPayload<T>,
1142        handle: &PayloadHandle<Tx, Err, N::Receipt, EvmTypesFor<Evm>>,
1143        make_state_provider: &MakeStateProvider,
1144    ) -> Result<
1145        (BlockExecutionOutput<N::Receipt>, Vec<Address>, ReceiptRootReceiver, Option<ExecutedBal>),
1146        InsertBlockErrorKind,
1147    >
1148    where
1149        Tx: ExecutableTxFor<Evm> + Send,
1150        Err: core::error::Error + Send + Sync + 'static,
1151        MakeStateProvider: Fn(bool) -> ProviderResult<EvmStateProviderBox> + Sync,
1152        Evm: ConfigureEngineEvm<T::ExecutionData, Primitives = N>,
1153        T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>,
1154        V: PayloadValidator<T, Block = N::Block>,
1155    {
1156        debug!(target: "engine::tree::payload_validator", "Executing block via BAL path");
1157
1158        let (receipt_tx, result_rx) = self.spawn_receipt_root_task(env.transaction_count);
1159        let input_bal = env.decoded_bal.ok_or_else(|| {
1160            InsertBlockErrorKind::Other("BAL execute path: no decoded BAL available".into())
1161        })?;
1162
1163        let make_db = |fill_on_miss| {
1164            let provider = make_state_provider(fill_on_miss)
1165                .map_err(crate::tree::payload_processor::bal::BalExecutionError::Provider)?;
1166            Ok(StateProviderDatabase::new(provider))
1167        };
1168        let execution_start = Instant::now();
1169        let ctx =
1170            self.execution_ctx_for(input).map_err(|e| InsertBlockErrorKind::Other(Box::new(e)))?;
1171        let (output, senders, built_bal, received_bal_evm) =
1172            crate::tree::payload_processor::bal::execute_block(
1173                &self.runtime,
1174                &self.evm_config,
1175                &make_db,
1176                input_bal,
1177                env.evm_env,
1178                ctx,
1179                env.transaction_count,
1180                handle.clone_transaction_receiver(),
1181                receipt_tx,
1182            )?;
1183        let execution_duration = execution_start.elapsed();
1184
1185        self.metrics.record_block_execution(&output, execution_duration);
1186        self.metrics.record_block_execution_gas_bucket(output.result.gas_used, execution_duration);
1187        debug!(
1188            target: "engine::tree::payload_validator",
1189            elapsed = ?execution_duration,
1190            "Executed block via BAL path",
1191        );
1192
1193        // The received BAL was already converted to the evm2 form to drive the workers. Once the
1194        // post-execution hash check against the rebuilt BAL passes, both have the same content, so
1195        // the converted one can be reused instead of converting the rebuilt BAL again.
1196        Ok((
1197            output,
1198            senders,
1199            result_rx,
1200            Some(ExecutedBal { alloy: built_bal, evm: received_bal_evm }),
1201        ))
1202    }
1203
1204    fn spawn_receipt_root_task(
1205        &self,
1206        receipts_len: usize,
1207    ) -> (ReceiptRootSender<N>, ReceiptRootReceiver) {
1208        // Unbounded channel is used since tx count bounds capacity anyway.
1209        let (receipt_tx, receipt_rx) = channel::unbounded();
1210        let (result_tx, result_rx) = tokio::sync::oneshot::channel();
1211        let task_handle = ReceiptRootTaskHandle::new(receipt_rx, result_tx);
1212        self.runtime.spawn_blocking_named("receipt-root", move || task_handle.run(receipts_len));
1213
1214        (receipt_tx, result_rx)
1215    }
1216
1217    /// Executes transactions and collects senders, streaming receipts to a background task.
1218    ///
1219    /// This method handles:
1220    /// - Applying pre-execution changes (e.g., beacon root updates)
1221    /// - Executing each transaction with timing metrics
1222    /// - Streaming receipts to the receipt root computation task
1223    /// - Collecting transaction senders for later use
1224    fn execute_transactions<Tx, Err>(
1225        &self,
1226        executor: &mut BlockExecutorFor<'_, Evm>,
1227        transaction_count: usize,
1228        transactions: impl Iterator<Item = Result<Tx, Err>>,
1229        receipt_tx: &ReceiptRootSender<N>,
1230        executed_tx_index: &AtomicUsize,
1231        prewarm_results: Option<&PrewarmResults<EvmTypesFor<Evm>>>,
1232    ) -> Result<Vec<Address>, BlockExecutionError>
1233    where
1234        Tx: ExecutableTxFor<Evm>,
1235        Err: core::error::Error + Send + Sync + 'static,
1236    {
1237        // Apply pre-execution changes (e.g., beacon root update)
1238        let pre_exec_start = Instant::now();
1239        debug_span!(target: "engine::tree", "pre_execution")
1240            .in_scope(|| executor.apply_pre_execution_changes())?;
1241        self.metrics.record_pre_execution(pre_exec_start.elapsed());
1242
1243        // Execute transactions
1244        let exec_span = debug_span!(target: "engine::tree", "execution").entered();
1245        let mut senders = Vec::with_capacity(transaction_count);
1246        let mut reuse_stats = PrewarmReuseStats::default();
1247        let mut transactions = transactions.into_iter();
1248        // Some executors may execute transactions that do not append receipts during the
1249        // main loop (e.g., system transactions whose receipts are added during finalization).
1250        // In that case, invoking the callback on every transaction would resend the previous
1251        // receipt with the same index and can panic the ordered root builder.
1252        let mut last_sent_len = 0usize;
1253        loop {
1254            // Measure time spent waiting for next transaction from iterator
1255            // (e.g., parallel signature recovery)
1256            let wait_start = Instant::now();
1257            let Some(tx_result) = transactions.next() else { break };
1258            self.metrics.record_transaction_wait(wait_start.elapsed());
1259            let tx = tx_result.map_err(BlockValidationError::other)?;
1260            senders.push(*tx.signer());
1261
1262            let _enter = tracing::enabled!(target: "engine::tree", Level::TRACE).then(|| {
1263                tracing::trace_span!(
1264                    target: "engine::tree",
1265                    "execute tx",
1266                    tx_index = senders.len() - 1,
1267                )
1268                .entered()
1269            });
1270            if tracing::enabled!(target: "engine::tree", Level::TRACE) {
1271                trace!(target: "engine::tree", "Executing transaction");
1272            }
1273
1274            let tx_start = Instant::now();
1275            let index = senders.len() - 1;
1276            match prewarm_results {
1277                Some(results) => {
1278                    let outcome = self.commit_prewarm_result(executor, results, index, tx.tx())?;
1279                    if outcome.is_err() {
1280                        // Later prewarm results are refreshed against the actual writes.
1281                        let result = executor.execute_transaction_without_commit(tx)?;
1282                        results.publish_executed(index, &result.result().pending_state);
1283                        executor.commit_transaction(result)?;
1284                    }
1285                    reuse_stats.record(outcome);
1286                }
1287                None => {
1288                    executor.execute_transaction(tx)?;
1289                }
1290            }
1291            self.metrics.record_transaction_execution(tx_start.elapsed());
1292
1293            // advance the shared counter so prewarm workers skip already-executed txs
1294            executed_tx_index.store(senders.len(), Ordering::Relaxed);
1295
1296            let current_len = executor.receipts().len();
1297            if current_len > last_sent_len {
1298                last_sent_len = current_len;
1299                // Send the latest receipt to the background task for incremental root computation.
1300                if let Some(receipt) = executor.receipts().last() {
1301                    let tx_index = current_len - 1;
1302                    receipt_tx
1303                        .send(IndexedReceipt::new(tx_index, receipt.clone()))
1304                        .map_err(|_| BlockExecutionError::msg("receipt root task closed"))?;
1305                }
1306            }
1307        }
1308
1309        drop(exec_span);
1310        if prewarm_results.is_some() {
1311            self.metrics.prewarm_reuse.record(reuse_stats);
1312        }
1313        Ok(senders)
1314    }
1315
1316    /// Commits the prewarm result of the transaction at `index` instead of executing it, if the
1317    /// result is ready and its reads match the current state.
1318    fn commit_prewarm_result(
1319        &self,
1320        executor: &mut BlockExecutorFor<'_, Evm>,
1321        results: &PrewarmResults<EvmTypesFor<Evm>>,
1322        index: usize,
1323        tx: &TxTy<N>,
1324    ) -> Result<Result<(), ReuseMiss>, BlockExecutionError> {
1325        executor.validate_transaction_gas_limit(tx.gas_limit())?;
1326        let result = match results
1327            .take_valid(index, executor.evm_mut().state_db_mut())
1328            .map_err(BlockExecutionError::other)?
1329        {
1330            Ok(result) => result,
1331            Err(miss) => return Ok(Err(miss)),
1332        };
1333        let Some(result) = self.evm_config.prewarm_tx_result(tx, result) else {
1334            return Ok(Err(ReuseMiss::Stale))
1335        };
1336        executor.commit_transaction(result)?;
1337        Ok(Ok(()))
1338    }
1339
1340    /// Validates the block after execution.
1341    ///
1342    /// This performs:
1343    /// - parent header validation
1344    /// - post-execution consensus validation
1345    /// - state-root based post-execution validation
1346    ///
1347    /// If `receipt_root_bloom` is provided, it will be used instead of computing the receipt root
1348    /// and logs bloom from the receipts.
1349    ///
1350    /// The `hashed_state` handle wraps the background hashed post state computation.
1351    #[instrument(level = "debug", target = "engine::tree::payload_validator", skip_all)]
1352    fn validate_post_execution<T: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>>(
1353        &mut self,
1354        block: &RecoveredBlock<N::Block>,
1355        parent_block: &SealedHeader<N::BlockHeader>,
1356        output: &BlockExecutionOutput<N::Receipt>,
1357        ctx: &mut TreeCtx<'_, N>,
1358        receipt_root_bloom: Option<ReceiptRootBloom>,
1359        built_bal: Option<BlockAccessList>,
1360    ) -> Result<(), InsertBlockErrorKind>
1361    where
1362        V: PayloadValidator<T, Block = N::Block>,
1363    {
1364        let start = Instant::now();
1365
1366        trace!(target: "engine::tree::payload_validator", block=?block.num_hash(), "Validating block consensus");
1367
1368        // Validate block post-execution rules
1369        let _enter =
1370            debug_span!(target: "engine::tree::payload_validator", "validate_block_post_execution")
1371                .entered();
1372        let built_bal = built_bal.map(Bal::from);
1373        let block_access_list_hash =
1374            built_bal.as_ref().map(|bal| bal.compute_hash_with_buf(&mut self.bal_hash_buf));
1375
1376        let validation_result = built_bal
1377            .as_ref()
1378            .map(|bal| bal.validate_gas_limit(block.gas_limit()).map_err(ConsensusError::from))
1379            .transpose()
1380            .and_then(|_| {
1381                self.consensus.validate_block_post_execution(
1382                    block,
1383                    output,
1384                    receipt_root_bloom,
1385                    block_access_list_hash,
1386                )
1387            });
1388
1389        if let Err(err) = validation_result {
1390            // call post-block hook
1391            self.on_invalid_block(parent_block, block, output, None, ctx.state_mut());
1392            return Err(err.into())
1393        }
1394        drop(_enter);
1395
1396        // record post-execution validation duration
1397        self.metrics
1398            .block_validation
1399            .post_execution_validation_duration
1400            .record(start.elapsed().as_secs_f64());
1401
1402        Ok(())
1403    }
1404
1405    /// Spawns transaction conversion and cache prewarming for payload validation.
1406    ///
1407    /// State-root tasks are prepared before this method and can provide capabilities that
1408    /// prewarm uses for BAL-derived authoritative updates or transaction-derived hints.
1409    #[instrument(
1410        level = "debug",
1411        target = "engine::tree::payload_validator",
1412        skip_all,
1413        fields(
1414            has_hint_stream = hint_stream.is_some(),
1415            has_hashed_update_stream = hashed_update_stream.is_some(),
1416            parallel_bal_execution
1417        )
1418    )]
1419    fn spawn_payload_processor<T: ExecutableTxIterator<Evm>>(
1420        &self,
1421        env: ExecutionEnv<Evm>,
1422        txs: T,
1423        state_provider_factory: OverlayStateProviderFactory<P, N>,
1424        hint_stream: Option<StateRootHintStream>,
1425        hashed_update_stream: Option<StateRootUpdateStream>,
1426        parallel_bal_execution: bool,
1427    ) -> Result<
1428        PayloadHandle<
1429            impl ExecutableTxFor<Evm> + use<N, P, Evm, V, T>,
1430            impl core::error::Error + Send + Sync + 'static + use<N, P, Evm, V, T>,
1431            N::Receipt,
1432            EvmTypesFor<Evm>,
1433        >,
1434        InsertBlockErrorKind,
1435    > {
1436        let start = Instant::now();
1437        let handle = self.payload_processor.spawn_with_state_root_streams(
1438            env,
1439            txs,
1440            state_provider_factory,
1441            hint_stream,
1442            hashed_update_stream,
1443            parallel_bal_execution,
1444        );
1445
1446        self.metrics.block_validation.spawn_payload_processor.record(start.elapsed().as_secs_f64());
1447
1448        Ok(handle)
1449    }
1450
1451    /// Creates an overlay state provider factory for the given parent hash.
1452    ///
1453    /// Returns `None` when the parent is neither in memory nor persisted.
1454    fn overlay_state_provider_factory(
1455        &self,
1456        hash: B256,
1457        state: &EngineApiTreeState<N>,
1458    ) -> ProviderResult<Option<OverlayStateProviderFactory<P, N>>> {
1459        if !state.tree_state.contains_hash(&hash) && self.provider.header(hash)?.is_none() {
1460            debug!(target: "engine::tree::payload_validator", %hash, "no canonical state found for block");
1461            return Ok(None)
1462        }
1463
1464        Ok(Some(OverlayStateProviderFactory::new(
1465            self.provider.clone(),
1466            state.tree_state.overlay_manager.overlay_builder(hash),
1467        )))
1468    }
1469
1470    /// Called when an invalid block is encountered during validation.
1471    fn on_invalid_block(
1472        &self,
1473        parent_header: &SealedHeader<N::BlockHeader>,
1474        block: &RecoveredBlock<N::Block>,
1475        output: &BlockExecutionOutput<N::Receipt>,
1476        trie_updates: Option<(&TrieUpdates, B256)>,
1477        state: &mut EngineApiTreeState<N>,
1478    ) {
1479        if state.invalid_headers.get(&block.hash()).is_some() {
1480            // we already marked this block as invalid
1481            return
1482        }
1483        self.invalid_block_hook.on_invalid_block(parent_header, block, output, trie_updates);
1484    }
1485
1486    /// Prepares the optional payload-builder state-root handle through the installed
1487    /// [`StateRootStrategy`].
1488    fn payload_state_root_handle_for(
1489        &self,
1490        parent_hash: B256,
1491        parent_header: &N::BlockHeader,
1492        timestamp: u64,
1493        state: &mut EngineApiTreeState<N>,
1494    ) -> Option<PayloadStateRootHandle> {
1495        let state_provider_factory = match self.overlay_state_provider_factory(parent_hash, state) {
1496            Ok(Some(state_provider_factory)) => state_provider_factory,
1497            Ok(None) => return None,
1498            Err(err) => {
1499                warn!(
1500                    target: "engine::tree::payload_validator",
1501                    %err,
1502                    %parent_hash,
1503                    "failed to prepare payload-builder state-root provider"
1504                );
1505                return None
1506            }
1507        };
1508        match self.state_root_strategy.prepare_payload_builder(PayloadStateRootJobContext::new(
1509            &self.runtime,
1510            &self.overlay_manager,
1511            parent_hash,
1512            parent_header,
1513            timestamp,
1514            state,
1515            state_provider_factory,
1516            &self.config,
1517        )) {
1518            Ok(handle) => handle,
1519            Err(err) => {
1520                warn!(
1521                    target: "engine::tree::payload_validator",
1522                    %err,
1523                    %parent_hash,
1524                    "failed to prepare payload-builder state-root job"
1525                );
1526                None
1527            }
1528        }
1529    }
1530
1531    /// Spawns a background task to compute and sort trie data for the executed block.
1532    ///
1533    /// This function creates a [`LazyTrieData`] handle and spawns a blocking task that:
1534    /// 1. Sort the block's hashed state and trie updates
1535    /// 2. Publishes the result so subsequent calls return immediately
1536    ///
1537    /// If the background task hasn't completed when `trie_data()` is called, callers wait for the
1538    /// publishing task instead of computing synchronously.
1539    ///
1540    /// The validation hot path can return immediately after state root verification,
1541    /// while consumers (DB writes, overlay providers, proofs) get trie data from the completed
1542    /// task.
1543    fn spawn_deferred_trie_task(
1544        &self,
1545        block: Arc<RecoveredBlock<N::Block>>,
1546        execution_outcome: Arc<BlockExecutionOutput<N::Receipt>>,
1547        hashed_state: LazyHashedPostState,
1548        trie_output: Arc<TrieUpdates>,
1549    ) -> ExecutedBlock<N> {
1550        // Create deferred handle and task that owns the unsorted inputs.
1551        // Resolve the lazy handle into Arc<HashedPostState>. By this point the hashed state has
1552        // already been computed and used for state root verification, so .get() returns instantly.
1553        let hashed_state = match hashed_state.try_into_inner() {
1554            Ok(state) => state,
1555            Err(handle) => handle.get().clone(),
1556        };
1557        let (deferred_trie_data, deferred_trie_task) =
1558            LazyTrieData::pending(hashed_state, trie_output);
1559        let block_validation_metrics = self.metrics.block_validation.clone();
1560
1561        // Capture block info for tracing.
1562        let block_number = block.number();
1563
1564        // Spawn background task to compute trie data.
1565        let compute_trie_input_task = move || {
1566            let _span = debug_span!(
1567                target: "engine::tree::payload_validator",
1568                "compute_trie_input_task",
1569                block_number
1570            )
1571            .entered();
1572
1573            let compute_start = Instant::now();
1574            let computed = deferred_trie_task.compute_and_publish();
1575            block_validation_metrics
1576                .deferred_trie_compute_duration
1577                .record(compute_start.elapsed().as_secs_f64());
1578
1579            // Record sizes of the computed trie data
1580            block_validation_metrics
1581                .hashed_post_state_size
1582                .record(computed.hashed_state.total_len() as f64);
1583            block_validation_metrics
1584                .trie_updates_sorted_size
1585                .record(computed.trie_updates.total_len() as f64);
1586        };
1587
1588        // Spawn task that computes trie data asynchronously.
1589        self.runtime.spawn_blocking_named(DEFERRED_TRIE_WORKER_NAME, compute_trie_input_task);
1590
1591        ExecutedBlock::with_deferred_trie_data(block, execution_outcome, deferred_trie_data)
1592    }
1593
1594    fn calculate_timing_stats(
1595        &self,
1596        block: &RecoveredBlock<N::Block>,
1597        provider_stats: Arc<StateProviderStats>,
1598        cache_stats: Option<Arc<CacheStats>>,
1599        output: &BlockExecutionOutput<N::Receipt>,
1600        execution_duration: Duration,
1601        state_hash_duration: Duration,
1602    ) -> Box<ExecutionTimingStats> {
1603        let accounts_read = provider_stats.total_account_fetches();
1604        let storage_read = provider_stats.total_storage_fetches();
1605        let code_read = provider_stats.total_code_fetches();
1606        let code_bytes_read = provider_stats.total_code_fetched_bytes();
1607
1608        // Write stats from BundleState (final state changes)
1609        let accounts_changed = output.state.len();
1610        let accounts_deleted =
1611            output.state.state.values().filter(|acc| acc.was_destroyed()).count();
1612        let storage_slots_changed =
1613            output.state.state.values().map(|account| account.storage.len()).sum::<usize>();
1614        let storage_slots_deleted = output
1615            .state
1616            .state
1617            .values()
1618            .flat_map(|account| account.storage.values())
1619            .filter(|slot| {
1620                slot.present_value.is_zero() && !slot.previous_or_original_value.is_zero()
1621            })
1622            .count();
1623
1624        // Helper: check if account represents a new contract deployment
1625        let is_new_deployment = |acc: &BundleAccount| -> bool {
1626            let has_code_now = acc.info.as_ref().is_some_and(|info| !info.is_empty_code_hash());
1627            let had_no_code_before =
1628                acc.original_info.as_ref().is_none_or(AccountInfo::is_empty_code_hash);
1629            has_code_now && had_no_code_before
1630        };
1631
1632        let bytecodes_changed =
1633            output.state.state.values().filter(|acc| is_new_deployment(acc)).count();
1634
1635        // Unique new code hashes to count actual bytes persisted (deduplicated)
1636        let unique_new_code_hashes: B256Set = output
1637            .state
1638            .state
1639            .values()
1640            .filter(|acc| is_new_deployment(acc))
1641            .filter_map(|acc| acc.info.as_ref().map(|info| info.code_hash))
1642            .collect();
1643        let code_bytes_written: usize = unique_new_code_hashes
1644            .iter()
1645            .filter_map(|hash| output.state.contracts.get(hash).map(|bytecode| bytecode.len()))
1646            .sum();
1647
1648        // Total time spent fetching state during execution
1649        let state_read_duration = provider_stats.total_account_fetch_latency() +
1650            provider_stats.total_storage_fetch_latency() +
1651            provider_stats.total_code_fetch_latency();
1652
1653        // EIP-7702 delegation tracking from bytecode changes
1654        // Count new EIP-7702 bytecodes as delegations set
1655        let eip7702_delegations_set =
1656            output.state.contracts.values().filter(|bytecode| bytecode.is_eip7702()).count();
1657        // Delegations cleared: accounts where bytecode changed FROM EIP-7702 TO empty
1658        // This detects when an EIP-7702 delegation is removed by setting code to empty
1659        // Note: Clearing a delegation does NOT destroy the account - it just empties the
1660        // bytecode
1661        let eip7702_delegations_cleared = output
1662            .state
1663            .state
1664            .values()
1665            .filter(|acc| {
1666                // Check if original bytecode was EIP-7702
1667                let original_was_eip7702 = acc
1668                    .original_info
1669                    .as_ref()
1670                    .and_then(|info| info.code.as_ref())
1671                    .is_some_and(|bytecode| bytecode.is_eip7702());
1672
1673                // Check if current code is empty (delegation cleared)
1674                let code_now_empty = acc.info.as_ref().is_some_and(AccountInfo::is_empty_code_hash);
1675
1676                original_was_eip7702 && code_now_empty
1677            })
1678            .count();
1679
1680        // Get cache statistics for detailed block logging
1681        let (account_cache_hits, account_cache_misses) = cache_stats
1682            .as_ref()
1683            .map(|s| (s.account_hits(), s.account_misses()))
1684            .unwrap_or_default();
1685        let (storage_cache_hits, storage_cache_misses) = cache_stats
1686            .as_ref()
1687            .map(|s| (s.storage_hits(), s.storage_misses()))
1688            .unwrap_or_default();
1689        let (code_cache_hits, code_cache_misses) =
1690            cache_stats.as_ref().map(|s| (s.code_hits(), s.code_misses())).unwrap_or_default();
1691        let (txpool_snapshot_account_hits, txpool_snapshot_account_misses) = cache_stats
1692            .as_ref()
1693            .map(|s| (s.txpool_snapshot_account_hits(), s.txpool_snapshot_account_misses()))
1694            .unwrap_or_default();
1695        let (txpool_snapshot_storage_hits, txpool_snapshot_storage_misses) = cache_stats
1696            .as_ref()
1697            .map(|s| (s.txpool_snapshot_storage_hits(), s.txpool_snapshot_storage_misses()))
1698            .unwrap_or_default();
1699        let (txpool_snapshot_code_hits, txpool_snapshot_code_misses) = cache_stats
1700            .as_ref()
1701            .map(|s| (s.txpool_snapshot_code_hits(), s.txpool_snapshot_code_misses()))
1702            .unwrap_or_default();
1703
1704        // Build execution timing stats for detailed block logging
1705        Box::new(ExecutionTimingStats {
1706            block_number: block.number(),
1707            block_hash: block.hash(),
1708            gas_used: output.result.gas_used,
1709            tx_count: block.transaction_count(),
1710            execution_duration,
1711            state_read_duration,
1712            state_hash_duration,
1713            accounts_read,
1714            storage_read,
1715            code_read,
1716            code_bytes_read,
1717            accounts_changed,
1718            accounts_deleted,
1719            storage_slots_changed,
1720            storage_slots_deleted,
1721            bytecodes_changed,
1722            code_bytes_written,
1723            eip7702_delegations_set,
1724            eip7702_delegations_cleared,
1725            account_cache_hits,
1726            account_cache_misses,
1727            storage_cache_hits,
1728            storage_cache_misses,
1729            code_cache_hits,
1730            code_cache_misses,
1731            txpool_snapshot_account_hits,
1732            txpool_snapshot_account_misses,
1733            txpool_snapshot_storage_hits,
1734            txpool_snapshot_storage_misses,
1735            txpool_snapshot_code_hits,
1736            txpool_snapshot_code_misses,
1737        })
1738    }
1739}
1740
1741/// Type that validates the payloads processed by the engine.
1742///
1743/// This provides the necessary functions for validating/executing payloads/blocks.
1744pub trait EngineValidator<
1745    Types: PayloadTypes,
1746    N: NodePrimitives = <<Types as PayloadTypes>::BuiltPayload as BuiltPayload>::Primitives,
1747>: Send + Sync + 'static
1748{
1749    /// Validates the payload attributes with respect to the header.
1750    ///
1751    /// By default, this enforces that the payload attributes timestamp is greater than the
1752    /// timestamp according to:
1753    ///   > 7. Client software MUST ensure that payloadAttributes.timestamp is greater than
1754    ///   > timestamp
1755    ///   > of a block referenced by forkchoiceState.headBlockHash.
1756    ///
1757    /// See also: <https://github.com/ethereum/execution-apis/blob/main/src/engine/common.md#specification-1>
1758    fn validate_payload_attributes_against_header(
1759        &self,
1760        attr: &Types::PayloadAttributes,
1761        header: &N::BlockHeader,
1762    ) -> Result<(), InvalidPayloadAttributesError>;
1763
1764    /// Ensures that the given payload does not violate any consensus rules that concern the block's
1765    /// layout.
1766    ///
1767    /// This function must convert the payload into the executable block and pre-validate its
1768    /// fields.
1769    ///
1770    /// Implementers should ensure that the checks are done in the order that conforms with the
1771    /// engine-API specification.
1772    fn convert_payload_to_block(
1773        &self,
1774        payload: Types::ExecutionData,
1775    ) -> Result<SealedBlock<N::Block>, NewPayloadError>;
1776
1777    /// Validates a payload received from engine API.
1778    fn validate_payload(
1779        &mut self,
1780        payload: Types::ExecutionData,
1781        ctx: TreeCtx<'_, N>,
1782    ) -> ValidationOutcome<N>;
1783
1784    /// Validates a block downloaded from the network, optionally carrying its access list data.
1785    fn validate_block(
1786        &mut self,
1787        block: SealedBlockWithAccessList<N::Block>,
1788        ctx: TreeCtx<'_, N>,
1789    ) -> ValidationOutcome<N>;
1790
1791    /// Hook called after an executed block is inserted directly into the tree.
1792    ///
1793    /// This is invoked when blocks are inserted via `InsertExecutedBlock` (e.g., locally built
1794    /// blocks by sequencers) to allow implementations to update internal state such as caches.
1795    fn on_inserted_executed_block(
1796        &self,
1797        block: BuiltPayloadExecutedBlock<N>,
1798    ) -> ProviderResult<ExecutedBlock<N>>;
1799
1800    /// Notifies the validator that `hash` is the current canonical head.
1801    ///
1802    /// This may also be called when a forkchoice update reaffirms the existing head.
1803    fn on_canonical_head_changed(&self, _hash: B256, _state: &EngineApiTreeState<N>) {}
1804
1805    /// Prepares the resources loaned to a payload builder job.
1806    ///
1807    /// `timestamp` is taken from the payload attributes.
1808    fn payload_builder_resources(
1809        &self,
1810        parent_hash: B256,
1811        parent_header: &N::BlockHeader,
1812        timestamp: u64,
1813        state: &mut EngineApiTreeState<N>,
1814    ) -> PayloadBuilderResources;
1815}
1816
1817impl<N, Types, P, Evm, V> EngineValidator<Types> for BasicEngineValidator<P, Evm, V>
1818where
1819    P: DatabaseProviderFactory<
1820            Provider: BlockReader
1821                          + StageCheckpointReader
1822                          + PruneCheckpointReader
1823                          + ChangeSetReader
1824                          + StorageChangeSetReader
1825                          + StorageSettingsCache
1826                          + HistoryReader
1827                          + 'static,
1828        > + BlockReader<Header = N::BlockHeader>
1829        + StateProviderFactory
1830        + StateReader
1831        + ChangeSetReader
1832        + Clone
1833        + 'static,
1834    N: NodePrimitives,
1835    V: PayloadValidator<Types, Block = N::Block> + Clone,
1836    Evm: ConfigureEngineEvm<Types::ExecutionData, Primitives = N> + 'static,
1837    Types: PayloadTypes<BuiltPayload: BuiltPayload<Primitives = N>>,
1838{
1839    fn validate_payload_attributes_against_header(
1840        &self,
1841        attr: &Types::PayloadAttributes,
1842        header: &N::BlockHeader,
1843    ) -> Result<(), InvalidPayloadAttributesError> {
1844        self.validator.validate_payload_attributes_against_header(attr, header)
1845    }
1846
1847    fn convert_payload_to_block(
1848        &self,
1849        payload: Types::ExecutionData,
1850    ) -> Result<SealedBlock<N::Block>, NewPayloadError> {
1851        let block = self.validator.convert_payload_to_block(payload)?;
1852        Ok(Arc::unwrap_or_clone(block))
1853    }
1854
1855    fn validate_payload(
1856        &mut self,
1857        payload: Types::ExecutionData,
1858        ctx: TreeCtx<'_, N>,
1859    ) -> ValidationOutcome<N> {
1860        self.validate_block_with_state(BlockOrPayload::Payload(payload), ctx)
1861    }
1862
1863    fn validate_block(
1864        &mut self,
1865        block: SealedBlockWithAccessList<N::Block>,
1866        ctx: TreeCtx<'_, N>,
1867    ) -> ValidationOutcome<N> {
1868        self.validate_block_with_state(BlockOrPayload::Block(block), ctx)
1869    }
1870
1871    fn on_inserted_executed_block(
1872        &self,
1873        block: BuiltPayloadExecutedBlock<N>,
1874    ) -> ProviderResult<ExecutedBlock<N>> {
1875        self.payload_processor.on_inserted_executed_block(
1876            block.recovered_block.block_with_parent(),
1877            &block.execution_output.state,
1878        );
1879
1880        Ok(self.spawn_deferred_trie_task(
1881            block.recovered_block,
1882            block.execution_output,
1883            LazyHashedPostState::ready(block.hashed_state),
1884            block.trie_updates,
1885        ))
1886    }
1887
1888    fn on_canonical_head_changed(&self, hash: B256, state: &EngineApiTreeState<N>) {
1889        let Some(txpool_prewarm) = self.txpool_prewarm.as_ref() else { return };
1890
1891        // Obtain the header of the new canonical head; pool transactions are warmed on top of
1892        // its state.
1893        let parent = match self.sealed_header_by_hash(hash, state) {
1894            Ok(Some(header)) => header,
1895            Ok(None) => return,
1896            Err(err) => {
1897                trace!(
1898                    target: "engine::tree::txpool_prewarm",
1899                    %err,
1900                    block_hash = ?hash,
1901                    "failed to fetch canonical header for txpool prewarming"
1902                );
1903                return
1904            }
1905        };
1906        // Unless results are recorded, warming reuses the head block's own environment rather
1907        // than predicting the next block's: attribute-level accuracy (timestamp, basefee) doesn't
1908        // matter for collecting state reads, and the worker disables the fee checks a stale
1909        // basefee would trip.
1910        let evm_env = match self.evm_config.evm_env(parent.header()) {
1911            Ok(evm_env) => evm_env,
1912            Err(err) => {
1913                trace!(
1914                    target: "engine::tree::txpool_prewarm",
1915                    %err,
1916                    block_hash = ?parent.hash(),
1917                    "failed to derive canonical txpool prewarming environment"
1918                );
1919                return
1920            }
1921        };
1922
1923        let state_provider_factory = match self.overlay_state_provider_factory(parent.hash(), state)
1924        {
1925            Ok(Some(state_provider_factory)) => state_provider_factory,
1926            Ok(None) => return,
1927            Err(err) => {
1928                trace!(
1929                    target: "engine::tree::txpool_prewarm",
1930                    %err,
1931                    block_hash = ?parent.hash(),
1932                    "failed to derive canonical txpool prewarming provider"
1933                );
1934                return
1935            }
1936        };
1937        txpool_prewarm.start(&parent, evm_env, state_provider_factory)
1938    }
1939
1940    fn payload_builder_resources(
1941        &self,
1942        parent_hash: B256,
1943        parent_header: &N::BlockHeader,
1944        timestamp: u64,
1945        state: &mut EngineApiTreeState<N>,
1946    ) -> PayloadBuilderResources {
1947        let execution_cache = self
1948            .config
1949            .share_execution_cache_with_payload_builder()
1950            .then(|| self.payload_processor.cache_for(parent_hash))
1951            .flatten();
1952        let state_root_handle =
1953            self.payload_state_root_handle_for(parent_hash, parent_header, timestamp, state);
1954        let mut resources = PayloadBuilderResources::new(execution_cache, state_root_handle)
1955            .with_lease(PayloadBuilderLease::new(JitPauseGuard::new(&self.evm_config)));
1956        // If the txpool prewarming is enabled then we should disable it for the duration
1957        // of the payload builder job. This is done by obtaining a lease that will release
1958        // the txpool prewarm when dropped.
1959        if let Some(txpool_prewarm) = self.txpool_prewarm.as_ref() {
1960            let txpool_lease = PayloadBuilderLease::new(txpool_prewarm.pause());
1961            resources = resources.with_lease(txpool_lease);
1962        }
1963        resources
1964    }
1965}
1966
1967impl<P, Evm, V> WaitForCaches for BasicEngineValidator<P, Evm, V>
1968where
1969    Evm: ConfigureEvm,
1970{
1971    fn wait_for_caches(&self) -> CacheWaitDurations {
1972        debug!(target: "engine::tree::payload_validator", "Waiting for execution cache and sparse trie locks");
1973
1974        let execution_cache = self.payload_processor.execution_cache();
1975        let overlay_manager = self.overlay_manager.clone();
1976        let (execution_tx, execution_rx) = mpsc::channel();
1977        let (sparse_trie_tx, sparse_trie_rx) = mpsc::channel();
1978
1979        self.runtime.spawn_blocking_named("wait-exec-cache", move || {
1980            let _ = execution_tx.send(execution_cache.wait_for_availability());
1981        });
1982        self.runtime.spawn_blocking_named("wait-sparse-tri", move || {
1983            let _ = sparse_trie_tx.send(overlay_manager.wait_for_sparse_trie_availability());
1984        });
1985
1986        let execution_cache =
1987            execution_rx.recv().expect("execution cache wait task failed to send result");
1988        let sparse_trie =
1989            sparse_trie_rx.recv().expect("sparse trie wait task failed to send result");
1990        debug!(
1991            target: "engine::tree::payload_validator",
1992            ?execution_cache,
1993            ?sparse_trie,
1994            "Execution cache and sparse trie locks acquired"
1995        );
1996        CacheWaitDurations { execution_cache, sparse_trie }
1997    }
1998}
1999
2000/// Enum representing either block or payload being validated.
2001#[derive(Debug, Clone)]
2002pub enum BlockOrPayload<T: PayloadTypes> {
2003    /// Payload.
2004    Payload(T::ExecutionData),
2005    /// Block with optional access list data, e.g. downloaded from the network.
2006    Block(SealedBlockWithAccessList<BlockTy<<T::BuiltPayload as BuiltPayload>::Primitives>>),
2007}
2008
2009impl<T: PayloadTypes> BlockOrPayload<T> {
2010    /// Returns the hash of the block.
2011    pub fn hash(&self) -> B256 {
2012        match self {
2013            Self::Payload(payload) => payload.block_hash(),
2014            Self::Block(block) => block.hash(),
2015        }
2016    }
2017
2018    /// Returns the number and hash of the block.
2019    pub fn num_hash(&self) -> NumHash {
2020        match self {
2021            Self::Payload(payload) => payload.num_hash(),
2022            Self::Block(block) => block.num_hash(),
2023        }
2024    }
2025
2026    /// Returns the parent hash of the block.
2027    pub fn parent_hash(&self) -> B256 {
2028        match self {
2029            Self::Payload(payload) => payload.parent_hash(),
2030            Self::Block(block) => block.parent_hash(),
2031        }
2032    }
2033
2034    /// Returns [`BlockWithParent`] for the block.
2035    pub fn block_with_parent(&self) -> BlockWithParent {
2036        match self {
2037            Self::Payload(payload) => payload.block_with_parent(),
2038            Self::Block(block) => block.block_with_parent(),
2039        }
2040    }
2041
2042    /// Returns a string showing whether or not this is a block or payload.
2043    pub const fn type_name(&self) -> &'static str {
2044        match self {
2045            Self::Payload(_) => "payload",
2046            Self::Block(_) => "block",
2047        }
2048    }
2049
2050    /// Returns true if this is a payload.
2051    pub const fn is_payload(&self) -> bool {
2052        matches!(self, Self::Payload(_))
2053    }
2054
2055    /// Returns true if this is a block.
2056    pub const fn is_block(&self) -> bool {
2057        matches!(self, Self::Block(_))
2058    }
2059
2060    /// Returns the decoded block access list, if present and successfully decoded.
2061    pub fn try_decoded_access_list(&self) -> Result<Option<DecodedBal>, alloy_rlp::Error> {
2062        match self {
2063            Self::Payload(payload) => payload
2064                .block_access_list()
2065                .map(|block_access_list| DecodedBal::from_rlp_bytes(block_access_list.clone()))
2066                .transpose(),
2067            Self::Block(block) => block.data().clone().map(DecodedBal::from_raw_bal).transpose(),
2068        }
2069    }
2070
2071    /// Returns whether execution must build a block access list.
2072    pub fn has_block_access_list(&self) -> bool {
2073        match self {
2074            Self::Payload(payload) => payload.block_access_list().is_some(),
2075            Self::Block(block) => block.block_access_list_hash().is_some(),
2076        }
2077    }
2078
2079    /// Returns the number of transactions in the payload or block.
2080    pub fn transaction_count(&self) -> usize
2081    where
2082        T::ExecutionData: ExecutionPayload,
2083    {
2084        match self {
2085            Self::Payload(payload) => payload.transaction_count(),
2086            Self::Block(block) => block.transaction_count(),
2087        }
2088    }
2089
2090    /// Returns the withdrawals from the payload or block.
2091    pub fn withdrawals(&self) -> Option<&[Withdrawal]>
2092    where
2093        T::ExecutionData: ExecutionPayload,
2094    {
2095        match self {
2096            Self::Payload(payload) => payload.withdrawals().map(|w| w.as_slice()),
2097            Self::Block(block) => block.body().withdrawals().map(|w| w.as_slice()),
2098        }
2099    }
2100
2101    /// Returns the total gas used by the block.
2102    pub fn gas_used(&self) -> u64
2103    where
2104        T::ExecutionData: ExecutionPayload,
2105    {
2106        match self {
2107            Self::Payload(payload) => payload.gas_used(),
2108            Self::Block(block) => block.gas_used(),
2109        }
2110    }
2111
2112    /// Returns the gas limit used by the block.
2113    pub fn gas_limit(&self) -> u64
2114    where
2115        T::ExecutionData: ExecutionPayload,
2116    {
2117        match self {
2118            Self::Payload(payload) => payload.gas_limit(),
2119            Self::Block(block) => block.gas_limit(),
2120        }
2121    }
2122}
2123
2124/// Block access list produced by executing a block.
2125struct ExecutedBal {
2126    /// Alloy form, only needed for the post-execution consensus checks (hash and gas limit).
2127    alloy: BlockAccessList,
2128    /// evm2 form, shared with the executed block so consumers can reuse it.
2129    evm: Arc<EvmBal>,
2130}