//! Custom EVM configuration and block executor for ConduitOp state transitions. //! //! Wraps the standard OP EVM config and block executor to apply state overrides //! at each state override round's activation block. use crate::{ chainspec::ConduitOpChainSpec, hardforks::ConduitOpHardforks, state_override::ensure_state_override, }; use alloy_consensus::Header; use alloy_evm::{ Database, EvmFactory, FromRecoveredTx, FromTxWithEncoded, block::{ BlockExecutionError, BlockExecutionResult, BlockExecutor, BlockExecutorFactory, CommitChanges, ExecutableTx, GasOutput, StateDB, }, }; use alloy_op_evm::{ OpBlockExecutionCtx, OpBlockExecutor, OpEvmFactory, PreRefundGasUsed, block::{OpTxEnv, receipt_builder::OpReceiptBuilder}, post_exec::{PostExecEvm, PostExecExecutorExt, PostExecRefundEvent}, }; use op_alloy_consensus::{EIP1559ParamError, SDMGasEntry}; use op_revm::OpSpecId; use reth_evm::{ ConfigureEngineEvm, ConfigureEvm, EvmEnv, EvmEnvFor, ExecutableTxIterator, ExecutionCtxFor, execute::{BasicBlockBuilder, BlockBuilder}, }; use reth_node_builder::{BuilderContext, NodeTypes, components::ExecutorBuilder}; use reth_optimism_evm::{ ConfigurePostExecEvm, OpBlockAssembler, OpBlockExecutorFactory, OpEvmConfig, OpNextBlockEnvAttributes, OpRethReceiptBuilder, OpTx, PostExecMode, }; use reth_optimism_forks::OpHardforks; use reth_optimism_payload_builder::OpExecData; use reth_optimism_primitives::OpPrimitives; use reth_primitives_traits::{NodePrimitives, SealedBlock, SealedHeader}; use revm::{ Inspector, context::Block, database::{DatabaseCommit, State}, }; use std::sync::Arc; type InnerBlockExecutorFactory = OpBlockExecutorFactory, OpEvmFactory>; /// Custom block executor wrapping [`OpBlockExecutor`]. /// /// Applies account state overrides when each state override round first activates, /// using the OP Stack 2-second block time heuristic to detect the transition block. pub struct ConduitOpBlockExecutor { inner: OpBlockExecutor, chain_spec: Arc, } impl BlockExecutor for ConduitOpBlockExecutor where E: PostExecEvm< DB: Database + DatabaseCommit + StateDB, Tx: FromRecoveredTx + FromTxWithEncoded + OpTxEnv, HaltReason: Send + 'static, >, R: OpReceiptBuilder< Transaction: alloy_consensus::Transaction + alloy_eips::Encodable2718 + op_alloy_consensus::OpTransaction, Receipt: alloy_consensus::TxReceipt, >, Spec: OpHardforks, { type Transaction = R::Transaction; type Receipt = R::Receipt; type Evm = E; type Result = as BlockExecutor>::Result; fn apply_pre_execution_changes(&mut self) -> Result<(), BlockExecutionError> { self.inner.apply_pre_execution_changes()?; // Apply state overrides at each round's transition block. Rounds are visited in // activation order, so if two transition windows ever overlap the later round wins. let timestamp = self.inner.evm.block().timestamp().saturating_to(); let chain_spec = self.chain_spec.clone(); for (fork, config) in chain_spec.state_override_forks() { ensure_state_override( chain_spec.as_ref(), fork, timestamp, config, self.inner.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> { self.inner.execute_transaction_with_commit_condition(tx, f) } fn execute_transaction_without_commit( &mut self, tx: impl ExecutableTx, ) -> Result { self.inner.execute_transaction_without_commit(tx) } fn commit_transaction(&mut self, output: Self::Result) -> GasOutput { self.inner.commit_transaction(output) } fn finish( self, ) -> Result<(Self::Evm, BlockExecutionResult), BlockExecutionError> { self.inner.finish() } fn evm_mut(&mut self) -> &mut Self::Evm { self.inner.evm_mut() } fn evm(&self) -> &Self::Evm { self.inner.evm() } fn receipts(&self) -> &[Self::Receipt] { self.inner.receipts() } } impl PostExecExecutorExt for ConduitOpBlockExecutor where E: PostExecEvm, R: OpReceiptBuilder, Spec: OpHardforks + Clone, { fn post_exec_entries(&self) -> &[SDMGasEntry] { self.inner.post_exec_entries() } fn take_post_exec_entries(&mut self) -> Vec { self.inner.take_post_exec_entries() } fn take_refund_events_by_tx(&mut self) -> Vec> { self.inner.take_refund_events_by_tx() } fn resume_at_tx_index(&mut self, first_tx_index: u64) -> Result<(), BlockExecutionError> { self.inner.resume_at_tx_index(first_tx_index) } } impl BlockExecutorFactory for ConduitOpEvmConfig { type EvmFactory = ::EvmFactory; type TxExecutionResult = ::TxExecutionResult; type ExecutionCtx<'a> = OpBlockExecutionCtx; type Transaction = ::Transaction; type Receipt = ::Receipt; type Executor<'a, DB: StateDB, I: Inspector<::Context>> = ConduitOpBlockExecutor< ::Evm, &'a OpRethReceiptBuilder, &'a Arc, >; fn evm_factory(&self) -> &Self::EvmFactory { self.inner.executor_factory.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>, { let inner = self.inner.executor_factory.create_executor(evm, ctx); ConduitOpBlockExecutor { inner, chain_spec: self.chain_spec.clone() } } } /// Custom EVM configuration wrapping [`OpEvmConfig`]. /// /// Delegates all standard OP behavior to the inner config but overrides /// `create_executor` to wrap each [`OpBlockExecutor`] in a [`ConduitOpBlockExecutor`] /// for custom state transitions. #[derive(Debug, Clone)] pub struct ConduitOpEvmConfig { inner: OpEvmConfig, chain_spec: Arc, } impl ConduitOpEvmConfig { /// Creates a new [`ConduitOpEvmConfig`]. pub fn new(chain_spec: Arc) -> Self { let inner = OpEvmConfig::new(chain_spec.clone(), OpRethReceiptBuilder::default()); Self { inner, chain_spec } } /// Returns the receipt builder used by the block executor factory. pub fn receipt_builder(&self) -> &OpRethReceiptBuilder { self.inner.executor_factory.receipt_builder() } /// Applies EvmLimitsFork0 parameters when the hardfork is active. fn maybe_apply_limits(&self, mut env: EvmEnv) -> EvmEnv { let timestamp = env.block_env.timestamp().saturating_to(); if self.chain_spec.is_evm_limits_fork0_active_at_timestamp(timestamp) && let Some(limits) = self.chain_spec.evm_limits_fork0 { if let Some(max_code_size) = limits.max_code_size { env.cfg_env.limit_contract_code_size = Some(max_code_size); } if let Some(max_initcode_size) = limits.max_initcode_size { env.cfg_env.limit_contract_initcode_size = Some(max_initcode_size); } if let Some(tx_gas_limit_cap) = limits.tx_gas_limit_cap { env.cfg_env.tx_gas_limit_cap = Some(tx_gas_limit_cap); } } env } } impl ConfigureEvm for ConduitOpEvmConfig { type Primitives = OpPrimitives; type Error = EIP1559ParamError; type NextBlockEnvCtx = OpNextBlockEnvAttributes; type BlockExecutorFactory = Self; type BlockAssembler = OpBlockAssembler; fn block_executor_factory(&self) -> &Self::BlockExecutorFactory { self } fn block_assembler(&self) -> &Self::BlockAssembler { &self.inner.block_assembler } fn evm_env(&self, header: &Header) -> Result, Self::Error> { self.inner.evm_env(header).map(|env| self.maybe_apply_limits(env)) } fn next_evm_env( &self, parent: &Header, attributes: &Self::NextBlockEnvCtx, ) -> Result, Self::Error> { self.inner.next_evm_env(parent, attributes).map(|env| self.maybe_apply_limits(env)) } fn context_for_block( &self, block: &'_ SealedBlock<::Block>, ) -> Result { self.inner.context_for_block(block) } fn context_for_next_block( &self, parent: &SealedHeader<::BlockHeader>, attributes: Self::NextBlockEnvCtx, ) -> Result { self.inner.context_for_next_block(parent, attributes) } } impl ConfigurePostExecEvm for ConduitOpEvmConfig { fn post_exec_executor_for_block<'a, DB: Database>( &'a self, db: &'a mut State, block: &'a SealedBlock<::Block>, post_exec_mode: PostExecMode, ) -> Result< impl BlockExecutor< Transaction = ::SignedTx, Receipt = ::Receipt, > + PostExecExecutorExt + 'a, Self::Error, > { let evm = self.evm_for_block(db, block.header())?; let ctx = self.inner.context_for_block_with_post_exec_mode(block, Some(post_exec_mode)); Ok(ConfigureEvm::create_executor(self, evm, ctx)) } fn post_exec_builder_for_next_block<'a, DB: Database + 'a>( &'a self, db: &'a mut State, parent: &'a SealedHeader<::BlockHeader>, attributes: Self::NextBlockEnvCtx, post_exec_mode: PostExecMode, ) -> Result< impl BlockBuilder< Primitives = Self::Primitives, Executor: PostExecExecutorExt + BlockExecutor< Evm: alloy_evm::Evm>>, Result: PreRefundGasUsed, >, > + 'a, Self::Error, > { let evm_env = self.next_evm_env(parent, &attributes)?; let evm = self.evm_with_env(db, evm_env); let ctx = self.inner.context_for_next_block_with_post_exec_mode( parent, attributes, post_exec_mode, ); let executor = ConfigureEvm::create_executor(self, evm, ctx.clone()); Ok(BasicBlockBuilder::<'a, ConduitOpEvmConfig, _, _, OpPrimitives> { executor, transactions: Vec::new(), ctx, parent, assembler: self.block_assembler(), }) } } impl ConfigureEngineEvm for ConduitOpEvmConfig { fn evm_env_for_payload(&self, payload: &OpExecData) -> Result, Self::Error> { self.inner.evm_env_for_payload(&payload.0).map(|env| self.maybe_apply_limits(env)) } fn context_for_payload<'a>( &self, payload: &'a OpExecData, ) -> Result, Self::Error> { self.inner.context_for_payload(&payload.0) } fn tx_iterator_for_payload( &self, payload: &OpExecData, ) -> Result, Self::Error> { self.inner.tx_iterator_for_payload(&payload.0) } } /// Executor builder that produces [`ConduitOpEvmConfig`]. /// /// Replaces [`OpExecutorBuilder`](reth_optimism_node::node::OpExecutorBuilder) to wire /// custom state transitions into the node. #[derive(Debug, Copy, Clone, Default)] pub struct ConduitOpExecutorBuilder; impl ExecutorBuilder for ConduitOpExecutorBuilder where Node: reth_node_builder::node::FullNodeTypes< Types: NodeTypes, >, { type EVM = ConduitOpEvmConfig; async fn build_evm(self, ctx: &BuilderContext) -> eyre::Result { Ok(ConduitOpEvmConfig::new(ctx.chain_spec())) } } #[cfg(test)] mod tests { use super::*; use crate::chainspec::ConduitOpChainSpecParser; use alloy_primitives::{Address, B256, Bytes}; use reth_cli::chainspec::ChainSpecParser; // `Cfg::tx_gas_limit_cap()` resolves the effective EIP-7825 cap. Since op-reth v2.4.2 the // spec-derived cap is no longer written into `cfg_env.tx_gas_limit_cap`, so only the raw // field reflects an explicit override and the accessor reflects what the EVM enforces. use revm::context_interface::Cfg; const TEST_MAX_CODE_SIZE: usize = 1_000_000; const TEST_MAX_INITCODE_SIZE: usize = 2_000_000; const KARST_GENESIS: &str = r#"{ "config": { "chainId": 99999, "homesteadBlock": 0, "eip150Block": 0, "eip155Block": 0, "eip158Block": 0, "byzantiumBlock": 0, "constantinopleBlock": 0, "petersburgBlock": 0, "istanbulBlock": 0, "muirGlacierBlock": 0, "berlinBlock": 0, "londonBlock": 0, "shanghaiTime": 0, "cancunTime": 0, "pragueTime": 0, "bedrockBlock": 0, "regolithTime": 0, "canyonTime": 0, "ecotoneTime": 0, "fjordTime": 0, "graniteTime": 0, "holoceneTime": 0, "isthmusTime": 0, "jovianTime": 0, "karstTime": 1000 }, "difficulty": "0x0", "gasLimit": "0x1c9c380", "alloc": {} }"#; fn with_evm_limits_fork(time: u64, limits: serde_json::Value) -> String { let mut genesis: serde_json::Value = serde_json::from_str(KARST_GENESIS).unwrap(); let mut fork = limits; if let serde_json::Value::Object(ref mut fields) = fork { fields.insert("time".to_string(), serde_json::json!(time)); } genesis["config"]["conduit"] = serde_json::json!({ "evmLimitsFork0": fork }); serde_json::to_string(&genesis).unwrap() } fn parse_genesis(json: &str, test_name: &str) -> Arc { let dir = std::env::temp_dir().join(format!("conduit-op-reth-{test_name}-test")); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("genesis.json"); std::fs::write(&path, json).unwrap(); let spec = ConduitOpChainSpecParser::parse(path.to_str().unwrap()).unwrap(); std::fs::remove_dir_all(&dir).ok(); spec } /// Regression test for Karst readiness: a genesis `karstTime` must flow through /// [`ConduitOpChainSpec`] and [`ConduitOpEvmConfig`] into the `KARST` EVM spec /// (Osaka semantics, including the EIP-7825 transaction gas cap that the tx pool /// reads via `evm_env.cfg_env.tx_gas_limit_cap()`). #[test] fn karst_genesis_flows_through_wrapper() { let dir = std::env::temp_dir().join("conduit-op-reth-karst-test"); std::fs::create_dir_all(&dir).unwrap(); let path = dir.join("genesis.json"); std::fs::write(&path, KARST_GENESIS).unwrap(); let spec = ConduitOpChainSpecParser::parse(path.to_str().unwrap()).unwrap(); std::fs::remove_dir_all(&dir).ok(); // Hardfork activation is delegated through ConduitOpChainSpec. assert!(!spec.is_karst_active_at_timestamp(999)); assert!(spec.is_karst_active_at_timestamp(1000)); assert!(spec.is_jovian_active_at_timestamp(999)); // ConduitOpEvmConfig delegates evm_env, which selects the KARST spec id. let evm_config = ConduitOpEvmConfig::new(spec); let pre = Header { timestamp: 999, gas_limit: 30_000_000, ..Default::default() }; let post = Header { timestamp: 1000, gas_limit: 30_000_000, ..Default::default() }; let env_pre = evm_config.evm_env(&pre).unwrap(); let env_post = evm_config.evm_env(&post).unwrap(); assert_eq!(env_pre.cfg_env.spec, OpSpecId::JOVIAN); assert_eq!(env_post.cfg_env.spec, OpSpecId::KARST); // The EIP-7825 tx gas cap (2^24) activates exactly at Karst. assert_eq!(env_pre.cfg_env.tx_gas_limit_cap(), u64::MAX); assert_eq!(env_post.cfg_env.tx_gas_limit_cap(), 16_777_216); } #[test] fn evm_limits_fork_applies_at_activation() { let spec = parse_genesis( &with_evm_limits_fork( 2000, serde_json::json!({ "maxCodeSize": TEST_MAX_CODE_SIZE, "maxInitcodeSize": TEST_MAX_INITCODE_SIZE, "txGasLimitCap": u64::MAX, }), ), "evm-limits", ); let before = Header { timestamp: 1999, gas_limit: 30_000_000, ..Default::default() }; let active = Header { timestamp: 2000, gas_limit: 30_000_000, ..Default::default() }; let evm_config = ConduitOpEvmConfig::new(spec); let env_before = evm_config.evm_env(&before).unwrap(); assert_eq!(env_before.cfg_env.spec, OpSpecId::KARST); assert_eq!(env_before.cfg_env.limit_contract_code_size, None); assert_eq!(env_before.cfg_env.limit_contract_initcode_size, None); // No override before activation, so the EIP-7825 cap still comes from the Karst spec. assert_eq!(env_before.cfg_env.tx_gas_limit_cap, None); assert_eq!(env_before.cfg_env.tx_gas_limit_cap(), 16_777_216); let env_active = evm_config.evm_env(&active).unwrap(); assert_eq!(env_active.cfg_env.spec, OpSpecId::KARST); assert_eq!(env_active.cfg_env.limit_contract_code_size, Some(TEST_MAX_CODE_SIZE)); assert_eq!(env_active.cfg_env.limit_contract_initcode_size, Some(TEST_MAX_INITCODE_SIZE)); assert_eq!(env_active.cfg_env.tx_gas_limit_cap, Some(u64::MAX)); let next_env = evm_config .next_evm_env( &before, &OpNextBlockEnvAttributes { timestamp: 2000, suggested_fee_recipient: Address::ZERO, prev_randao: B256::ZERO, gas_limit: 30_000_000, parent_beacon_block_root: None, extra_data: Bytes::new(), }, ) .unwrap(); assert_eq!(next_env.cfg_env, env_active.cfg_env); } #[test] fn evm_limits_fork_can_preempt_karst_tx_gas_cap() { let spec = parse_genesis( &with_evm_limits_fork( 500, serde_json::json!({ "txGasLimitCap": u64::MAX, }), ), "evm-limits-before-karst", ); let evm_config = ConduitOpEvmConfig::new(spec); let before = Header { timestamp: 499, gas_limit: 30_000_000, ..Default::default() }; let custom_fork = Header { timestamp: 500, gas_limit: 30_000_000, ..Default::default() }; let karst = Header { timestamp: 1000, gas_limit: 30_000_000, ..Default::default() }; let before_env = evm_config.evm_env(&before).unwrap(); assert_eq!(before_env.cfg_env.spec, OpSpecId::JOVIAN); assert_eq!(before_env.cfg_env.tx_gas_limit_cap, None); let custom_fork_env = evm_config.evm_env(&custom_fork).unwrap(); assert_eq!(custom_fork_env.cfg_env.spec, OpSpecId::JOVIAN); assert_eq!(custom_fork_env.cfg_env.tx_gas_limit_cap, Some(u64::MAX)); let karst_env = evm_config.evm_env(&karst).unwrap(); assert_eq!(karst_env.cfg_env.spec, OpSpecId::KARST); assert_eq!(karst_env.cfg_env.tx_gas_limit_cap, Some(u64::MAX)); } #[test] fn evm_limits_fork_leaves_omitted_limits_unchanged() { let active = Header { timestamp: 2000, gas_limit: 30_000_000, ..Default::default() }; let gas_only_spec = parse_genesis( &with_evm_limits_fork(2000, serde_json::json!({ "txGasLimitCap": u64::MAX })), "evm-limits-gas-only", ); let gas_only_env = ConduitOpEvmConfig::new(gas_only_spec).evm_env(&active).unwrap(); assert_eq!(gas_only_env.cfg_env.limit_contract_code_size, None); assert_eq!(gas_only_env.cfg_env.limit_contract_initcode_size, None); assert_eq!(gas_only_env.cfg_env.tx_gas_limit_cap, Some(u64::MAX)); let code_only_spec = parse_genesis( &with_evm_limits_fork( 2000, serde_json::json!({ "maxCodeSize": TEST_MAX_CODE_SIZE, }), ), "evm-limits-code-only", ); let code_only_env = ConduitOpEvmConfig::new(code_only_spec).evm_env(&active).unwrap(); assert_eq!(code_only_env.cfg_env.limit_contract_code_size, Some(TEST_MAX_CODE_SIZE)); assert_eq!(code_only_env.cfg_env.limit_contract_initcode_size, None); // The fork omits `txGasLimitCap`, so the Karst spec cap is left to apply on its own. assert_eq!(code_only_env.cfg_env.tx_gas_limit_cap, None); assert_eq!(code_only_env.cfg_env.tx_gas_limit_cap(), 16_777_216); } }