//! Optimism payload builder implementation. use crate::{ OpAttributes, OpPayloadBuilderAttributes, OpPayloadPrimitives, config::OpBuilderConfig, error::OpPayloadBuilderError, payload::OpBuiltPayload, }; use alloy_consensus::{BlockHeader, Sealable, Transaction, Typed2718, transaction::Recovered}; use alloy_evm::Evm as AlloyEvm; use alloy_primitives::{Address, B256, Sealed, U256}; use alloy_rpc_types_debug::ExecutionWitness; use alloy_rpc_types_engine::PayloadId; use op_alloy_consensus::{SDMGasEntry, TxPostExec, build_post_exec_tx}; use op_revm::{L1BlockInfo, constants::L1_BLOCK_CONTRACT}; use reth_basic_payload_builder::*; use reth_chainspec::{ChainSpecProvider, EthChainSpec}; use reth_evm::{ ConfigureEvm, Database, execute::{ BlockBuilder, BlockBuilderOutcome, BlockExecutionError, BlockExecutor, BlockValidationError, }, }; use reth_execution_cache::{CachedStateMetrics, CachedStateMetricsSource, CachedStateProvider}; use reth_execution_types::BlockExecutionOutput; use reth_metrics::{ Metrics, metrics::{self, Counter, Gauge, Histogram}, }; use reth_optimism_evm::{ConfigurePostExecEvm, PostExecExecutorExt, PostExecMode}; use reth_optimism_forks::OpHardforks; use reth_optimism_primitives::{L2_TO_L1_MESSAGE_PASSER_ADDRESS, OpTransaction}; use reth_optimism_txpool::{ OpPooledTx, estimated_da_size::DataAvailabilitySized, interop::{MaybeInteropTransaction, is_valid_interop}, }; use reth_payload_builder_primitives::PayloadBuilderError; use reth_payload_primitives::{BuildNextEnv, BuiltPayloadExecutedBlock}; use reth_payload_util::{BestPayloadTransactions, NoopPayloadTransactions, PayloadTransactions}; use reth_primitives_traits::{ HeaderTy, NodePrimitives, SealedHeader, SealedHeaderFor, SignedTransaction, TxTy, }; use reth_revm::{ cancelled::CancelOnDrop, database::StateProviderDatabase, db::State, witness::ExecutionWitnessRecord, }; use reth_storage_api::{StateProvider, StateProviderFactory, errors::ProviderError}; use reth_transaction_pool::{BestTransactionsAttributes, PoolTransaction, TransactionPool}; use reth_trie_parallel::{ root::ParallelStateRootError, state_root_task::{StateRootComputeOutcome, StateRootHandle}, }; use revm::context::{Block, BlockEnv}; use std::{ marker::PhantomData, sync::{Arc, mpsc::RecvTimeoutError}, time::{Duration, Instant}, }; use tracing::{debug, trace, warn}; /// Payload-builder metrics. #[derive(Metrics, Clone)] #[metrics(scope = "optimism_payload_builder")] struct OpPayloadBuilderMetrics { /// Total SDM gas refunded by produced `PostExec` payloads. sdm_refund_gas_total: Counter, /// SDM gas refunded by the latest produced block. sdm_refund_gas_per_block: Gauge, /// Builds whose state root came from the engine's shared sparse trie. state_root_from_shared_trie_total: Counter, /// Builds that fell back to the synchronous trie walk after the shared sparse trie failed to /// produce a state root. state_root_fallback_total: Counter, } impl OpPayloadBuilderMetrics { fn record_sdm_refund_gas(&self, gas_refund: u64) { self.sdm_refund_gas_total.increment(gas_refund); self.sdm_refund_gas_per_block.set(gas_refund as f64); } } /// Metrics for waiting on the engine's shared sparse trie. #[derive(Metrics, Clone)] #[metrics(scope = "optimism_payload_builder")] struct StateRootWaitMetrics { /// Time spent waiting for the shared sparse trie's state root, in seconds. state_root_wait_duration_seconds: Histogram, } impl StateRootWaitMetrics { fn record(outcome: &'static str, elapsed: Duration) { Self::new_with_labels(&[("outcome", outcome)]) .state_root_wait_duration_seconds .record(elapsed); } } enum StateRootWaitResult { Task(Result), Timeout(Duration), Disconnected, } /// Waits for the engine's shared sparse trie to produce a state root, bounded by `wait`. /// /// `None` preserves the previous unbounded wait. A timeout becomes an error so the caller takes /// the existing synchronous fallback path. fn await_sparse_trie_state_root( handle: &mut StateRootHandle, wait: Option, ) -> Result { let receiver = handle.take_state_root_rx(); let started = Instant::now(); let result = wait.map_or_else( || { receiver .recv() .map_or_else(|_| StateRootWaitResult::Disconnected, StateRootWaitResult::Task) }, |wait| match receiver.recv_timeout(wait) { Ok(result) => StateRootWaitResult::Task(result), Err(RecvTimeoutError::Timeout) => StateRootWaitResult::Timeout(wait), Err(RecvTimeoutError::Disconnected) => StateRootWaitResult::Disconnected, }, ); let elapsed = started.elapsed(); match result { StateRootWaitResult::Task(Ok(outcome)) => { StateRootWaitMetrics::record("success", elapsed); Ok(outcome) } StateRootWaitResult::Task(Err(err)) => { StateRootWaitMetrics::record("task_error", elapsed); Err(err) } StateRootWaitResult::Timeout(wait) => { StateRootWaitMetrics::record("timeout", elapsed); Err(ParallelStateRootError::Other(format!( "sparse trie task did not produce a state root within {wait:?}" ))) } StateRootWaitResult::Disconnected => { StateRootWaitMetrics::record("disconnected", elapsed); Err(ParallelStateRootError::Other("sparse trie task dropped".to_string())) } } } fn sdm_refund_gas(entries: &[SDMGasEntry]) -> u64 { entries.iter().map(|entry| entry.gas_refund).sum() } fn build_post_exec_recovered_tx(block_number: u64, entries: Vec) -> Recovered where Tx: From>, { let sealed = build_post_exec_tx(block_number, entries).seal_slow(); Recovered::new_unchecked(Tx::from(sealed), Address::ZERO) } /// Wraps refund entries in a post-exec transaction and executes it via `execute`. /// /// # Returns /// - `true` if a post-exec transaction was executed. /// - `false` if `entries` is empty. /// /// The post-exec transaction MUST execute successfully: any error is surfaced as /// `PayloadBuilderError::EvmExecutionError` so the payload build aborts. A verifier /// replaying this block will expect the post-exec tx to match the refunds it observes, /// so dropping the tx (or returning an empty block) on failure would produce a payload /// that no honest verifier can reproduce. fn try_include_post_exec_tx( block_number: u64, entries: Vec, execute: impl FnOnce(Recovered) -> Result, ) -> Result where Tx: From>, Err: core::error::Error + Send + Sync + 'static, { if entries.is_empty() { return Ok(false); } let post_exec_recovered = build_post_exec_recovered_tx(block_number, entries); execute(post_exec_recovered).map_err(|err| { warn!(target: "payload_builder", %err, "post-exec tx execution failed, aborting payload"); PayloadBuilderError::evm(err) })?; debug!(target: "payload_builder", "post-exec tx included in block"); Ok(true) } /// Optimism's payload builder #[derive(Debug)] pub struct OpPayloadBuilder< Pool, Client, Evm, Txs = (), Attrs = OpPayloadBuilderAttributes::Primitives>>, > { /// The rollup's compute pending block configuration option. pub compute_pending_block: bool, /// The type responsible for creating the evm. pub evm_config: Evm, /// Transaction pool. pub pool: Pool, /// Node client. pub client: Client, /// Settings for the builder, e.g. DA settings. pub config: OpBuilderConfig, /// The type responsible for yielding the best transactions for the payload if mempool /// transactions are allowed. pub best_transactions: Txs, /// Marker for the payload attributes type. _pd: PhantomData, } impl Clone for OpPayloadBuilder where Pool: Clone, Client: Clone, Evm: ConfigureEvm, Txs: Clone, { fn clone(&self) -> Self { Self { evm_config: self.evm_config.clone(), pool: self.pool.clone(), client: self.client.clone(), config: self.config.clone(), best_transactions: self.best_transactions.clone(), compute_pending_block: self.compute_pending_block, _pd: PhantomData, } } } impl OpPayloadBuilder { /// `OpPayloadBuilder` constructor. /// /// Configures the builder with the default settings. pub fn new(pool: Pool, client: Client, evm_config: Evm) -> Self { Self::with_builder_config(pool, client, evm_config, Default::default()) } /// Configures the builder with the given [`OpBuilderConfig`]. pub const fn with_builder_config( pool: Pool, client: Client, evm_config: Evm, config: OpBuilderConfig, ) -> Self { Self { pool, client, compute_pending_block: true, evm_config, config, best_transactions: (), _pd: PhantomData, } } } impl OpPayloadBuilder { /// Sets the rollup's compute pending block configuration option. pub const fn set_compute_pending_block(mut self, compute_pending_block: bool) -> Self { self.compute_pending_block = compute_pending_block; self } /// Configures the type responsible for yielding the transactions that should be included in the /// payload. pub fn with_transactions( self, best_transactions: T, ) -> OpPayloadBuilder { let Self { pool, client, compute_pending_block, evm_config, config, .. } = self; OpPayloadBuilder { pool, client, compute_pending_block, evm_config, best_transactions, config, _pd: PhantomData, } } /// Enables the rollup's compute pending block configuration option. pub const fn compute_pending_block(self) -> Self { self.set_compute_pending_block(true) } /// Returns the rollup's compute pending block configuration option. pub const fn is_compute_pending_block(&self) -> bool { self.compute_pending_block } } impl OpPayloadBuilder where Pool: TransactionPool>, Client: StateProviderFactory + ChainSpecProvider, N: OpPayloadPrimitives, N::SignedTx: From>, Evm: ConfigurePostExecEvm< Primitives = N, NextBlockEnvCtx: BuildNextEnv, >, Attrs: OpAttributes>, { /// Constructs an Optimism payload from the transactions sent via the /// Payload attributes by the sequencer. If the `no_tx_pool` argument is passed in /// the payload attributes, the transaction pool will be ignored and the only transactions /// included in the payload will be those sent through the attributes. /// /// Given build arguments including an Optimism client, transaction pool, /// and configuration, this function creates a transaction payload. Returns /// a result indicating success with the payload or an error in case of failure. fn build_payload<'a, Txs>( &self, args: BuildArguments>, best: impl FnOnce(BestTransactionsAttributes) -> Txs + Send + Sync + 'a, ) -> Result>, PayloadBuilderError> where Txs: PayloadTransactions + OpPooledTx>, { let BuildArguments { mut cached_reads, execution_cache, config, cancel, best_payload, trie_handle, } = args; let ctx = OpPayloadBuilderCtx { evm_config: self.evm_config.clone(), builder_config: self.config.clone(), chain_spec: self.client.chain_spec(), config, cancel, best_payload, }; let builder = OpBuilder::new(best).with_trie_handle(trie_handle); let mut state_provider = self.client.state_by_block_hash(ctx.parent().hash())?; // Serve account, storage and bytecode reads from the engine's cache when it shares one. // Trie and proof reads still go to the inner provider, which `CachedStateProvider` // delegates to, so the state root walk in `BlockBuilder::finish` is unaffected. if let Some(execution_cache) = execution_cache { debug_assert_eq!(execution_cache.executed_block_hash(), ctx.parent().hash()); state_provider = Box::new(CachedStateProvider::new( state_provider, execution_cache.cache().clone(), CachedStateMetrics::zeroed(CachedStateMetricsSource::Builder), )); } let state = StateProviderDatabase::new(&state_provider); if ctx.attributes().no_tx_pool() { builder.build(state, &state_provider, ctx) } else { // sequencer mode we can reuse cachedreads from previous runs builder.build(cached_reads.as_db_mut(state), &state_provider, ctx) } .map(|out| out.with_cached_reads(cached_reads)) } /// Computes the witness for the payload. pub fn payload_witness( &self, parent: SealedHeader, attributes: Attrs::RpcPayloadAttributes, ) -> Result { let attributes = Attrs::try_new(parent.hash(), attributes, 3)?; let payload_id = attributes.payload_id(); let config = PayloadConfig { parent_header: Arc::new(parent), attributes, payload_id }; let ctx = OpPayloadBuilderCtx { evm_config: self.evm_config.clone(), builder_config: self.config.clone(), chain_spec: self.client.chain_spec(), config, cancel: Default::default(), best_payload: Default::default(), }; let state_provider = self.client.state_by_block_hash(ctx.parent().hash())?; let builder = OpBuilder::new(|_| NoopPayloadTransactions::::default()); builder.witness(state_provider, &ctx) } } /// Implementation of the [`PayloadBuilder`] trait for [`OpPayloadBuilder`]. /// /// This impl uses [`crate::payload::OpPayloadAttrs`] (the RPC payload attributes wrapper) as the /// `Attributes` type, converting to [`OpPayloadBuilderAttributes`] internally for building. impl PayloadBuilder for OpPayloadBuilder> where N: OpPayloadPrimitives, N::SignedTx: From>, Client: StateProviderFactory + ChainSpecProvider + Clone, Pool: TransactionPool>, Evm: ConfigurePostExecEvm< Primitives = N, NextBlockEnvCtx: BuildNextEnv< OpPayloadBuilderAttributes, N::BlockHeader, Client::ChainSpec, >, >, Txs: OpPayloadTransactions, { type Attributes = crate::payload::OpPayloadAttrs; type BuiltPayload = OpBuiltPayload; fn try_build( &self, args: BuildArguments, ) -> Result, PayloadBuilderError> { let pool = self.pool.clone(); let converted_args = convert_build_args::(args)?; self.build_payload(converted_args, |attrs| { self.best_transactions.best_transactions(pool, attrs) }) } fn on_missing_payload( &self, _args: BuildArguments, ) -> MissingPayloadBehaviour { // we want to await the job that's already in progress because that should be returned as // is, there's no benefit in racing another job MissingPayloadBehaviour::AwaitInProgress } // NOTE: this should only be used for testing purposes because this doesn't have access to L1 // system txs, hence on_missing_payload we return [MissingPayloadBehaviour::AwaitInProgress]. fn build_empty_payload( &self, config: PayloadConfig, ) -> Result { let args = BuildArguments { config, cached_reads: Default::default(), execution_cache: None, trie_handle: None, cancel: Default::default(), best_payload: None, }; let converted_args = convert_build_args::(args)?; self.build_payload(converted_args, |_| { NoopPayloadTransactions::::default() })? .into_payload() .ok_or_else(|| PayloadBuilderError::MissingPayload) } } /// Converts `BuildArguments` from [`OpPayloadAttrs`](crate::payload::OpPayloadAttrs) to /// [`OpPayloadBuilderAttributes`], decoding the RPC transaction bytes into typed transactions. fn convert_build_args( args: BuildArguments>, ) -> Result< BuildArguments, OpBuiltPayload>, PayloadBuilderError, > { let BuildArguments { config, cached_reads, execution_cache, trie_handle, cancel, best_payload } = args; let parent_hash = config.parent_header.hash(); let payload_id = config.payload_id; let builder_attrs = OpPayloadBuilderAttributes::from_rpc_attrs(parent_hash, payload_id, config.attributes.0) .map_err(PayloadBuilderError::other)?; Ok(BuildArguments { config: PayloadConfig { parent_header: config.parent_header, attributes: builder_attrs, payload_id, }, cached_reads, execution_cache, trie_handle, cancel, best_payload, }) } /// The type that builds the payload. /// /// Payload building for optimism is composed of several steps. /// The first steps are mandatory and defined by the protocol. /// /// 1. first all System calls are applied. /// 2. After canyon the forced deployed `create2deployer` must be loaded /// 3. all sequencer transactions are executed (part of the payload attributes) /// /// Depending on whether the node acts as a sequencer and is allowed to include additional /// transactions (`no_tx_pool == false`): /// 4. include additional transactions /// /// And finally /// 5. build the block: compute all roots (txs, state) #[derive(derive_more::Debug)] pub struct OpBuilder<'a, Txs> { /// Yields the best transaction to include if transactions from the mempool are allowed. #[debug(skip)] best: Box Txs + 'a>, /// Handle to the engine's sparse trie pipeline, if it shares one for this payload. trie_handle: Option, } impl<'a, Txs> OpBuilder<'a, Txs> { /// Creates a new [`OpBuilder`]. pub fn new(best: impl FnOnce(BestTransactionsAttributes) -> Txs + Send + Sync + 'a) -> Self { Self { best: Box::new(best), trie_handle: None } } /// Shares the engine's sparse trie pipeline with this build. /// /// When set, per-transaction state diffs stream to the trie task during execution and the /// final root is taken from it, instead of the blocking trie walk in /// [`BlockBuilder::finish`]. pub fn with_trie_handle(mut self, trie_handle: Option) -> Self { self.trie_handle = trie_handle; self } } impl OpBuilder<'_, Txs> { /// Builds the payload on top of the state. pub fn build( self, db: impl Database, state_provider: impl StateProvider, ctx: OpPayloadBuilderCtx, ) -> Result>, PayloadBuilderError> where Evm: ConfigurePostExecEvm< Primitives = N, NextBlockEnvCtx: BuildNextEnv, >, ChainSpec: EthChainSpec + OpHardforks, N: OpPayloadPrimitives, N::SignedTx: From>, Txs: PayloadTransactions + OpPooledTx>, Attrs: OpAttributes, { let Self { best, trie_handle } = self; debug!(target: "payload_builder", id=%ctx.payload_id(), parent_header = ?ctx.parent().hash(), parent_number = ctx.parent().number(), "building new payload"); let mut db = State::builder().with_database(db).with_bundle_update().build(); // Load the L1 block contract into the database cache. If the L1 block contract is not // pre-loaded the database will panic when trying to fetch the DA footprint gas // scalar. db.load_cache_account(L1_BLOCK_CONTRACT).map_err(BlockExecutionError::other)?; let mut builder = ctx.block_builder(&mut db)?; // If we have a sparse trie handle, wire a state hook that streams per-tx state diffs // to the background trie pipeline for incremental state root computation. if let Some(ref handle) = trie_handle { builder.executor_mut().set_state_hook(Some(Box::new(handle.state_hook()))); } // 1. apply pre-execution changes builder.apply_pre_execution_changes().map_err(|err| { warn!(target: "payload_builder", %err, "failed to apply pre-execution changes"); PayloadBuilderError::Internal(err.into()) })?; // 2. execute sequencer transactions let mut info = ctx.execute_sequencer_transactions(&mut builder, None)?; // 3. if mem pool transactions are requested we execute them if !ctx.attributes().no_tx_pool() { let best_txs = best(ctx.best_transaction_attributes(builder.evm_mut().block())); if ctx .execute_best_transactions(&mut info, &mut builder, best_txs, None, None)? .is_some() { return Ok(BuildOutcomeKind::Cancelled); } // check if the new payload is even more valuable if !ctx.is_better_payload(info.total_fees) { // can skip building the block return Ok(BuildOutcomeKind::Aborted { fees: info.total_fees }); } } let sdm_refund_gas = if ctx.sdm_production_enabled() { let block_number = builder.evm_mut().block().number().saturating_to(); let entries = builder.executor_mut().take_post_exec_entries(); let refund_gas = self::sdm_refund_gas(&entries); try_include_post_exec_tx(block_number, entries, |tx| { builder.execute_transaction(tx).map(|g| g.tx_gas_used()) })?; refund_gas } else { 0 }; let metrics = OpPayloadBuilderMetrics::default(); let BlockBuilderOutcome { execution_result, hashed_state, trie_updates, block, block_access_list: _, } = if let Some(mut handle) = trie_handle { // Drop the state hook, which drops the StateHookSender and triggers // FinishedStateUpdates via its Drop impl, signaling the trie task to finalize. builder.executor_mut().set_state_hook(None); // The sparse trie has been computing incrementally alongside tx execution, so the // final root is usually immediate. Bound the wait anyway because a silent task would // otherwise park the payload job and `getPayload` indefinitely. match await_sparse_trie_state_root(&mut handle, ctx.builder_config.state_root_wait) { Ok(outcome) => { metrics.state_root_from_shared_trie_total.increment(1); debug!(target: "payload_builder", id=%ctx.payload_id(), state_root=?outcome.state_root, "received state root from sparse trie"); builder.finish( state_provider, Some((outcome.state_root, Arc::unwrap_or_clone(outcome.trie_updates))), )? } Err(err) => { metrics.state_root_fallback_total.increment(1); warn!(target: "payload_builder", id=%ctx.payload_id(), %err, "sparse trie failed, falling back to sync state root"); // Drop the handle before starting the fallback. Reth versions with a // cancellation guard can then stop work whose result is no longer needed. drop(handle); builder.finish(state_provider, None)? } } } else { builder.finish(state_provider, None)? }; metrics.record_sdm_refund_gas(sdm_refund_gas); let sealed_block = Arc::new(block.sealed_block().clone()); debug!(target: "payload_builder", id=%ctx.attributes().payload_id(), sealed_block_header = ?sealed_block.header(), "sealed built block"); let execution_outcome = BlockExecutionOutput { state: db.take_bundle(), result: execution_result }; // create the executed block data let executed: BuiltPayloadExecutedBlock = BuiltPayloadExecutedBlock { recovered_block: Arc::new(block), execution_output: Arc::new(execution_outcome), hashed_state: Arc::new(hashed_state), trie_updates: Arc::new(trie_updates), }; let no_tx_pool = ctx.attributes().no_tx_pool(); let payload = OpBuiltPayload::new(ctx.payload_id(), sealed_block, info.total_fees, Some(executed)); if no_tx_pool { // if `no_tx_pool` is set only transactions from the payload attributes will be included // in the payload. In other words, the payload is deterministic and we can // freeze it once we've successfully built it. Ok(BuildOutcomeKind::Freeze(payload)) } else { Ok(BuildOutcomeKind::Better { payload }) } } /// Builds the payload and returns its [`ExecutionWitness`] based on the state after execution. pub fn witness( self, state_provider: impl StateProvider, ctx: &OpPayloadBuilderCtx, ) -> Result where Evm: ConfigurePostExecEvm< Primitives = N, NextBlockEnvCtx: BuildNextEnv, >, ChainSpec: EthChainSpec + OpHardforks, N: OpPayloadPrimitives, N::SignedTx: From>, Txs: PayloadTransactions>, Attrs: OpAttributes, { let mut db = State::builder() .with_database(StateProviderDatabase::new(&state_provider)) .with_bundle_update() .build(); let mut builder = ctx.block_builder(&mut db)?; builder.apply_pre_execution_changes()?; ctx.execute_sequencer_transactions(&mut builder, None)?; builder.into_executor().apply_post_execution_changes()?; if ctx.chain_spec.is_isthmus_active_at_timestamp(ctx.attributes().timestamp()) { // force load `L2ToL1MessagePasser.sol` so l2 withdrawals root can be computed even if // no l2 withdrawals in block _ = db.load_cache_account(L2_TO_L1_MESSAGE_PASSER_ADDRESS)?; } let ExecutionWitnessRecord { hashed_state, codes, keys, lowest_block_number: _ } = ExecutionWitnessRecord::from_executed_state(&db, Default::default()); let state = state_provider.witness(Default::default(), hashed_state, Default::default())?; Ok(ExecutionWitness { state: state.into_iter().collect(), codes, keys, ..Default::default() }) } } /// A type that returns a the [`PayloadTransactions`] that should be included in the pool. pub trait OpPayloadTransactions: Clone + Send + Sync + Unpin + 'static { /// Returns an iterator that yields the transaction in the order they should get included in the /// new payload. fn best_transactions>( &self, pool: Pool, attr: BestTransactionsAttributes, ) -> impl PayloadTransactions; } impl OpPayloadTransactions for () { fn best_transactions>( &self, pool: Pool, attr: BestTransactionsAttributes, ) -> impl PayloadTransactions { BestPayloadTransactions::new(pool.best_transactions_with_attributes(attr)) } } /// Holds the state after execution #[derive(Debug)] pub struct ExecutedPayload { /// Tracked execution info pub info: ExecutionInfo, /// Withdrawal hash. pub withdrawals_root: Option, /// The transaction receipts. pub receipts: Vec, /// The block env used during execution. pub block_env: BlockEnv, } /// This acts as the container for executed transactions and its byproducts (receipts, gas used) #[derive(Default, Debug)] pub struct ExecutionInfo { /// All gas used so far pub cumulative_gas_used: u64, /// Estimated DA size pub cumulative_da_bytes_used: u64, /// Tracks fees from executed mempool transactions pub total_fees: U256, } impl ExecutionInfo { /// Create a new instance with allocated slots. pub const fn new() -> Self { Self { cumulative_gas_used: 0, cumulative_da_bytes_used: 0, total_fees: U256::ZERO } } /// Returns true if the transaction would exceed the block limits: /// - block gas limit: ensures the transaction still fits into the block. /// - tx DA limit: if configured, ensures the tx does not exceed the maximum allowed DA limit /// per tx. /// - block DA limit: if configured, ensures the transaction's DA size does not exceed the /// maximum allowed DA limit per block. pub fn is_tx_over_limits( &self, tx_da_size: u64, block_gas_limit: u64, tx_data_limit: Option, block_data_limit: Option, tx_gas_limit: u64, da_footprint_gas_scalar: Option, ) -> bool { if tx_data_limit.is_some_and(|da_limit| tx_da_size > da_limit) { return true; } let total_da_bytes_used = self.cumulative_da_bytes_used.saturating_add(tx_da_size); if block_data_limit.is_some_and(|da_limit| total_da_bytes_used > da_limit) { return true; } // Post Jovian: the tx DA footprint must be less than the block gas limit if let Some(da_footprint_gas_scalar) = da_footprint_gas_scalar { let tx_da_footprint = total_da_bytes_used.saturating_mul(da_footprint_gas_scalar as u64); if tx_da_footprint > block_gas_limit { return true; } } self.cumulative_gas_used + tx_gas_limit > block_gas_limit } } /// Container type that holds all necessities to build a new payload. #[derive(derive_more::Debug)] pub struct OpPayloadBuilderCtx< Evm: ConfigureEvm, ChainSpec, Attrs = OpPayloadBuilderAttributes::Primitives>>, > { /// The type that knows how to perform system calls and configure the evm. pub evm_config: Evm, /// Additional config for the builder/sequencer, e.g. DA and gas limit pub builder_config: OpBuilderConfig, /// The chainspec pub chain_spec: Arc, /// How to build the payload. pub config: PayloadConfig>, /// Marker to check whether the job has been cancelled. pub cancel: CancelOnDrop, /// The currently best payload. pub best_payload: Option>, } impl OpPayloadBuilderCtx where Evm: ConfigurePostExecEvm< Primitives: OpPayloadPrimitives, NextBlockEnvCtx: BuildNextEnv, ChainSpec>, >, ChainSpec: EthChainSpec + OpHardforks, Attrs: OpAttributes>, { /// Returns the parent block the payload will be build on. pub fn parent(&self) -> &SealedHeaderFor { self.config.parent_header.as_ref() } /// Returns the builder attributes. pub const fn attributes(&self) -> &Attrs { &self.config.attributes } /// Returns the current fee settings for transactions from the mempool pub fn best_transaction_attributes(&self, block_env: impl Block) -> BestTransactionsAttributes { BestTransactionsAttributes::new( block_env.basefee(), block_env.blob_gasprice().map(|p| p as u64), ) } /// Returns whether SDM production should run for this payload. /// /// Two gates must agree: /// - **Protocol**: SDM rides the Interop hardfork, so this requires Interop active at the next /// block's timestamp per the chain spec. /// - **Operator**: the local opt-in flag on `OpBuilderConfig`, mutated by the `admin_` SDM RPC. /// Starts disabled at process boot. /// /// Either being false disables production. pub fn sdm_production_enabled(&self) -> bool { let protocol_active = reth_optimism_evm::is_sdm_active_at_timestamp( &self.chain_spec, self.attributes().timestamp(), ); protocol_active && self.builder_config.sdm_post_exec_opt_in.enabled() } /// Returns the unique id for this payload job. pub fn payload_id(&self) -> PayloadId { self.attributes().payload_id() } /// Returns true if the fees are higher than the previous payload. pub fn is_better_payload(&self, total_fees: U256) -> bool { is_better_payload(self.best_payload.as_ref(), total_fees) } /// Prepares a [`BlockBuilder`] for the next block. pub fn block_builder<'a, DB: Database>( &'a self, db: &'a mut State, ) -> Result< impl BlockBuilder + 'a, PayloadBuilderError, > { let post_exec_mode: PostExecMode = self.sdm_production_enabled().into(); self.evm_config .post_exec_builder_for_next_block( db, self.parent(), Evm::NextBlockEnvCtx::build_next_env( self.attributes(), self.parent(), self.chain_spec.as_ref(), ) .map_err(PayloadBuilderError::other)?, post_exec_mode, ) .map_err(PayloadBuilderError::other) } /// Executes all sequencer transactions that are included in the payload attributes. /// /// When `committed_txs` is `Some(vec)`, each successfully committed sequencer /// transaction is appended to `vec` in commit order. `None` skips the /// recording. The function never reads or clears the vec; the caller controls /// capacity and lifecycle. pub fn execute_sequencer_transactions( &self, builder: &mut impl BlockBuilder, mut committed_txs: Option<&mut Vec>>>, ) -> Result { let mut info = ExecutionInfo::new(); for sequencer_tx in self.attributes().sequencer_transactions() { // A sequencer's block should never contain blob transactions. if sequencer_tx.value().is_eip4844() { return Err(PayloadBuilderError::other( OpPayloadBuilderError::BlobTransactionRejected, )); } // Convert the transaction to a [RecoveredTx]. This is // purely for the purposes of utilizing the `evm_config.tx_env`` function. // Deposit transactions do not have signatures, so if the tx is a deposit, this // will just pull in its `from` address. let sequencer_tx = sequencer_tx.value().try_clone_into_recovered().map_err(|_| { PayloadBuilderError::other(OpPayloadBuilderError::TransactionEcRecoverFailed) })?; let gas_used = match builder.execute_transaction(sequencer_tx.clone()) { Ok(gas_used) => gas_used, Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { error, .. })) => { trace!(target: "payload_builder", %error, ?sequencer_tx, "Error in sequencer transaction, skipping."); continue; } Err(err) => { // this is an error that we should treat as fatal for this attempt return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))); } }; // add gas used by the transaction to cumulative gas used, before creating the receipt info.cumulative_gas_used += gas_used.tx_gas_used(); // Record the successfully committed transaction for callers that want per-call // visibility. if let Some(sink) = committed_txs.as_deref_mut() { sink.push(sequencer_tx); } } Ok(info) } /// Executes the given best transactions and updates the execution info. /// /// `gas_limit_cap` is an optional upper bound on the per-call gas budget. /// - `None`: effective limit is `min(block_gas_limit, gas_limit_config)`. /// - `Some(g)`: effective limit is `min(g, block_gas_limit, gas_limit_config)` /// /// When `committed_txs` is `Some(vec)`, each successfully committed transaction /// is appended to `vec` in commit order. `None` skips the recording. The /// function never reads or clears the vec; the caller controls capacity and /// lifecycle. /// /// Returns `Ok(Some(()))` if the job was cancelled. pub fn execute_best_transactions( &self, info: &mut ExecutionInfo, builder: &mut Builder, mut best_txs: impl PayloadTransactions< Transaction: PoolTransaction> + OpPooledTx, >, gas_limit_cap: Option, mut committed_txs: Option<&mut Vec>>>, ) -> Result, PayloadBuilderError> where Builder: BlockBuilder, <::Evm as AlloyEvm>::DB: Database, { let mut block_gas_limit = builder.evm_mut().block().gas_limit(); if let Some(gas_limit_config) = self.builder_config.gas_limit_config.gas_limit() { // If a gas limit is configured, use that limit as target if it's smaller, otherwise use // the block's actual gas limit. block_gas_limit = gas_limit_config.min(block_gas_limit); }; if let Some(gas_limit_cap) = gas_limit_cap { // If a gas limit cap is provided, use that limit as target if it's smaller, otherwise // use the block's actual gas limit. block_gas_limit = gas_limit_cap.min(block_gas_limit); } let block_da_limit = self.builder_config.da_config.max_da_block_size(); let tx_da_limit = self.builder_config.da_config.max_da_tx_size(); let base_fee = builder.evm_mut().block().basefee(); while let Some(tx) = best_txs.next(()) { let interop = tx.interop_deadline(); let tx_da_size = tx.estimated_da_size(); // Compute the miner fee on the pool tx so downstream pool wrappers can // override `effective_tip_per_gas` (e.g. to convert non-native fee // denominations into a native-wei tip) before the consensus tx is exposed. let miner_fee = tx .effective_tip_per_gas(base_fee) .expect("selected pool transaction must have a valid effective miner tip at the block base fee"); let tx = tx.into_consensus(); let da_footprint_gas_scalar = self .chain_spec .is_jovian_active_at_timestamp(self.attributes().timestamp()) .then_some( L1BlockInfo::fetch_da_footprint_gas_scalar(builder.evm_mut().db_mut()).expect( "DA footprint should always be available from the database post jovian", ), ); if info.is_tx_over_limits( tx_da_size, block_gas_limit, tx_da_limit, block_da_limit, tx.gas_limit(), da_footprint_gas_scalar, ) { // we can't fit this transaction into the block, so we need to mark it as // invalid which also removes all dependent transaction from // the iterator before we can continue best_txs.mark_invalid(tx.signer(), tx.nonce()); continue; } // A sequencer's block should never contain blob or deposit transactions from the pool. if tx.is_eip4844() || tx.is_deposit() { best_txs.mark_invalid(tx.signer(), tx.nonce()); continue; } // We skip invalid cross chain txs, they would be removed on the next block update in // the maintenance job if let Some(interop) = interop && !is_valid_interop(interop, self.config.attributes.timestamp()) { best_txs.mark_invalid(tx.signer(), tx.nonce()); continue; } // check if the job was cancelled, if so we can exit early if self.cancel.is_cancelled() { return Ok(Some(())); } let gas_used = match builder.execute_transaction(tx.clone()) { Ok(gas_used) => gas_used, Err(BlockExecutionError::Validation(BlockValidationError::InvalidTx { error, .. })) => { if error.is_nonce_too_low() { // if the nonce is too low, we can skip this transaction trace!(target: "payload_builder", %error, ?tx, "skipping nonce too low transaction"); } else { // if the transaction is invalid, we can skip it and all of its // descendants trace!(target: "payload_builder", %error, ?tx, "skipping invalid transaction and its descendants"); best_txs.mark_invalid(tx.signer(), tx.nonce()); } continue; } Err(err) => { // this is an error that we should treat as fatal for this attempt return Err(PayloadBuilderError::EvmExecutionError(Box::new(err))); } }; // add gas used by the transaction to cumulative gas used, before creating the // receipt let tx_gas_used = gas_used.tx_gas_used(); info.cumulative_gas_used += tx_gas_used; info.cumulative_da_bytes_used += tx_da_size; // update and add to total fees info.total_fees += U256::from(miner_fee) * U256::from(tx_gas_used); // Record the successfully committed transaction for callers that want per-call // visibility. if let Some(sink) = committed_txs.as_deref_mut() { sink.push(tx); } } Ok(None) } } #[cfg(test)] mod tests;