//! Block executor for Optimism. use crate::{OpEvmFactory, spec_by_timestamp_after_bedrock}; use alloc::{boxed::Box, format, string::String, vec::Vec}; use alloy_consensus::{Eip658Value, Header, Transaction, TransactionEnvelope, TxReceipt}; use alloy_eips::{Encodable2718, Typed2718, eip7685::Requests}; use alloy_evm::{ Database, Evm, EvmFactory, FromRecoveredTx, FromTxWithEncoded, IntoTxEnv, RecoveredTx, block::{ BlockExecutionError, BlockExecutionResult, BlockExecutor, BlockExecutorFactory, BlockValidationError, CommitChanges, ExecutableTx, GasOutput, InternalBlockExecutionError, StateDB, SystemCaller, TxResult, state_changes::post_block_balance_increments, }, eth::{EthTxResult, receipt_builder::ReceiptBuilderCtx}, }; use alloy_op_hardforks::{OpChainHardforks, OpHardforks}; use alloy_primitives::{Address, B256, Bytes, U256}; use canyon::ensure_create2_deployer; use op_alloy::consensus::{ OpDepositReceipt, OpTransaction as OpConsensusTransaction, POST_EXEC_TX_TYPE_ID, PostExecPayload, SDMGasEntry, }; use op_revm::{ L1BlockInfo, OpTransaction, constants::{BASE_FEE_RECIPIENT, L1_BLOCK_CONTRACT, OPERATOR_FEE_RECIPIENT}, encoded_tx_da_footprint, transaction::deposit::DEPOSIT_TRANSACTION_TYPE, tx_da_footprint, }; pub use receipt_builder::OpAlloyReceiptBuilder; use receipt_builder::OpReceiptBuilder; use revm::{ Database as _, DatabaseCommit, Inspector, context::{ Block, TxEnv, result::{ExecutionResult, ResultAndState, ResultGas}, }, database::DatabaseCommitExt, state::{Account, AccountStatus, EvmState}, }; use crate::post_exec::{ PostExecEvm, PostExecEvmFactoryAdapter, PostExecEvmFactoryHooks, PostExecExecutedTx, PostExecRefundEvent, PostExecRefundPolicyFactory, PostExecTxContext, PostExecTxKind, noop_post_exec_result, }; mod canyon; pub mod receipt_builder; /// Wraps an [`OpBlockExecutionError`] as a block-execution validation error. fn validation_error(err: OpBlockExecutionError) -> BlockExecutionError { BlockExecutionError::Validation(BlockValidationError::Other(Box::new(err))) } /// Returns the gas a transaction would have used had execution spent `discount` less gas. /// /// The EIP-3529 refund cap and the EIP-7623 floor are both functions of gas spent, so a discount on /// spent gas does not lower gas used one-for-one: the cap shrinks with it, and a binding floor /// absorbs it entirely. fn gas_used_with_spend_discount(gas: &ResultGas, discount: u64, max_refund_quotient: u64) -> u64 { let spent = gas.total_gas_spent().saturating_sub(discount); // `inner_refunded` is already capped at `total_gas_spent / quotient`, and the discounted cap is // no larger, so this equals capping the raw refund counter at the discounted spend. let refunded = gas.inner_refunded().min(spent / max_refund_quotient); spent.saturating_sub(refunded).max(gas.floor_gas()) } /// Returns a producer policy's consensus-safe refund for an executed transaction. /// /// A refund policy is advisory: malformed output must not reject an otherwise valid transaction or /// abort payload production. A normal-transaction refund that exceeds the gas execution spent can /// only come from a faulty policy and is discarded, while deposits are never refundable. /// /// A policy's refund is a discount on the gas execution spent (for block-level warming, the /// EIP-2929 surcharges on block-warm accesses). It is clipped to what that discount actually saves /// the transaction, so the refund never lowers canonical gas below the gas the transaction would /// have used had execution spent that much less. Gas used is net of the EIP-3529 refund, so a /// discount can exceed it; the clip, not a comparison with gas used, is what keeps the refund /// within the verifier's `refund <= evmGasUsed` bound. The clip is producer policy, not consensus: /// verifiers apply whatever refund the payload carries. #[cfg_attr(not(feature = "metrics"), allow(clippy::missing_const_for_fn))] fn sanitize_producer_refund( refund: u64, gas: &ResultGas, max_refund_quotient: u64, is_deposit: bool, ) -> u64 { let (refund, correction) = if is_deposit && refund > 0 { (0, Some("ineligible_transaction")) } else if refund > gas.total_gas_spent() { (0, Some("exceeds_gas_spent")) } else { let net_saving = gas.tx_gas_used().saturating_sub(gas_used_with_spend_discount( gas, refund, max_refund_quotient, )); if refund > net_saving { (net_saving, Some("exceeds_net_saving")) } else { (refund, None) } }; #[cfg(feature = "metrics")] if let Some(reason) = correction { metrics::counter!("optimism_sdm.policy_refund_corrections", "reason" => reason) .increment(1); } #[cfg(not(feature = "metrics"))] let _ = correction; refund } /// Trait for OP transaction environments. Allows to recover the transaction encoded bytes if /// they're available. pub trait OpTxEnv { /// Returns the encoded bytes of the transaction. fn encoded_bytes(&self) -> Option<&Bytes>; } impl OpTxEnv for OpTransaction { fn encoded_bytes(&self) -> Option<&Bytes> { self.enveloped_tx.as_ref() } } /// Canonical post-exec execution mode for an OP block. #[derive(Debug, Default, Clone)] pub enum PostExecMode { /// Execute with legacy gas accounting. #[default] Disabled, /// Produce canonical post-exec refunds locally and append them to the block later. Produce, /// Verify canonical gas accounting using a post-exec payload embedded in the block. Verify(PostExecPayload), /// Reject the block in pre-execution, so the engine classifies it as invalid. /// /// Callers must run [`BlockExecutor::apply_pre_execution_changes`] before executing /// transactions. This variant is rejected there; `finish()` is not a substitute for /// pre-execution validation. Invalid(String), } impl From for PostExecMode { /// `true` opts into local post-exec production; `false` disables it. fn from(produce: bool) -> Self { if produce { Self::Produce } else { Self::Disabled } } } /// Per-block post-exec state carried by [`OpBlockExecutor`]. #[derive(Debug)] pub enum PostExecState { /// Execute with legacy gas accounting. Disabled, /// Produce canonical post-exec refunds locally and append them to the block later. Producing { /// Accumulated per-tx refunds for post-exec tx assembly. entries: Vec, }, /// Reject the block before executing any transactions. Invalid { /// Parser failure. reason: String, }, /// Verify canonical gas accounting using a post-exec payload embedded in the block. Verifying { /// Decoded post-exec payload being verified. Entries are strictly ordered by transaction /// index, so verification can consume them with a cursor instead of allocating a map. payload: PostExecPayload, /// Offset of the next unconsumed payload entry. next_entry: usize, /// Invalid verifier payload reason, if any. invalid_reason: Option, /// Whether the block's synthetic post-exec transaction has been seen during execution. saw_post_exec_tx: bool, }, } /// Checks the version-1 canonical form of a verifier payload's refund entries: non-empty, no zero /// refunds, and tx indices strictly increasing. Returns the first violation. fn validate_verifier_entries(entries: &[SDMGasEntry]) -> Result<(), String> { if entries.is_empty() { return Err(String::from("empty post-exec payload gas refund entries")); } let mut previous_index = None; for entry in entries { if entry.gas_refund == 0 { return Err(format!("zero post-exec payload refund for tx index {}", entry.index)); } match previous_index { Some(previous) if entry.index == previous => { return Err(format!( "duplicate post-exec payload entry for tx index {}", entry.index )); } Some(previous) if entry.index < previous => { return Err(format!( "post-exec payload entries not strictly increasing: tx index {} follows {}", entry.index, previous, )); } _ => {} } previous_index = Some(entry.index); } Ok(()) } impl PostExecState { fn new(mode: PostExecMode) -> Self { match mode { PostExecMode::Disabled => Self::Disabled, PostExecMode::Produce => Self::Producing { entries: Vec::new() }, PostExecMode::Verify(payload) => { let invalid_reason = validate_verifier_entries(&payload.gas_refund_entries).err(); Self::Verifying { payload, next_entry: 0, invalid_reason, saw_post_exec_tx: false } } PostExecMode::Invalid(reason) => Self::Invalid { reason }, } } const fn is_producing(&self) -> bool { matches!(self, Self::Producing { .. }) } const fn is_verifying(&self) -> bool { matches!(self, Self::Verifying { .. }) } const fn invalid_reason(&self) -> Option<&str> { match self { Self::Invalid { reason } | Self::Verifying { invalid_reason: Some(reason), .. } => { Some(reason.as_str()) } _ => None, } } fn verify_block_number(&self, block_number: u64) -> Option { match self { Self::Verifying { payload, .. } if payload.block_number != block_number => { Some(format!( "payload block number {} does not match block number {}", payload.block_number, block_number, )) } _ => None, } } const fn produced_entries(&self) -> &[SDMGasEntry] { match self { Self::Producing { entries } => entries.as_slice(), _ => &[], } } const fn produced_entries_mut(&mut self) -> Option<&mut Vec> { match self { Self::Producing { entries } => Some(entries), _ => None, } } fn take_entries(&mut self) -> Vec { match self { Self::Producing { entries } => core::mem::take(entries), _ => Vec::new(), } } fn verifier_refund(&self, tx_index: u64) -> Option { match self { Self::Verifying { payload, next_entry, .. } => payload .gas_refund_entries .get(*next_entry) .filter(|entry| entry.index == tx_index) .map(|entry| entry.gas_refund), _ => None, } } fn consume_verifier_entry(&mut self, tx_index: u64) { if let Self::Verifying { payload, next_entry, .. } = self { if payload .gas_refund_entries .get(*next_entry) .is_some_and(|entry| entry.index == tx_index) { *next_entry += 1; } } } fn verify_post_exec_tx( &mut self, tx_index: u64, payload: &PostExecPayload, ) -> Result<(), String> { match self { Self::Verifying { payload: expected, saw_post_exec_tx, .. } => { if *saw_post_exec_tx { return Err(format!("duplicate post-exec tx at index {tx_index}")); } if payload != expected { return Err(format!("post-exec tx payload mismatch at index {tx_index}")); } *saw_post_exec_tx = true; Ok(()) } Self::Producing { .. } => Ok(()), Self::Disabled => Err(format!( "unexpected post-exec tx at index {tx_index}: SDM not active for this block" )), Self::Invalid { reason } => Err(reason.clone()), } } /// Moves the verifier cursor past the entries for transactions `[0, first_tx_index)`, which a /// resumed executor never runs. fn skip_verifier_entries_before(&mut self, first_tx_index: u64) { if let Self::Verifying { payload, next_entry, .. } = self { *next_entry = payload.gas_refund_entries.partition_point(|entry| entry.index < first_tx_index); } } fn remaining_verifier_indexes(&self) -> Vec { match self { Self::Verifying { payload, next_entry, .. } => { payload.gas_refund_entries[*next_entry..].iter().map(|entry| entry.index).collect() } _ => Vec::new(), } } /// Whether a `Verify` block claims a post-exec payload yet never carried the trailing `0x7D`. /// /// Per-tx settlement drains the verifier entries as the refunded txs commit, so an absent /// `0x7D` is invisible to the unconsumed-entries check — only this flag proves the producer /// actually committed the claimed refunds on-chain. const fn missing_post_exec_tx(&self) -> bool { matches!(self, Self::Verifying { saw_post_exec_tx: false, .. }) } } /// Context for OP block execution. #[derive(Debug, Default, Clone)] pub struct OpBlockExecutionCtx { /// Parent block hash. pub parent_hash: B256, /// Whether this block is the activation block of some fork at or after Jovian, which must /// contain only deposit transactions. /// /// Compute via [`OpHardforks::is_no_user_tx_activation_block`] where the parent timestamp is /// available; `false` skips the executor's check. pub no_user_tx_activation_block: bool, /// Parent beacon block root. pub parent_beacon_block_root: Option, /// The block's extra data. pub extra_data: Bytes, /// Canonical post-exec execution mode for this block. pub post_exec_mode: PostExecMode, } /// Balance patch that reconciles fee distribution with the post-refund gas used. /// /// The EVM has already paid fees out based on `evm_gas_used`, so just lowering `gas_used` in the /// receipt isn't enough — the sender, beneficiary, base-fee recipient, and operator-fee recipient /// all need their balances rolled back to match the canonical gas. This struct carries the /// per-recipient debits, plus the matching credit to the sender (which equals their sum). #[derive(Debug, Default, Clone)] pub struct PostExecAdjustment { /// Refund amount subtracted from `evm_gas_used` to produce `canonical_gas_used`. pub refund: u64, /// Wei to credit back to the sender (sum of the three recipient deltas below). pub sender_balance_delta: U256, /// Wei to debit from the block beneficiary — priority-fee share of the refund. pub beneficiary_balance_delta: U256, /// Wei to debit from the base-fee recipient — base-fee share of the refund. pub base_fee_balance_delta: U256, /// Wei to debit from the operator-fee recipient — operator-fee share of the refund /// (post-Isthmus). pub operator_fee_balance_delta: U256, /// Exact policy-provided attribution events that produced the refund. pub refund_events: Vec, } /// The result of executing an OP transaction. #[derive(Debug)] pub struct OpTxResult { /// The inner result of the transaction execution. pub inner: EthTxResult, /// Whether the transaction is a deposit transaction. pub is_deposit: bool, /// Whether the transaction is a post-exec transaction. pub is_post_exec: bool, /// Gas used by EVM execution before any post-exec (SDM) refund — the "real compute" performed. /// /// Accumulated and bounded against the block gas limit by both block builders and the executor /// (see [`PreRefundGasUsed`]). pub evm_gas_used: u64, /// Canonical gas used after any post-exec adjustment. pub canonical_gas_used: u64, /// Canonical post-exec adjustment, if any. pub post_exec: Option, /// Cached depositor nonce — looked up during execute so commit can be infallible. /// `Some` only for regolith deposit transactions. pub depositor_nonce: Option, } /// Read access to a transaction's pre-refund EVM gas usage. /// /// Lets block builders read `evm_gas_used` through the generic [`BlockExecutor::Result`] type /// (otherwise only bounded by `TxResult`) to self-limit a block against the block gas limit. pub trait PreRefundGasUsed { /// Gas used by EVM execution, before any post-exec (SDM) refund. fn evm_gas_used(&self) -> u64; } impl PreRefundGasUsed for OpTxResult { fn evm_gas_used(&self) -> u64 { self.evm_gas_used } } impl TxResult for OpTxResult where H: Send + 'static, T: Send + 'static, { type HaltReason = H; fn result(&self) -> &ResultAndState { &self.inner.result } fn into_result(self) -> ResultAndState { self.inner.result } } /// Block executor for Optimism. #[derive(Debug)] pub struct OpBlockExecutor { /// Spec. pub spec: Spec, /// Receipt builder. pub receipt_builder: R, /// Context for block execution. pub ctx: OpBlockExecutionCtx, /// The EVM used by executor. pub evm: Evm, /// Receipts of executed transactions. pub receipts: Vec, /// Total gas used by executed transactions. pub gas_used: u64, /// Total pre-refund EVM gas (real compute) across executed txs, before any post-exec (SDM) /// refund. Bounded by the block gas limit; equals [`Self::gas_used`] with SDM off, greater /// otherwise. pub evm_gas_used: u64, /// Da footprint. /// /// This is only set for blocks post-Jovian activation. /// See [DA footprint block limit spec](https://github.com/ethereum-optimism/specs/blob/main/specs/protocol/jovian/exec-engine.md#da-footprint-block-limit) pub da_footprint_used: u64, /// Whether Regolith hardfork is active. pub is_regolith: bool, /// Utility to call system smart contracts. pub system_caller: SystemCaller, /// Cached L1 block info for the current block. pub l1_block_info: Option, /// Post-exec execution state (mode and producer/verifier working state). pub post_exec: PostExecState, /// Per-transaction exact policy-provided refund attribution events aligned with receipts /// (so, after [`Self::resume_at_tx_index`], with this executor's transactions only). pub refund_events_by_tx: Vec>, /// Block index of the first transaction this executor runs: non-zero only after /// [`Self::resume_at_tx_index`]. pub first_tx_index: u64, } impl OpBlockExecutor where E: Evm, R: OpReceiptBuilder, Spec: OpHardforks + Clone, { /// Creates a new [`OpBlockExecutor`]. pub fn new(evm: E, ctx: OpBlockExecutionCtx, spec: Spec, receipt_builder: R) -> Self { let post_exec = PostExecState::new(ctx.post_exec_mode.clone()); Self { is_regolith: spec .is_regolith_active_at_timestamp(evm.block().timestamp().saturating_to()), evm, system_caller: SystemCaller::new(spec.clone()), spec, receipt_builder, receipts: Vec::new(), gas_used: 0, evm_gas_used: 0, da_footprint_used: 0, ctx, l1_block_info: None, post_exec, refund_events_by_tx: Vec::new(), first_tx_index: 0, } } /// Resumes the block at transaction index `first_tx_index`, after a prefix that another /// executor ran. /// /// The caller supplies the prefix's post-state as this executor's prestate and does not call /// [`BlockExecutor::apply_pre_execution_changes`], which the prefix already applied. In /// `Verify` mode the payload's entries for indexes below `first_tx_index` count as applied, so /// the prefix must have run against exactly those entries. Receipts, refund events and gas /// totals, including the block gas and DA admission budgets, cover only the transactions this /// executor runs. /// /// # Errors /// /// Returns the payload-level errors that /// [`BlockExecutor::apply_pre_execution_changes`] would have raised, or an error in `Produce` /// mode, whose produced entries and refund-inspector state can't be rebuilt from a prestate. pub fn resume_at_tx_index(&mut self, first_tx_index: u64) -> Result<(), BlockExecutionError> { if self.post_exec.is_producing() { return Err(BlockExecutionError::msg( "cannot resume a post-exec producer mid-block: its entries and refund state are lost", )); } if let Some(reason) = self.post_exec.invalid_reason() { return Err(validation_error(OpBlockExecutionError::InvalidPostExecPayload( String::from(reason), ))); } let block_number = self.evm.block().number().saturating_to::(); if let Some(reason) = self.post_exec.verify_block_number(block_number) { return Err(validation_error(OpBlockExecutionError::InvalidPostExecPayload(reason))); } self.first_tx_index = first_tx_index; self.post_exec.skip_verifier_entries_before(first_tx_index); Ok(()) } /// Set the post-exec execution mode for the executor. #[must_use] pub fn with_post_exec_mode(mut self, post_exec_mode: PostExecMode) -> Self { self.set_post_exec_mode(post_exec_mode); self } /// Set the post-exec execution mode for the executor. /// /// This is primarily intended for tests and replay tooling that need to override the /// block-context default after construction. pub fn set_post_exec_mode(&mut self, post_exec_mode: PostExecMode) { self.post_exec = PostExecState::new(post_exec_mode); } /// Returns the accumulated post-exec entries (sequencer mode) without clearing them. pub const fn post_exec_entries(&self) -> &[SDMGasEntry] { self.post_exec.produced_entries() } /// Take the accumulated post-exec entries (sequencer mode). /// Returns the entries and clears the internal state. pub fn take_post_exec_entries(&mut self) -> Vec { self.post_exec.take_entries() } /// Take the exact per-transaction policy-provided refund events aligned with receipts. pub fn take_refund_events_by_tx(&mut self) -> Vec> { core::mem::take(&mut self.refund_events_by_tx) } } /// Returns whether `err` shows that the block's transactions are invalid, rather than a failure of /// the node that executes it. /// /// A derived block that fails with such an error is replaced with its deposits-only block. The /// fault proof program and op-reth's payload builder both decide with this function, so that they /// replace the same blocks. A node-local failure classified as invalid would derive a wrong /// deposits-only block, so every other error is not. pub fn is_invalid_payload_error(err: &BlockExecutionError) -> bool { // Exhaustive, so a new variant must be classified: one that defaults to node-local would stall // derivation on every node. match err { BlockExecutionError::Validation(validation) => match validation { BlockValidationError::InvalidTx { .. } | BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { .. } | BlockValidationError::BlockGasExceeded => true, // The OP executor boxes only `OpBlockExecutionError` into `Other`. Any other type is // unclassified and so node-local. BlockValidationError::Other(err) => { err.downcast_ref::().is_some_and(|err| match err { OpBlockExecutionError::TransactionDaFootprintAboveGasLimit { .. } | OpBlockExecutionError::UnexpectedNonDepositTxInForkActivationBlock | OpBlockExecutionError::InvalidPostExecPayload(_) | OpBlockExecutionError::PostExecSettlementUnderflow { .. } => true, }) } BlockValidationError::EVM { .. } | BlockValidationError::IncrementBalanceFailed | BlockValidationError::MissingParentBeaconBlockRoot | BlockValidationError::CancunGenesisParentBeaconBlockRootNotZero { .. } | BlockValidationError::BeaconRootContractCall { .. } | BlockValidationError::BlockHashContractCall { .. } | BlockValidationError::WithdrawalRequestsContractCall { .. } | BlockValidationError::ConsolidationRequestsContractCall { .. } | BlockValidationError::BuilderDepositRequestsContractCall { .. } | BlockValidationError::BuilderExitRequestsContractCall { .. } | BlockValidationError::DepositRequestDecode(_) => false, }, BlockExecutionError::Internal( InternalBlockExecutionError::EVM { .. } | InternalBlockExecutionError::Other(_), ) => false, } } /// Custom errors that can occur during OP block execution. /// /// Each variant is caused by the block's transactions (see [`is_invalid_payload_error`]). A failure /// of the node, such as a database read, must use [`BlockExecutionError::other`] instead. #[derive(Debug, thiserror::Error)] pub enum OpBlockExecutionError { /// Transaction DA footprint exceeds available block DA footprint. #[error( "transaction DA footprint exceeds available block DA footprint. transaction_da_footprint: {transaction_da_footprint}, available_block_da_footprint: {available_block_da_footprint}" )] TransactionDaFootprintAboveGasLimit { /// The DA footprint of the transaction to execute. transaction_da_footprint: u64, /// The available block DA footprint. available_block_da_footprint: u64, }, /// A fork-activation block at or after Jovian, which must contain only deposit transactions, /// contained a non-deposit (user) transaction. #[error("unexpected non-deposit transactions in fork activation block")] UnexpectedNonDepositTxInForkActivationBlock, /// The block contained an invalid post-exec payload. #[error("invalid post-exec payload: {0}")] InvalidPostExecPayload(String), /// Canonical post-exec settlement would underflow an account balance. #[error("canonical post-exec settlement underflow for {address}: delta {delta}")] PostExecSettlementUnderflow { /// Account whose balance would underflow. address: Address, /// Delta that could not be removed from the account. delta: U256, }, } impl OpBlockExecutor where E: Evm< DB: Database + DatabaseCommit + StateDB, Tx: FromRecoveredTx + FromTxWithEncoded + OpTxEnv, >, R: OpReceiptBuilder< Transaction: Transaction + Encodable2718 + OpConsensusTransaction, Receipt: TxReceipt, >, Spec: OpHardforks, { fn jovian_da_footprint_estimation( &mut self, tx_env: &E::Tx, tx: impl RecoveredTx, ) -> Result { // Load the L1 block contract into the cache. If the L1 block contract is not pre-loaded the // database will panic when trying to fetch the DA footprint gas scalar. self.evm.db_mut().basic(L1_BLOCK_CONTRACT).map_err(BlockExecutionError::other)?; let da_footprint_gas_scalar = L1BlockInfo::fetch_da_footprint_gas_scalar(self.evm.db_mut()) .map_err(BlockExecutionError::other)? .into(); // Use the cached enveloped tx bytes if available, otherwise encode the transaction. Ok(tx_env.encoded_bytes().map_or_else( || tx_da_footprint(tx.tx(), da_footprint_gas_scalar), |encoded| encoded_tx_da_footprint(encoded, da_footprint_gas_scalar), )) } fn invalid_post_exec_payload(reason: impl Into) -> BlockExecutionError { validation_error(OpBlockExecutionError::InvalidPostExecPayload(reason.into())) } fn verifier_post_exec_refund_for_tx( &self, tx_index: u64, is_deposit: bool, is_post_exec: bool, evm_gas_used: u64, ) -> Result { // Entry-existence first: deposit and post-exec txs are called with this helper // unconditionally to validate their tx index against the payload, so we can only // raise the deposit/post-exec error when the payload actually targets them. let Some(refund) = self.post_exec.verifier_refund(tx_index) else { return Ok(0); }; if is_deposit { return Err(Self::invalid_post_exec_payload(format!( "payload entry targets deposit tx index {tx_index}" ))); } if is_post_exec { return Err(Self::invalid_post_exec_payload(format!( "payload entry targets post-exec tx index {tx_index}" ))); } if refund > evm_gas_used { return Err(Self::invalid_post_exec_payload(format!( "payload refund {refund} exceeds evm_gas_used {evm_gas_used} for tx index {tx_index}" ))); } Ok(refund) } /// Applies the post-exec refund to the result gas so `tx_gas_used()` reports canonical gas. /// /// The EVM refund counter stays unchanged to avoid subtracting the refund twice. EIP-7623 is /// part of `evm_gas_used`, so SDM applies after its floor and may reduce canonical gas below /// that floor. Reducing both `total_gas_spent` and `floor_gas` preserves this ordering in the /// generic [`revm::context::result::ResultGas`] view used by receipts, tracing, and execution /// observers. const fn canonicalize_result_gas( result: &mut ExecutionResult, post_exec_refund: u64, ) { if post_exec_refund == 0 { return; } match result { ExecutionResult::Success { gas, .. } | ExecutionResult::Revert { gas, .. } | ExecutionResult::Halt { gas, .. } => { *gas = gas .with_total_gas_spent(gas.total_gas_spent().saturating_sub(post_exec_refund)) .with_floor_gas(gas.floor_gas().saturating_sub(post_exec_refund)); } } } fn state_account_mut<'a>( db: &mut E::DB, state: &'a mut EvmState, address: Address, ) -> Result<&'a mut Account, BlockExecutionError> { use revm::primitives::hash_map::Entry; match state.entry(address) { Entry::Occupied(entry) => Ok(entry.into_mut()), Entry::Vacant(entry) => { let info = db.basic(address).map_err(BlockExecutionError::other)?.unwrap_or_default(); // Account::from sets original_info equal to the current info, which is // safe: it is not used by State::commit — the CacheAccount tracks its // own previous state for building transitions. let mut account = Account::from(info); account.status = AccountStatus::Touched; Ok(entry.insert(account)) } } } fn add_state_balance( db: &mut E::DB, state: &mut EvmState, address: Address, delta: U256, ) -> Result<(), BlockExecutionError> { if delta.is_zero() { return Ok(()); } let account = Self::state_account_mut(db, state, address)?; account.mark_touch(); account.info.balance = account.info.balance.saturating_add(delta); Ok(()) } fn sub_state_balance( db: &mut E::DB, state: &mut EvmState, address: Address, delta: U256, ) -> Result<(), BlockExecutionError> { if delta.is_zero() { return Ok(()); } let account = Self::state_account_mut(db, state, address)?; account.mark_touch(); account.info.balance = account.info.balance.checked_sub(delta).ok_or_else(|| { BlockExecutionError::Validation(BlockValidationError::Other(Box::new( OpBlockExecutionError::PostExecSettlementUnderflow { address, delta }, ))) })?; Ok(()) } fn l1_block_info( &mut self, spec_id: op_revm::OpSpecId, ) -> Result { if let Some(l1_block_info) = &self.l1_block_info { return Ok(l1_block_info.clone()); } let block_number = self.evm.block().number(); let l1_block_info = L1BlockInfo::try_fetch(self.evm.db_mut(), block_number, spec_id) .map_err(BlockExecutionError::other)?; self.l1_block_info = Some(l1_block_info.clone()); Ok(l1_block_info) } /// Computes the fee-settlement patch required after canonicalizing post-exec gas. /// /// `evm.transact` has already charged the sender and paid fee recipients according to /// `evm_gas_used`. Lowering only the receipt's `gas_used` would leave those balance changes /// in place. This translates the refunded gas back into the exact per-recipient deltas /// `execute_transaction_without_commit` then applies before state is committed. fn post_exec_settlement_deltas( &mut self, tx: impl RecoveredTx, evm_gas_used: u64, post_exec_refund: u64, is_deposit: bool, is_post_exec: bool, ) -> Result { if is_deposit || is_post_exec || post_exec_refund == 0 { return Ok(PostExecAdjustment::default()); } let gas_delta_u256 = U256::from(post_exec_refund); let basefee = u128::from(self.evm.block().basefee()); let spec_id = spec_by_timestamp_after_bedrock( &self.spec, self.evm.block().timestamp().saturating_to(), ); let effective_gas_price = tx.tx().effective_gas_price(Some(self.evm.block().basefee())); // SDM/PostExec is only enabled on forks after Karst, which is already post-London. // A saturating_sub landing at zero is intentional and consensus-valid: a legacy tx // with a gas price equal to the basefee pays zero priority fee, so the beneficiary // delta below must be zero as well — we credit back only what the beneficiary // actually received for the refunded gas, which is the (effective_price - basefee) // component. let beneficiary_gas_price = effective_gas_price.saturating_sub(basefee); let base_fee_balance_delta = gas_delta_u256.saturating_mul(U256::from(basefee)); let beneficiary_balance_delta = gas_delta_u256.saturating_mul(U256::from(beneficiary_gas_price)); let canonical_gas_used = evm_gas_used.saturating_sub(post_exec_refund); let l1_block_info = self.l1_block_info(spec_id)?; let encoded = tx.tx().encoded_2718(); let raw_fee = l1_block_info.operator_fee_charge(encoded.as_ref(), U256::from(evm_gas_used), spec_id); let canonical_fee = l1_block_info.operator_fee_charge( encoded.as_ref(), U256::from(canonical_gas_used), spec_id, ); let operator_fee_balance_delta = raw_fee.saturating_sub(canonical_fee); let sender_balance_delta = gas_delta_u256 .saturating_mul(U256::from(effective_gas_price)) .saturating_add(operator_fee_balance_delta); Ok(PostExecAdjustment { refund: post_exec_refund, sender_balance_delta, beneficiary_balance_delta, base_fee_balance_delta, operator_fee_balance_delta, refund_events: Vec::new(), }) } fn apply_post_exec_refund_to_state( &mut self, state: &mut EvmState, sender: Address, deltas: &PostExecAdjustment, ) -> Result<(), BlockExecutionError> { let beneficiary = self.evm.block().beneficiary(); Self::add_state_balance(self.evm.db_mut(), state, sender, deltas.sender_balance_delta)?; Self::sub_state_balance( self.evm.db_mut(), state, beneficiary, deltas.beneficiary_balance_delta, )?; Self::sub_state_balance( self.evm.db_mut(), state, BASE_FEE_RECIPIENT, deltas.base_fee_balance_delta, )?; Self::sub_state_balance( self.evm.db_mut(), state, OPERATOR_FEE_RECIPIENT, deltas.operator_fee_balance_delta, )?; Ok(()) } } /// Ensures a transaction's gas limit fits within the gas still available in the block. /// /// Checks one condition at a time: pre-Regolith deposits are exempt from this check, and any /// other transaction must not declare more gas than remains in the block. fn validate_block_gas( transaction_gas_limit: u64, block_available_gas: u64, is_regolith: bool, is_deposit: bool, ) -> Result<(), BlockExecutionError> { // Pre-Regolith deposits are exempt from the available-block-gas check. if is_deposit && !is_regolith { return Ok(()); } if transaction_gas_limit > block_available_gas { return Err(BlockValidationError::TransactionGasLimitMoreThanAvailableBlockGas { transaction_gas_limit, block_available_gas, } .into()); } Ok(()) } impl OpBlockExecutor where E: PostExecEvm, R: OpReceiptBuilder, { /// Rolls the refund policy back to the checkpoint taken before a candidate, if one was taken. /// /// A failed revert outranks whatever made the candidate fail: the policy's block-scoped state /// is unspecified from then on, so a caller must not skip the candidate and carry on. fn revert_refund_checkpoint( &mut self, refund_checkpoint: Option, ) -> Result<(), BlockExecutionError> { refund_checkpoint.map_or(Ok(()), |checkpoint| { self.evm.revert_refund_checkpoint(checkpoint).map_err(BlockExecutionError::other) }) } } /// UPSTREAM-MIRROR(copy): alloy-evm@0.39.0 `alloy_evm::eth::block::EthBlockExecutor` /// /// Mirrors upstream's `BlockExecutor` impl, reusing its `EthTxResult` for the inner result /// but reimplementing every method. Known divergences to re-confirm on each bump: upstream /// tracks regular and state block gas separately and returns `GasOutput::with_state_gas`, /// this tracks `gas_used`/`evm_gas_used` and returns `GasOutput::new`; upstream's admission /// check clamps the transaction gas limit by `cfg.tx_gas_limit_cap`, `validate_block_gas` /// does not. Upstream's Amsterdam state-gas capacity check is inapplicable until an OP fork maps /// to Amsterdam semantics. impl BlockExecutor for OpBlockExecutor where E: PostExecEvm< DB: Database + DatabaseCommit + StateDB, Tx: FromRecoveredTx + FromTxWithEncoded + OpTxEnv, HaltReason: Send + 'static, >, R: OpReceiptBuilder< Transaction: Transaction + Encodable2718 + OpConsensusTransaction, Receipt: TxReceipt, >, Spec: OpHardforks, { type Transaction = R::Transaction; type Receipt = R::Receipt; type Evm = E; type Result = OpTxResult::TxType>; fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { if let Some(reason) = self.post_exec.invalid_reason() { return Err(Self::invalid_post_exec_payload(String::from(reason))); } let block_number = self.evm.block().number().saturating_to::(); if let Some(reason) = self.post_exec.verify_block_number(block_number) { return Err(Self::invalid_post_exec_payload(reason)); } self.system_caller.apply_blockhashes_contract_call(self.ctx.parent_hash, &mut self.evm)?; self.system_caller .apply_beacon_root_contract_call(self.ctx.parent_beacon_block_root, &mut self.evm)?; // Ensure that the create2deployer is force-deployed at the canyon transition. Optimism // blocks will always have at least a single transaction in them (the L1 info transaction), // so we can safely assume that this will always be triggered upon the transition and that // the above check for empty blocks will never be hit on OP chains. ensure_create2_deployer( &self.spec, self.evm.block().timestamp().saturating_to(), self.evm.db_mut(), ) .map_err(BlockExecutionError::other)?; Ok(()) } fn execute_transaction_with_commit_condition( &mut self, tx: impl ExecutableTx, f: impl FnOnce(&Self::Result) -> CommitChanges, ) -> Result, BlockExecutionError> { // Producer policy state is updated during EVM execution (before the commit decision) and // is not journaled with EVM state. A declined candidate must not affect a later committed // transaction, or the producer's payload can diverge from commit-only derivation paths. // Checkpoint only in Produce mode and revert on decline or execution error. This runs for // every candidate, which is why the policy contract requires an O(1) checkpoint. let refund_checkpoint = self.post_exec.is_producing().then(|| self.evm.refund_checkpoint()); let output = match self.execute_transaction_without_commit(tx) { Ok(output) => output, Err(err) => { self.revert_refund_checkpoint(refund_checkpoint)?; return Err(err); } }; if !f(&output).should_commit() { self.revert_refund_checkpoint(refund_checkpoint)?; return Ok(None); } Ok(Some(self.commit_transaction(output))) } /// In Produce mode, this method does not checkpoint or revert producer-policy state. A failing /// transaction still records its fee-vault touches on the `transact_raw` error path, and a /// successfully executed transaction does the same even if its commit is later declined. /// Callers that may discard a candidate must checkpoint and revert the policy themselves, via /// [`PostExecEvm::refund_checkpoint`] and [`PostExecEvm::revert_refund_checkpoint`], or use /// [`execute_transaction_with_commit_condition`](Self::execute_transaction_with_commit_condition), /// which reverts to the per-candidate checkpoint on execution error and declined commit. fn execute_transaction_without_commit( &mut self, tx: impl ExecutableTx, ) -> Result { let (tx_env, tx) = tx.into_parts(); let is_deposit = tx.tx().ty() == DEPOSIT_TRANSACTION_TYPE; let is_post_exec = tx.tx().ty() == POST_EXEC_TX_TYPE_ID; let tx_index = self.first_tx_index + self.receipts.len() as u64; // Since Jovian, fork-activation blocks must contain only deposit transactions — before, // the sequencer skipped user txs there by policy, but it wasn't a consensus rule. The // synthetic post-exec SDM tx is not a user tx, so it is allowed. if self.ctx.no_user_tx_activation_block && !is_deposit && !is_post_exec { return Err(validation_error( OpBlockExecutionError::UnexpectedNonDepositTxInForkActivationBlock, )); } let transaction_gas_limit = tx.tx().gas_limit(); // Bound the block's *pre-refund* `evm_gas_used` (real compute) rather than canonical // `gas_used`, so SDM refunds can't admit more compute than the block gas limit allows. // Inducting off the declared gas limit (an upper bound on actual `evm_gas_used`) keeps the // pre-refund sum within the limit. Since `evm_gas_used >= gas_used`, this subsumes the // canonical block-gas-limit check; with SDM off the two are identical. let evm_gas_available = self.evm.block().gas_limit().saturating_sub(self.evm_gas_used); validate_block_gas(transaction_gas_limit, evm_gas_available, self.is_regolith, is_deposit)?; if is_post_exec { let payload = tx.tx().as_post_exec().map(|tx| &tx.inner().payload).ok_or_else(|| { Self::invalid_post_exec_payload(format!( "transaction at index {tx_index} has post-exec type but no post-exec payload", )) })?; if let Err(reason) = self.post_exec.verify_post_exec_tx(tx_index, payload) { return Err(Self::invalid_post_exec_payload(reason)); } // Validates that no Verify payload entry targets this tx index; refund is always 0. self.verifier_post_exec_refund_for_tx(tx_index, false, true, 0)?; return Ok(OpTxResult { inner: EthTxResult { result: noop_post_exec_result(), blob_gas_used: 0, tx_type: tx.tx().tx_type(), }, is_deposit: false, is_post_exec: true, evm_gas_used: 0, canonical_gas_used: 0, post_exec: None, depositor_nonce: None, }); } let da_footprint_used = if self .spec .is_jovian_active_at_timestamp(self.evm.block().timestamp().saturating_to()) && !is_deposit { let da_footprint_available = self.evm.block().gas_limit().saturating_sub(self.da_footprint_used); let tx_da_footprint = self.jovian_da_footprint_estimation(&tx_env, &tx)?; if tx_da_footprint > da_footprint_available { return Err(validation_error( OpBlockExecutionError::TransactionDaFootprintAboveGasLimit { transaction_da_footprint: tx_da_footprint, available_block_da_footprint: da_footprint_available, }, )); } tx_da_footprint } else { 0 }; if self.post_exec.is_producing() { self.evm.begin_post_exec_tx(PostExecTxContext { tx_index, kind: if is_deposit { PostExecTxKind::Deposit } else { PostExecTxKind::Normal }, }); } // Execute transaction and return the result let mut result = self.evm.transact(tx_env).map_err(|err| { let hash = tx.tx().trie_hash(); BlockExecutionError::evm(err, hash) })?; let evm_gas_used = result.result.tx_gas_used(); let (post_exec_refund, refund_events) = if self.post_exec.is_producing() { let PostExecExecutedTx { refund_total: refund, refund_events } = self.evm.take_last_post_exec_tx_result(); // The policy is advisory. Contain a faulty policy here, before its output changes gas, // settlement, receipts, or the trailing payload: excessive normal-tx refunds are // discarded, refunds are clipped to their net saving, and deposits never receive a // refund. let max_refund_quotient = self.evm.cfg_env().gas_params.max_refund_quotient(); let refund = sanitize_producer_refund( refund, result.result.gas(), max_refund_quotient, is_deposit, ); (refund, refund_events) } else { ( self.verifier_post_exec_refund_for_tx(tx_index, is_deposit, false, evm_gas_used)?, Vec::new(), ) }; let canonical_gas_used = evm_gas_used.saturating_sub(post_exec_refund); let mut deltas = self.post_exec_settlement_deltas( &tx, evm_gas_used, post_exec_refund, is_deposit, false, )?; deltas.refund_events = refund_events; let post_exec = (post_exec_refund > 0 || !deltas.refund_events.is_empty()).then_some(deltas); // Pre-compute depositor nonce here so `commit_transaction` can be infallible. // Only post-regolith deposit transactions need the depositor account from DB. let sender = *tx.signer(); let depositor_nonce = if self.is_regolith && is_deposit { let account = self .evm .db_mut() .basic(sender) .map_err(BlockExecutionError::other)? .unwrap_or_default(); Some(account.nonce) } else { None }; // Canonicalize the result gas and apply any post-exec refund to state in-place. Both // operations must run before commit so commit_transaction stays infallible. Self::canonicalize_result_gas(&mut result.result, post_exec_refund); if let Some(deltas) = post_exec.as_ref() { self.apply_post_exec_refund_to_state(&mut result.state, sender, deltas)?; } Ok(OpTxResult { inner: EthTxResult { result, blob_gas_used: da_footprint_used, tx_type: tx.tx().tx_type(), }, is_deposit, is_post_exec: false, evm_gas_used, canonical_gas_used, post_exec, depositor_nonce, }) } fn commit_transaction(&mut self, output: Self::Result) -> GasOutput { let tx_index = self.first_tx_index + self.receipts.len() as u64; let OpTxResult { inner: EthTxResult { result: ResultAndState { result, state }, blob_gas_used, tx_type }, is_deposit, is_post_exec, evm_gas_used, canonical_gas_used, post_exec, depositor_nonce, } = output; let (post_exec_refund, refund_events) = match post_exec { Some(deltas) => (deltas.refund, deltas.refund_events), None => (0, Vec::new()), }; if !is_deposit && !is_post_exec && post_exec_refund > 0 { if let Some(entries) = self.post_exec.produced_entries_mut() { entries.push(SDMGasEntry { index: tx_index, gas_refund: post_exec_refund }); } } if self.post_exec.is_verifying() && post_exec_refund > 0 { self.post_exec.consume_verifier_entry(tx_index); } if !is_post_exec { self.refund_events_by_tx.push(refund_events); } // add canonical gas used self.gas_used += canonical_gas_used; // Accumulate pre-refund EVM gas (real compute); bounded against the block gas limit by the // admission check in `execute_transaction_without_commit`. self.evm_gas_used += evm_gas_used; // Update DA footprint if Jovian is active if self.spec.is_jovian_active_at_timestamp(self.evm.block().timestamp().saturating_to()) && !is_deposit && !is_post_exec { // Add to DA footprint used self.da_footprint_used = self.da_footprint_used.saturating_add(blob_gas_used); } self.receipts.push( match self.receipt_builder.build_receipt(ReceiptBuilderCtx { tx_type, result, cumulative_gas_used: self.gas_used, evm: &self.evm, state: &state, }) { Ok(receipt) => receipt, Err(ctx) => { let receipt = alloy_consensus::Receipt { // Success flag was added in `EIP-658: Embedding transaction status code // in receipts`. status: Eip658Value::Eip658(ctx.result.is_success()), cumulative_gas_used: self.gas_used, logs: ctx.result.into_logs(), }; self.receipt_builder.build_deposit_receipt(OpDepositReceipt { inner: receipt, deposit_nonce: depositor_nonce, // The deposit receipt version was introduced in Canyon to indicate an // update to how receipt hashes should be computed // when set. The state transition process ensures // this is only set for post-Canyon deposit // transactions. deposit_receipt_version: (is_deposit && self.spec.is_canyon_active_at_timestamp( self.evm.block().timestamp().saturating_to(), )) .then_some(1), }) } }, ); self.evm.db_mut().commit(state); GasOutput::new(canonical_gas_used) } fn finish( mut self, ) -> Result<(Self::Evm, BlockExecutionResult), BlockExecutionError> { let indexes = self.post_exec.remaining_verifier_indexes(); if !indexes.is_empty() { return Err(Self::invalid_post_exec_payload(format!( "{} unconsumed post-exec payload entries for tx indexes {:?}", indexes.len(), indexes, ))); } if self.post_exec.missing_post_exec_tx() { return Err(Self::invalid_post_exec_payload( "post-exec payload present but block carries no post-exec tx", )); } let balance_increments = post_block_balance_increments::
(&self.spec, self.evm.block(), &[], None); // increment balances; the DB-level state hook (if any) fires via the commit inside. self.evm .db_mut() .increment_balances(balance_increments) .map_err(|_| BlockValidationError::IncrementBalanceFailed)?; Ok(( self.evm, BlockExecutionResult { receipts: self.receipts, requests: Requests::default(), gas_used: self.gas_used, blob_gas_used: self.da_footprint_used, }, )) } fn evm_mut(&mut self) -> &mut Self::Evm { &mut self.evm } fn evm(&self) -> &Self::Evm { &self.evm } fn receipts(&self) -> &[Self::Receipt] { &self.receipts } } /// Ethereum block executor factory. #[derive(Debug, Clone, Default, Copy)] pub struct OpBlockExecutorFactory< R = OpAlloyReceiptBuilder, Spec = OpChainHardforks, EvmFactory = OpEvmFactory, > { /// Receipt builder. receipt_builder: R, /// Chain specification. spec: Spec, /// EVM factory. evm_factory: EvmFactory, } impl OpBlockExecutorFactory { /// Creates a new [`OpBlockExecutorFactory`] with the given spec, [`EvmFactory`], and /// [`OpReceiptBuilder`]. pub const fn new(receipt_builder: R, spec: Spec, evm_factory: EvmFactory) -> Self { Self { receipt_builder, spec, evm_factory } } /// Exposes the receipt builder. pub const fn receipt_builder(&self) -> &R { &self.receipt_builder } /// Exposes the chain specification. pub const fn spec(&self) -> &Spec { &self.spec } /// Exposes the EVM factory. pub const fn evm_factory(&self) -> &EvmFactory { &self.evm_factory } } impl BlockExecutorFactory for OpBlockExecutorFactory> where R: OpReceiptBuilder< Transaction: Transaction + Encodable2718 + OpConsensusTransaction, Receipt: TxReceipt, > + 'static, Spec: OpHardforks + 'static, F: PostExecEvmFactoryHooks + 'static, F::Tx: FromRecoveredTx + FromTxWithEncoded + OpTxEnv, Self: 'static, { type EvmFactory = PostExecEvmFactoryAdapter; type ExecutionCtx<'a> = OpBlockExecutionCtx; type Transaction = R::Transaction; type Receipt = R::Receipt; type TxExecutionResult = OpTxResult< as EvmFactory>::HaltReason, ::TxType, >; type Executor< 'a, DB: StateDB, I: Inspector< as EvmFactory>::Context>, > = OpBlockExecutor< as EvmFactory>::Evm, &'a R, &'a Spec>; fn evm_factory(&self) -> &Self::EvmFactory { &self.evm_factory } fn create_executor<'a, DB, I>( &'a self, evm: as EvmFactory>::Evm, ctx: Self::ExecutionCtx<'a>, ) -> Self::Executor<'a, DB, I> where DB: StateDB, I: Inspector< as EvmFactory>::Context>, { OpBlockExecutor::new(evm, ctx, &self.spec, &self.receipt_builder) } } impl BlockExecutorFactory for OpBlockExecutorFactory> where ReceiptBuilder: OpReceiptBuilder< Transaction: Transaction + Encodable2718 + OpConsensusTransaction, Receipt: TxReceipt, > + 'static, Spec: OpHardforks + 'static, Tx: IntoTxEnv + Into> + Default + Clone + core::fmt::Debug + FromRecoveredTx + FromTxWithEncoded + OpTxEnv + 'static, RefundPolicyFactory: PostExecRefundPolicyFactory + 'static, RefundPolicyFactory::Policy: 'static, Self: 'static, { type EvmFactory = OpEvmFactory; type ExecutionCtx<'a> = OpBlockExecutionCtx; type Transaction = ReceiptBuilder::Transaction; type Receipt = ReceiptBuilder::Receipt; type TxExecutionResult = OpTxResult< ::HaltReason, ::TxType, >; type Executor<'a, DB: StateDB, I: Inspector<::Context>> = OpBlockExecutor<::Evm, &'a ReceiptBuilder, &'a Spec>; fn evm_factory(&self) -> &Self::EvmFactory { &self.evm_factory } fn create_executor<'a, DB, I>( &'a self, evm: ::Evm, ctx: Self::ExecutionCtx<'a>, ) -> Self::Executor<'a, DB, I> where DB: StateDB, I: Inspector<::Context>, { OpBlockExecutor::new(evm, ctx, &self.spec, &self.receipt_builder) } } #[cfg(test)] mod tests;