1use 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
175const MAX_EXPECTED_GAS_LIMIT_MULTIPLIER: u64 = 2;
178
179const 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
185pub struct TreeCtx<'a, N: NodePrimitives> {
190 state: &'a mut EngineApiTreeState<N>,
192 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 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 pub const fn state(&self) -> &EngineApiTreeState<N> {
218 &*self.state
219 }
220
221 pub const fn state_mut(&mut self) -> &mut EngineApiTreeState<N> {
223 self.state
224 }
225
226 pub const fn canonical_in_memory_state(&self) -> &'a CanonicalInMemoryState<N> {
228 self.canonical_in_memory_state
229 }
230}
231
232struct 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#[derive(derive_more::Debug)]
264pub struct BasicEngineValidator<P, Evm, V>
265where
266 Evm: ConfigureEvm,
267{
268 provider: P,
270 consensus: Arc<dyn FullConsensus<Evm::Primitives>>,
272 evm_config: Evm,
274 config: TreeConfig,
276 payload_processor: PayloadProcessor<Evm>,
278 precompile_cache_map: PrecompileCacheMap<SpecFor<Evm>>,
280 #[debug(skip)]
282 invalid_block_hook: Box<dyn InvalidBlockHook<Evm::Primitives>>,
283 metrics: EngineApiMetrics,
285 validator: V,
287 runtime: reth_tasks::Runtime,
289 overlay_manager: OverlayManager<Evm::Primitives>,
291 #[debug(skip)]
293 state_root_strategy: Arc<dyn StateRootStrategy<Evm::Primitives, P, Evm>>,
294 #[debug(skip)]
298 txpool_prewarm: Option<txpool_prewarm::Handle<Evm::Primitives, P, Evm>>,
299 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 #[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 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 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 #[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 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 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 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 #[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 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 let validated_block = self.spawn_convert_and_validate(&input, parent_block.clone());
506
507 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 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 input.gas_limit() >
540 parent_block.gas_limit().saturating_mul(MAX_EXPECTED_GAS_LIMIT_MULTIPLIER)
541 {
542 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 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 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 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 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 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 let execution_state_hook = state_root_job.take_execution_hook();
630 let hint_stream = state_root_job.take_hint_stream();
633 let hashed_update_stream = state_root_job.take_hashed_update_stream();
634
635 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 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 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 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 handle.stop_prewarming_execution();
749
750 let output = Arc::new(output);
754
755 let valid_block_tx = handle.terminate_caching(Some(output.clone()));
758
759 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 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 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 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 if state_root != block.header().state_root() {
890 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 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 #[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 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 fn sealed_header_by_hash(
994 &self,
995 hash: B256,
996 state: &EngineApiTreeState<N>,
997 ) -> ProviderResult<Option<SealedHeader<N::BlockHeader>>> {
998 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 #[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 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 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 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 #[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 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 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 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 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 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 let mut last_sent_len = 0usize;
1253 loop {
1254 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 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 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 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 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 #[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 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 self.on_invalid_block(parent_block, block, output, None, ctx.state_mut());
1392 return Err(err.into())
1393 }
1394 drop(_enter);
1395
1396 self.metrics
1398 .block_validation
1399 .post_execution_validation_duration
1400 .record(start.elapsed().as_secs_f64());
1401
1402 Ok(())
1403 }
1404
1405 #[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 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 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 return
1482 }
1483 self.invalid_block_hook.on_invalid_block(parent_header, block, output, trie_updates);
1484 }
1485
1486 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 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 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 let block_number = block.number();
1563
1564 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 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 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 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 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 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 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 let eip7702_delegations_set =
1656 output.state.contracts.values().filter(|bytecode| bytecode.is_eip7702()).count();
1657 let eip7702_delegations_cleared = output
1662 .state
1663 .state
1664 .values()
1665 .filter(|acc| {
1666 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 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 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 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
1741pub trait EngineValidator<
1745 Types: PayloadTypes,
1746 N: NodePrimitives = <<Types as PayloadTypes>::BuiltPayload as BuiltPayload>::Primitives,
1747>: Send + Sync + 'static
1748{
1749 fn validate_payload_attributes_against_header(
1759 &self,
1760 attr: &Types::PayloadAttributes,
1761 header: &N::BlockHeader,
1762 ) -> Result<(), InvalidPayloadAttributesError>;
1763
1764 fn convert_payload_to_block(
1773 &self,
1774 payload: Types::ExecutionData,
1775 ) -> Result<SealedBlock<N::Block>, NewPayloadError>;
1776
1777 fn validate_payload(
1779 &mut self,
1780 payload: Types::ExecutionData,
1781 ctx: TreeCtx<'_, N>,
1782 ) -> ValidationOutcome<N>;
1783
1784 fn validate_block(
1786 &mut self,
1787 block: SealedBlockWithAccessList<N::Block>,
1788 ctx: TreeCtx<'_, N>,
1789 ) -> ValidationOutcome<N>;
1790
1791 fn on_inserted_executed_block(
1796 &self,
1797 block: BuiltPayloadExecutedBlock<N>,
1798 ) -> ProviderResult<ExecutedBlock<N>>;
1799
1800 fn on_canonical_head_changed(&self, _hash: B256, _state: &EngineApiTreeState<N>) {}
1804
1805 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 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 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 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#[derive(Debug, Clone)]
2002pub enum BlockOrPayload<T: PayloadTypes> {
2003 Payload(T::ExecutionData),
2005 Block(SealedBlockWithAccessList<BlockTy<<T::BuiltPayload as BuiltPayload>::Primitives>>),
2007}
2008
2009impl<T: PayloadTypes> BlockOrPayload<T> {
2010 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 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 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 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 pub const fn type_name(&self) -> &'static str {
2044 match self {
2045 Self::Payload(_) => "payload",
2046 Self::Block(_) => "block",
2047 }
2048 }
2049
2050 pub const fn is_payload(&self) -> bool {
2052 matches!(self, Self::Payload(_))
2053 }
2054
2055 pub const fn is_block(&self) -> bool {
2057 matches!(self, Self::Block(_))
2058 }
2059
2060 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 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 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 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 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 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
2124struct ExecutedBal {
2126 alloy: BlockAccessList,
2128 evm: Arc<EvmBal>,
2130}