Skip to main content

foundry_evm/executors/
mod.rs

1//! EVM executor abstractions, which can execute calls.
2//!
3//! Used for running tests, scripts, and interacting with the inner backend which holds the state.
4
5use crate::inspectors::{
6    Cheatcodes, CmpOperands, EdgeCoverage, EdgeIndexMap, InspectorData, InspectorStack,
7    cheatcodes::BroadcastableTransactions,
8};
9use alloy_consensus::transaction::Recovered;
10use alloy_dyn_abi::{DynSolValue, FunctionExt, JsonAbiExt};
11use alloy_eips::{Typed2718, eip4788::BEACON_ROOTS_ADDRESS, eip7702::SignedAuthorization};
12use alloy_json_abi::Function;
13use alloy_network::TransactionBuilder;
14use alloy_primitives::{
15    Address, B256, Bytes, Log, TxKind, U256, keccak256,
16    map::{AddressHashMap, HashMap},
17};
18use alloy_sol_types::{SolCall, sol};
19use evm2::{
20    Evm, TxResultWithState,
21    bytecode::Bytecode,
22    evm::{AccountInfo, PendingState, SystemTx},
23    interpreter::InstrStop,
24};
25use foundry_cheatcodes::CheatcodesBackend;
26use foundry_common::FoundryTransactionBuilder;
27use foundry_evm_core::{
28    backend::{Backend, BackendResult, CowBackend, GLOBAL_FAIL_SLOT, handler_error},
29    constants::{
30        CALLER, CHEATCODE_ADDRESS, CHEATCODE_CONTRACT_HASH, DEFAULT_CREATE2_DEPLOYER,
31        DEFAULT_CREATE2_DEPLOYER_CODE, DEFAULT_CREATE2_DEPLOYER_DEPLOYER,
32    },
33    decode::{RevertDecoder, SkipReason},
34    edgecov::{self, EdgeCovGuard},
35    eip2935::{
36        HISTORY_STORAGE_ADDRESS, HISTORY_STORAGE_CODE, history_storage_slot, history_storage_value,
37        history_window_start,
38    },
39    evm::{
40        ChainFor, EthEvmNetwork, EvmEnv, EvmEnvFor, EvmFactoryFor, FoundryEvmExt,
41        FoundryEvmFactory, FoundryEvmFor, FoundryEvmNetwork, FoundryTxConversion, SpecFor,
42        TransactionRequestFor, TxFor, TxResultFor, TypesFor, evm_env, release_inspector,
43    },
44};
45use foundry_evm_coverage::HitMaps;
46use foundry_evm_fuzz::ObservedCall;
47use foundry_evm_networks::NetworkConfigs;
48use foundry_evm_traces::{SparsedTraceArena, TraceRequirements};
49use sancov::SancovGuard;
50use std::{
51    borrow::Cow,
52    sync::{
53        Arc,
54        atomic::{AtomicBool, Ordering},
55    },
56    time::{Duration, Instant},
57};
58
59#[cfg(feature = "monad")]
60use foundry_evm_core::evm::{BlockContext, MonadEvmNetwork};
61
62mod builder;
63pub use builder::ExecutorBuilder;
64
65mod campaign;
66
67pub mod fuzz;
68pub use fuzz::FuzzedExecutor;
69
70pub mod invariant;
71pub use invariant::InvariantExecutor;
72
73mod corpus;
74mod corpus_io;
75mod sancov;
76mod showmap;
77mod trace;
78
79pub use corpus::{DynamicTargetCtx, StatelessReplayTarget, persist_corpus_seed};
80pub use corpus_io::{
81    CorpusDirEntry, canonical_replay_dirs, parse_corpus_filename, read_corpus_dir, read_corpus_tree,
82};
83pub use showmap::{
84    InvariantReplayOptions, MinimizationReplayInput, ReplayFailure, ReplayObservation,
85    ShowmapDomain, ShowmapOpts, ShowmapReplayTarget, ShowmapStats, replay_corpus_to_showmap,
86    replay_sequence_for_minimization,
87};
88pub use trace::{TracingExecutor, TracingFork};
89
90const DURATION_BETWEEN_METRICS_REPORT: Duration = Duration::from_secs(5);
91
92/// EIP-8130 transaction type.
93const EIP8130_TX_TYPE: u8 = 0x79;
94
95sol! {
96    interface ITest {
97        function setUp() external;
98        function failed() external view returns (bool failed);
99
100        #[derive(Default)]
101        function beforeTestSetup(bytes4 testSelector) public view returns (bytes[] memory beforeTestCalldata);
102    }
103}
104
105/// EVM executor.
106///
107/// The executor can be configured with various evm2 inspectors, like `Cheatcodes`.
108///
109/// There are multiple ways of interacting the EVM:
110/// - `call`: executes a transaction, but does not persist any state changes; similar to `eth_call`,
111///   where the EVM state is unchanged after the call.
112/// - `transact`: executes a transaction and persists the state changes
113/// - `deploy`: a special case of `transact`, specialized for persisting the state of a contract
114///   deployment
115/// - `setup`: a special case of `transact`, used to set up the environment for a test
116///
117/// Every execution builds an EVM from the backend, installs the inspector stack, which holds the
118/// backend for the run, and then parks the EVM into the backend to commit or drops it to discard.
119#[derive(Clone, Debug)]
120pub struct Executor<FEN: FoundryEvmNetwork> {
121    /// The backend holding the accepted state.
122    ///
123    /// Wrapped in `Arc` for efficient cloning during parallel fuzzing. Use [`Arc::make_mut`]
124    /// for copy-on-write semantics when mutation is needed.
125    backend: Arc<Backend<FEN>>,
126    /// The EVM environment (spec, runtime version and block).
127    evm_env: EvmEnvFor<FEN>,
128    /// The transaction defaults of the executor's calls, such as the sender and gas price.
129    tx: TransactionRequestFor<FEN>,
130    /// The inspector stack.
131    inspector: InspectorStack<FEN>,
132    /// The gas limit for calls and deployments.
133    gas_limit: u64,
134    /// Whether `failed()` should be called on the test contract to determine if the test failed.
135    legacy_assertions: bool,
136    /// Whether committing setup calls should return retained storage observations for guidance.
137    collect_setup_storage: bool,
138}
139
140impl<FEN: FoundryEvmNetwork> Executor<FEN> {
141    /// Creates a new `Executor` with the given arguments.
142    #[inline]
143    pub fn new(
144        mut backend: Backend<FEN>,
145        evm_env: EvmEnvFor<FEN>,
146        tx: TransactionRequestFor<FEN>,
147        inspector: InspectorStack<FEN>,
148        networks: NetworkConfigs,
149        gas_limit: u64,
150        legacy_assertions: bool,
151    ) -> Self {
152        backend.set_networks(networks);
153        let extra_cheatcode_addresses = inspector.extra_cheatcode_addresses();
154        backend.extend_persistent_accounts(extra_cheatcode_addresses.iter().copied());
155
156        // Need to create a non-empty contract on the cheatcodes address so `extcodesize` checks
157        // do not fail. The code hash is fixed, so each account gets its own stub code seeded with
158        // it: clones share the cached hash.
159        for (address, code_hash) in std::iter::once((CHEATCODE_ADDRESS, CHEATCODE_CONTRACT_HASH))
160            .chain(extra_cheatcode_addresses.iter().map(|&address| (address, keccak256(address))))
161        {
162            let stub = Bytecode::new_raw(Bytes::from_static(&[0]));
163            stub.seed_hash(code_hash);
164            backend.insert_account_info(
165                address,
166                AccountInfo::new(U256::ZERO, 0, code_hash, Some(stub)),
167            );
168        }
169
170        // Foundry enables `EIP7702` on every spec, so the EIP-2935 predeploy keys off the spec.
171        if !backend.is_forked_mode() && evm_env.spec.into() >= evm2::SpecId::PRAGUE {
172            let account = backend.basic(HISTORY_STORAGE_ADDRESS).ok().flatten().unwrap_or_default();
173            backend.insert_account_info(
174                HISTORY_STORAGE_ADDRESS,
175                account.with_code(Bytecode::new_raw(HISTORY_STORAGE_CODE.clone())),
176            );
177
178            let current_block = evm_env.block.number;
179            let mut block_number = history_window_start(current_block);
180            while block_number < current_block {
181                let block_hash = backend.block_hash(block_number).unwrap_or_default();
182                let slot = history_storage_slot(block_number);
183                let value = history_storage_value(block_hash);
184                backend.insert_account_storage(HISTORY_STORAGE_ADDRESS, slot, value);
185                block_number += U256::ONE;
186            }
187        }
188
189        Self {
190            backend: Arc::new(backend),
191            evm_env,
192            tx,
193            inspector,
194            gas_limit,
195            legacy_assertions,
196            collect_setup_storage: false,
197        }
198    }
199
200    fn clone_with_backend(&self, backend: Backend<FEN>) -> Self {
201        Self {
202            backend: Arc::new(backend),
203            evm_env: self.evm_env,
204            tx: self.tx.clone(),
205            inspector: self.inspector().clone(),
206            gas_limit: self.gas_limit,
207            legacy_assertions: self.legacy_assertions,
208            collect_setup_storage: self.collect_setup_storage,
209        }
210    }
211
212    /// Returns a reference to the EVM backend.
213    pub fn backend(&self) -> &Backend<FEN> {
214        &self.backend
215    }
216
217    /// Returns a mutable reference to the EVM backend.
218    ///
219    /// Uses copy-on-write semantics: if other clones of this executor share the backend,
220    /// this will clone the backend first.
221    pub fn backend_mut(&mut self) -> &mut Backend<FEN> {
222        Arc::make_mut(&mut self.backend)
223    }
224
225    /// Returns a reference to the EVM environment.
226    pub const fn evm_env(&self) -> &EvmEnvFor<FEN> {
227        &self.evm_env
228    }
229
230    /// Returns a mutable reference to the EVM environment.
231    pub const fn evm_env_mut(&mut self) -> &mut EvmEnvFor<FEN> {
232        &mut self.evm_env
233    }
234
235    /// Returns the transaction defaults of the executor's calls.
236    pub const fn tx(&self) -> &TransactionRequestFor<FEN> {
237        &self.tx
238    }
239
240    /// Returns the transaction defaults of the executor's calls mutably.
241    pub const fn tx_mut(&mut self) -> &mut TransactionRequestFor<FEN> {
242        &mut self.tx
243    }
244
245    /// Returns a reference to the EVM inspector.
246    pub const fn inspector(&self) -> &InspectorStack<FEN> {
247        &self.inspector
248    }
249
250    /// Returns a mutable reference to the EVM inspector.
251    pub const fn inspector_mut(&mut self) -> &mut InspectorStack<FEN> {
252        &mut self.inspector
253    }
254
255    /// Returns the EVM spec.
256    pub const fn spec_id(&self) -> SpecFor<FEN> {
257        self.evm_env.spec
258    }
259
260    /// Sets the EVM spec and updates spec-dependent gas parameters.
261    pub fn set_spec_id(&mut self, spec_id: SpecFor<FEN>) {
262        self.evm_env = EvmFactoryFor::<FEN>::default().env_with_spec(self.evm_env, spec_id);
263    }
264
265    /// Returns the gas limit for calls and deployments.
266    ///
267    /// This is different from the gas limit imposed by the passed in environment, as those limits
268    /// are used by the EVM for certain opcodes like `gaslimit`.
269    pub const fn gas_limit(&self) -> u64 {
270        self.gas_limit
271    }
272
273    /// Sets the gas limit for calls and deployments.
274    pub const fn set_gas_limit(&mut self, gas_limit: u64) {
275        self.gas_limit = gas_limit;
276    }
277
278    /// Returns whether `failed()` should be called on the test contract to determine if the test
279    /// failed.
280    pub const fn legacy_assertions(&self) -> bool {
281        self.legacy_assertions
282    }
283
284    /// Sets whether `failed()` should be called on the test contract to determine if the test
285    /// failed.
286    pub const fn set_legacy_assertions(&mut self, legacy_assertions: bool) {
287        self.legacy_assertions = legacy_assertions;
288    }
289
290    /// Creates the default CREATE2 Contract Deployer for local tests and scripts.
291    pub fn deploy_create2_deployer(&mut self) -> eyre::Result<()> {
292        trace!("deploying local create2 deployer");
293        // evm2's local database reports unknown accounts as absent.
294        let create2_deployer_account = self.account(DEFAULT_CREATE2_DEPLOYER)?;
295
296        // If the deployer is not currently deployed, deploy the default one.
297        if create2_deployer_account.code.is_none_or(|code| code.is_empty()) {
298            let creator = DEFAULT_CREATE2_DEPLOYER_DEPLOYER;
299
300            // Probably 0, but just in case.
301            let initial_balance = self.get_balance(creator)?;
302            self.set_balance(creator, U256::MAX)?;
303
304            // The deployer is test harness state, so the debugger does not step through it.
305            let recorder = self.inspector_mut().debug_recorder.take();
306            let res = self.deploy(creator, DEFAULT_CREATE2_DEPLOYER_CODE.into(), U256::ZERO, None);
307            self.inspector_mut().debug_recorder = recorder;
308            let res = res?;
309            trace!(create2=?res.address, "deployed local create2 deployer");
310
311            self.set_balance(creator, initial_balance)?;
312        }
313        Ok(())
314    }
315
316    /// Returns the accepted account at `address`, or an empty account.
317    fn account(&self, address: Address) -> BackendResult<AccountInfo> {
318        Ok(self.backend().basic(address)?.unwrap_or_default())
319    }
320
321    /// Set the balance of an account.
322    pub fn set_balance(&mut self, address: Address, amount: U256) -> BackendResult<()> {
323        trace!(?address, ?amount, "setting account balance");
324        let account = self.account(address)?.with_balance(amount);
325        self.backend_mut().insert_account_info(address, account);
326        Ok(())
327    }
328
329    /// Gets the balance of an account
330    pub fn get_balance(&self, address: Address) -> BackendResult<U256> {
331        Ok(self.account(address)?.balance)
332    }
333
334    /// Sets the nonce of an account without modifying the transaction defaults.
335    pub fn set_account_nonce(&mut self, address: Address, nonce: u64) -> BackendResult<()> {
336        let account = self.account(address)?.with_nonce(nonce);
337        self.backend_mut().insert_account_info(address, account);
338        Ok(())
339    }
340
341    /// Sets the nonce of an account and the transaction defaults.
342    pub fn set_nonce(&mut self, address: Address, nonce: u64) -> BackendResult<()> {
343        self.set_account_nonce(address, nonce)?;
344        self.tx_mut().set_nonce(nonce);
345        Ok(())
346    }
347
348    /// Returns the nonce of an account.
349    pub fn get_nonce(&self, address: Address) -> BackendResult<u64> {
350        Ok(self.account(address)?.nonce)
351    }
352
353    /// Set the code of an account.
354    pub fn set_code(&mut self, address: Address, code: Bytecode) -> BackendResult<()> {
355        let account = self.account(address)?.with_code(code);
356        self.backend_mut().insert_account_info(address, account);
357        Ok(())
358    }
359
360    /// Set the storage of an account.
361    pub fn set_storage(
362        &mut self,
363        address: Address,
364        storage: HashMap<U256, U256>,
365    ) -> BackendResult<()> {
366        self.backend_mut().replace_account_storage(address, storage);
367        Ok(())
368    }
369
370    /// Set a storage slot of an account.
371    pub fn set_storage_slot(
372        &mut self,
373        address: Address,
374        slot: U256,
375        value: U256,
376    ) -> BackendResult<()> {
377        self.backend_mut().insert_account_storage(address, slot, value);
378        Ok(())
379    }
380
381    /// Apply prestate trace data to the executor's backend.
382    ///
383    /// This is used to set up the EVM state based on the prestate trace from
384    /// `debug_traceTransaction`, which provides all accounts and storage slots
385    /// that will be accessed during transaction execution.
386    pub fn apply_prestate_trace(
387        &mut self,
388        prestate: std::collections::BTreeMap<Address, alloy_rpc_types::trace::geth::AccountState>,
389    ) -> eyre::Result<()> {
390        let backend = self.backend_mut();
391        for (address, account_state) in prestate {
392            let code = account_state.code.map(Bytecode::new_raw).unwrap_or_default();
393            let info = AccountInfo::default()
394                .with_balance(account_state.balance.unwrap_or_default())
395                .with_nonce(account_state.nonce.unwrap_or_default())
396                .with_code(code);
397            backend.insert_account_info(address, info);
398
399            for (slot, value) in account_state.storage {
400                backend.insert_account_storage(address, slot.into(), value.into());
401            }
402        }
403        Ok(())
404    }
405
406    /// Returns `true` if the account has no code.
407    pub fn is_empty_code(&self, address: Address) -> BackendResult<bool> {
408        Ok(self.backend().basic(address)?.is_none_or(|acc| acc.is_empty_code_hash()))
409    }
410
411    #[inline]
412    pub fn set_trace_requirements(&mut self, requirements: TraceRequirements) -> &mut Self {
413        self.inspector_mut().tracing_requirements(requirements);
414        self
415    }
416
417    #[inline]
418    pub fn set_script_execution(&mut self, script_address: Address) {
419        self.inspector_mut().script(script_address);
420    }
421
422    #[inline]
423    pub fn set_trace_printer(&mut self, trace_printer: bool) -> &mut Self {
424        self.inspector_mut().print(trace_printer);
425        self
426    }
427
428    #[inline]
429    pub fn create2_deployer(&self) -> Address {
430        self.inspector().create2_deployer
431    }
432
433    /// Deploys a contract and commits the new state to the underlying database.
434    ///
435    /// Executes a CREATE transaction with the contract `code` and persistent database state
436    /// modifications.
437    pub fn deploy(
438        &mut self,
439        from: Address,
440        code: Bytes,
441        value: U256,
442        rd: Option<&RevertDecoder>,
443    ) -> Result<DeployResult<FEN>, EvmError<FEN>> {
444        let (evm_env, tx) = self.prepare_call_env(from, TxKind::Create, code, value);
445        self.deploy_with_env(evm_env, tx, rd)
446    }
447
448    /// Deploys a contract using the given environment and transaction and commits the new state to
449    /// the underlying database.
450    ///
451    /// # Panics
452    ///
453    /// Panics if `tx` is not a create transaction.
454    #[instrument(name = "deploy", level = "debug", skip_all)]
455    pub fn deploy_with_env(
456        &mut self,
457        evm_env: EvmEnvFor<FEN>,
458        tx: TransactionRequestFor<FEN>,
459        rd: Option<&RevertDecoder>,
460    ) -> Result<DeployResult<FEN>, EvmError<FEN>> {
461        assert!(
462            tx.kind().is_some_and(|kind| kind.is_create()),
463            "Expected create transaction, got {:?}",
464            tx.kind()
465        );
466        trace!(sender=?tx.from(), "deploying contract");
467
468        let result = self.transact_with_env(evm_env, tx)?;
469        self.persist_deployment(result, rd)
470    }
471
472    /// Turns the committed result of a creation into a deployment, marking the created contract
473    /// persistent so that its state survives fork switches.
474    ///
475    /// # Panics
476    ///
477    /// Panics if a successful creation returned no address.
478    pub fn persist_deployment(
479        &mut self,
480        result: RawCallResult<FEN>,
481        rd: Option<&RevertDecoder>,
482    ) -> Result<DeployResult<FEN>, EvmError<FEN>> {
483        let result = result.into_result(rd)?;
484        let Some(address) = result.created_address else {
485            panic!("Deployment succeeded, but no address was returned: {result:#?}");
486        };
487        self.backend_mut().add_persistent_account(address);
488        trace!(%address, "deployed contract");
489        Ok(DeployResult { raw: result, address })
490    }
491
492    /// Calls the `setUp()` function on a contract.
493    ///
494    /// This will commit any state changes to the underlying database.
495    ///
496    /// Ayn changes made during the setup call to env's block environment are persistent, for
497    /// example `vm.chainId()` will change the `block.chainId` for all subsequent test calls.
498    #[instrument(name = "setup", level = "debug", skip_all)]
499    pub fn setup(
500        &mut self,
501        from: Option<Address>,
502        to: Address,
503        rd: Option<&RevertDecoder>,
504    ) -> Result<RawCallResult<FEN>, EvmError<FEN>> {
505        trace!(?from, ?to, "setting up contract");
506
507        let from = from.unwrap_or(CALLER);
508        self.backend_mut().set_test_contract(to).set_caller(from);
509        let calldata = Bytes::from_static(&ITest::setUpCall::SELECTOR);
510        let mut res = self.transact_raw(from, to, calldata, U256::ZERO)?;
511        res = res.into_result(rd)?;
512
513        // record any changes made to the block's environment during setup
514        self.evm_env_mut().block = res.evm_env.block;
515        // and also the spec and chain ID, which can be set manually.
516        if res.evm_env.spec != self.spec_id() {
517            self.set_spec_id(res.evm_env.spec);
518        }
519        self.evm_env_mut().set_chain_id(res.evm_env.chain_id());
520
521        let success = self.is_raw_call_success(to, Cow::Borrowed(&res.state_changeset), &res);
522        if !success {
523            return Err(res.into_execution_error("execution error".to_string()).into());
524        }
525
526        Ok(res)
527    }
528
529    /// Performs a call to an account on the current state of the VM.
530    pub fn call(
531        &self,
532        from: Address,
533        to: Address,
534        func: &Function,
535        args: &[DynSolValue],
536        value: U256,
537        rd: Option<&RevertDecoder>,
538    ) -> Result<CallResult<DynSolValue, FEN>, EvmError<FEN>> {
539        let calldata = Bytes::from(func.abi_encode_input(args)?);
540        let result = self.call_raw(from, to, calldata, value)?;
541        result.into_decoded_result(func, rd)
542    }
543
544    /// Performs a call to an account on the current state of the VM.
545    pub fn call_sol<C: SolCall>(
546        &self,
547        from: Address,
548        to: Address,
549        args: &C,
550        value: U256,
551        rd: Option<&RevertDecoder>,
552    ) -> Result<CallResult<C::Return, FEN>, EvmError<FEN>> {
553        let calldata = Bytes::from(args.abi_encode());
554        let mut raw = self.call_raw(from, to, calldata, value)?;
555        raw = raw.into_result(rd)?;
556        Ok(CallResult { decoded_result: C::abi_decode_returns(&raw.result)?, raw })
557    }
558
559    /// Performs a call to an account on the current state of the VM.
560    pub fn transact(
561        &mut self,
562        from: Address,
563        to: Address,
564        func: &Function,
565        args: &[DynSolValue],
566        value: U256,
567        rd: Option<&RevertDecoder>,
568    ) -> Result<CallResult<DynSolValue, FEN>, EvmError<FEN>> {
569        let calldata = Bytes::from(func.abi_encode_input(args)?);
570        let result = self.transact_raw(from, to, calldata, value)?;
571        result.into_decoded_result(func, rd)
572    }
573
574    /// Performs a raw call to an account on the current state of the VM.
575    pub fn call_raw(
576        &self,
577        from: Address,
578        to: Address,
579        calldata: Bytes,
580        value: U256,
581    ) -> eyre::Result<RawCallResult<FEN>> {
582        let (evm_env, tx) = self.prepare_call_env(from, TxKind::Call(to), calldata, value);
583        self.call_with_env(evm_env, tx)
584    }
585
586    /// Performs a raw call to an account on the current state of the VM with an EIP-7702
587    /// authorization list.
588    pub fn call_raw_with_authorization(
589        &mut self,
590        from: Address,
591        to: Address,
592        calldata: Bytes,
593        value: U256,
594        authorization_list: Vec<SignedAuthorization>,
595    ) -> eyre::Result<RawCallResult<FEN>> {
596        let (evm_env, mut tx) = self.prepare_call_env(from, to.into(), calldata, value);
597        with_authorization_list(&mut tx, authorization_list);
598        self.call_with_env(evm_env, tx)
599    }
600
601    /// Performs a raw call to an account on the current state of the VM.
602    pub fn transact_raw(
603        &mut self,
604        from: Address,
605        to: Address,
606        calldata: Bytes,
607        value: U256,
608    ) -> eyre::Result<RawCallResult<FEN>> {
609        let (evm_env, tx) = self.prepare_call_env(from, TxKind::Call(to), calldata, value);
610        self.transact_with_env(evm_env, tx)
611    }
612
613    /// Performs a raw call to an account on the current state of the VM with an EIP-7702
614    /// authorization last.
615    pub fn transact_raw_with_authorization(
616        &mut self,
617        from: Address,
618        to: Address,
619        calldata: Bytes,
620        value: U256,
621        authorization_list: Vec<SignedAuthorization>,
622    ) -> eyre::Result<RawCallResult<FEN>> {
623        let (evm_env, mut tx) = self.prepare_call_env(from, TxKind::Call(to), calldata, value);
624        with_authorization_list(&mut tx, authorization_list);
625        self.transact_with_env(evm_env, tx)
626    }
627
628    /// Applies the EIP-4788 beacon roots system call (Cancun+).
629    /// <https://eips.ethereum.org/EIPS/eip-4788>
630    pub fn apply_beacon_root(&mut self, parent_beacon_block_root: B256) -> eyre::Result<()> {
631        let mut evm = self.backend().create_evm();
632        install_env::<FEN>(self.backend(), &mut evm, self.evm_env);
633        let pending = evm
634            .system_call(SystemTx::new(BEACON_ROOTS_ADDRESS, parent_beacon_block_root.into()))?
635            .detach()
636            .pending_state;
637        drop(evm);
638
639        // Only the beacon roots contract keeps the changes, not the system caller.
640        let mut state = PendingState::default();
641        for change in pending.account_changes().filter(|c| c.address == BEACON_ROOTS_ADDRESS) {
642            state.insert_account(change.address, change.original.cloned(), change.current.cloned());
643            for (key, slot) in change.storage.changed_slots() {
644                state.insert_storage(change.address, *key, slot.original, slot.current);
645            }
646        }
647        self.backend_mut().commit_pending(&state);
648        Ok(())
649    }
650
651    /// Executes the transaction `tx` with `evm_env`.
652    ///
653    /// The state after the call is **not** persisted.
654    #[instrument(name = "call", level = "debug", skip_all)]
655    pub fn call_with_env(
656        &self,
657        evm_env: EvmEnvFor<FEN>,
658        tx: TransactionRequestFor<FEN>,
659    ) -> eyre::Result<RawCallResult<FEN>> {
660        let init = tx.from().zip(tx.kind());
661        let tx_env = TypesFor::<FEN>::tx_from_request(tx.clone())?;
662        let mut result =
663            self.call_tx_with_init(evm_env, &tx_env, None, init, self.inspector().clone())?;
664        result.set_stipend(&evm_env, tx);
665        Ok(result)
666    }
667
668    /// Executes the converted transaction `tx` with `evm_env`, and `ext` or extension state
669    /// prepared for `tx`, without persisting its state.
670    ///
671    /// The result's `stipend` is zero, since `tx` is opaque; see [`calculate_stipend`].
672    #[instrument(name = "call", level = "debug", skip_all)]
673    pub fn call_tx(
674        &self,
675        evm_env: EvmEnvFor<FEN>,
676        tx: &Recovered<TxFor<FEN>>,
677        ext: Option<ChainFor<FEN>>,
678    ) -> eyre::Result<RawCallResult<FEN>> {
679        self.call_tx_with_init(evm_env, tx, ext, None, self.inspector().clone())
680    }
681
682    /// Performs a raw call like [`Self::call_raw`], but without the fuzz guidance inspectors.
683    ///
684    /// The call collects no edge coverage, comparison operands, or dictionary values, so use it
685    /// for calls whose instrumentation output is discarded, such as invariant predicate checks.
686    pub fn call_raw_without_fuzz_instrumentation(
687        &self,
688        from: Address,
689        to: Address,
690        calldata: Bytes,
691        value: U256,
692    ) -> eyre::Result<RawCallResult<FEN>> {
693        let (evm_env, tx) = self.prepare_call_env(from, TxKind::Call(to), calldata, value);
694        let init = tx.from().zip(tx.kind());
695        let tx_env = TypesFor::<FEN>::tx_from_request(tx.clone())?;
696        let mut stack = self.inspector().clone();
697        stack.disable_fuzz_instrumentation();
698        let mut result = self.call_tx_with_init(evm_env, &tx_env, None, init, stack)?;
699        result.set_stipend(&evm_env, tx);
700        Ok(result)
701    }
702
703    /// Like [`Self::call_tx`] with the inspector `stack`, recording `init`'s caller and test
704    /// contract, if the call modifies the backend.
705    fn call_tx_with_init(
706        &self,
707        evm_env: EvmEnvFor<FEN>,
708        tx: &Recovered<TxFor<FEN>>,
709        ext: Option<ChainFor<FEN>>,
710        init: Option<(Address, TxKind)>,
711        mut stack: InspectorStack<FEN>,
712    ) -> eyre::Result<RawCallResult<FEN>> {
713        let mut backend = CowBackend::new_borrowed(self.backend());
714        if let Some((caller, kind)) = init {
715            backend.initialize(caller, kind);
716        }
717        let (execution, evm) = execute(&mut backend, evm_env, tx, ext, &mut stack)?;
718        // Retain lifecycle changes; defer pending writes until commit.
719        backend.park_detached(evm);
720        let mut result = convert_executed_result(execution, stack, &backend)?;
721        if let Cow::Owned(backend) = backend.backend {
722            result.post_execution_backend = Some(Box::new(backend));
723        }
724        Ok(result)
725    }
726
727    /// Executes the transaction `tx` with `evm_env` and persists its state.
728    #[instrument(name = "transact", level = "debug", skip_all)]
729    pub fn transact_with_env(
730        &mut self,
731        evm_env: EvmEnvFor<FEN>,
732        tx: TransactionRequestFor<FEN>,
733    ) -> eyre::Result<RawCallResult<FEN>> {
734        // Every transaction records its caller and test contract.
735        if let (Some(caller), Some(kind)) = (tx.from(), tx.kind()) {
736            self.backend_mut().initialize(caller, kind);
737        }
738        let mut result =
739            self.transact_tx(evm_env, &TypesFor::<FEN>::tx_from_request(tx.clone())?, None)?;
740        result.set_stipend(&evm_env, tx);
741        Ok(result)
742    }
743
744    /// Executes the converted transaction `tx` with `evm_env`, and `ext` or extension state
745    /// prepared for `tx`, and persists its state.
746    #[instrument(name = "transact", level = "debug", skip_all)]
747    pub fn transact_tx(
748        &mut self,
749        evm_env: EvmEnvFor<FEN>,
750        tx: &Recovered<TxFor<FEN>>,
751        ext: Option<ChainFor<FEN>>,
752    ) -> eyre::Result<RawCallResult<FEN>> {
753        let mut stack = self.inspector().clone();
754        let collect_setup_storage = self.collect_setup_storage;
755        let backend = self.backend_mut();
756        let (execution, mut evm) = execute(backend, evm_env, tx, ext, &mut stack)?;
757        let suspended_storage = if collect_setup_storage {
758            backend.lifecycle().suspended_storage().collect()
759        } else {
760            Vec::new()
761        };
762        // Later transactions read the slots an account created here never wrote as zero.
763        evm.overlay_db_mut().commit_pending(&execution.state);
764        backend.park(evm);
765        let mut result = convert_executed_result(execution, stack, &*backend)?;
766        result.suspended_storage = suspended_storage;
767        // The execution already committed its state into the backend.
768        self.persist_inspector_state(&mut result);
769        Ok(result)
770    }
771
772    /// Replays the transactions preceding `target` in its block, then executes `target` with the
773    /// inspectors and persists the state of all of them.
774    ///
775    /// The caller selects which prefix transactions replay. `target_kind` is the target's kind,
776    /// which decides the test contract.
777    #[instrument(name = "transact_block_replay", level = "debug", skip_all)]
778    pub fn transact_with_block_replay(
779        &mut self,
780        mut evm_env: EvmEnvFor<FEN>,
781        target: &Recovered<TxFor<FEN>>,
782        target_kind: TxKind,
783        replay: &[(B256, Recovered<TxFor<FEN>>)],
784    ) -> eyre::Result<RawCallResult<FEN>> {
785        self.replay_block_prefix(&mut evm_env, target, target_kind, replay, |evm, tx| {
786            evm.ext_mut().for_next_transaction(tx);
787        })?;
788        self.transact_tx(evm_env, target, None)
789    }
790
791    /// Commits the transactions preceding `target` in its block, each with the network extension
792    /// state `prepare` sets up for it, and initializes the target's caller and test contract.
793    fn replay_block_prefix(
794        &mut self,
795        evm_env: &mut EvmEnvFor<FEN>,
796        target: &Recovered<TxFor<FEN>>,
797        target_kind: TxKind,
798        replay: &[(B256, Recovered<TxFor<FEN>>)],
799        mut prepare: impl FnMut(&mut FoundryEvmFor<'_, FEN>, &Recovered<TxFor<FEN>>),
800    ) -> eyre::Result<()> {
801        // EIP-8130 requires phase-aware execution and has no ordinary call/create kind.
802        // Check the entire prefix before executing anything.
803        eyre::ensure!(
804            target.ty() != EIP8130_TX_TYPE,
805            "EIP-8130 target transactions are not supported by tooling replay"
806        );
807        for (hash, tx) in replay {
808            eyre::ensure!(
809                tx.ty() != EIP8130_TX_TYPE,
810                "EIP-8130 prefix transaction {hash} is not supported by tooling replay"
811            );
812        }
813        let block_number = evm_env.block.number;
814        let caller = target.signer();
815        self.backend_mut().set_caller(caller).set_spec_id(evm_env.spec);
816        if !replay.is_empty() {
817            evm_env.set_feature(evm2::EvmFeatures::BALANCE_CHECK, false);
818        }
819
820        for (tx_hash, tx) in replay {
821            let backend = self.backend_mut();
822            let mut evm = backend.create_evm();
823            install_env::<FEN>(backend, &mut evm, *evm_env);
824            prepare(&mut evm, tx);
825            let result = evm.transact(tx).map(|executed| executed.commit()).map_err(|err| {
826                eyre::eyre!(
827                    "Failed to execute transaction: {tx_hash:?} in block {block_number}: {err:?}"
828                )
829            })?;
830            backend.park(evm);
831            if result.status
832                && let Some(address) = result.created_address
833            {
834                backend.add_persistent_account(address);
835            }
836        }
837
838        // The prefix has run, so the caller's nonce is the target's canonical nonce.
839        self.backend_mut().initialize(caller, target_kind);
840        Ok(())
841    }
842
843    /// Commits a call's state and inspector. Detached backends replace the executor's backend,
844    /// so commit before unrelated backend mutations.
845    #[instrument(name = "commit", level = "debug", skip_all)]
846    fn commit(&mut self, result: &mut RawCallResult<FEN>) {
847        if let Some(mut backend) = result.post_execution_backend.take() {
848            // Snapshot failures are call-local.
849            backend.set_state_snapshot_failure(self.backend().has_state_snapshot_failure());
850            self.backend = Arc::new(*backend);
851        }
852        self.backend_mut().commit_pending(&result.state_changeset);
853        self.persist_inspector_state(result);
854    }
855
856    /// Persists the cheatcode state and block of an executed call into the inspector stack.
857    fn persist_inspector_state(&mut self, result: &mut RawCallResult<FEN>) {
858        // Persist cheatcode state.
859        self.inspector_mut().cheatcodes = result.cheatcodes.take();
860        if let Some(cheats) = self.inspector_mut().cheatcodes.as_mut() {
861            // Clear broadcastable transactions
862            cheats.broadcastable_transactions.clear();
863            cheats.ignored_traces.ignored.clear();
864            // if tracing was paused but never unpaused, we should begin next frame with tracing
865            // still paused
866            if let Some(last_pause_call) = cheats.ignored_traces.last_pause_call.as_mut() {
867                *last_pause_call = (0, 0);
868            }
869        }
870
871        // Persist the changed environment.
872        self.inspector_mut().set_block(result.evm_env.block);
873    }
874
875    /// Returns `true` if a test can be considered successful.
876    ///
877    /// This is the same as [`Self::is_success`], but will consume the `state_changeset` map to use
878    /// internally when calling `failed()`.
879    pub fn is_raw_call_mut_success(
880        &self,
881        address: Address,
882        call_result: &mut RawCallResult<FEN>,
883    ) -> bool {
884        self.is_raw_call_success(
885            address,
886            Cow::Owned(std::mem::take(&mut call_result.state_changeset)),
887            call_result,
888        )
889    }
890
891    /// Returns `true` if a test can be considered successful.
892    ///
893    /// This is the same as [`Self::is_success`], but intended for outcomes of [`Self::call_raw`].
894    pub fn is_raw_call_success(
895        &self,
896        address: Address,
897        state_changeset: Cow<'_, PendingState>,
898        call_result: &RawCallResult<FEN>,
899    ) -> bool {
900        if call_result.has_state_snapshot_failure {
901            // a failure occurred in a reverted snapshot, which is considered a failed test
902            return false;
903        }
904        self.is_success_raw(
905            address,
906            call_result.reverted,
907            state_changeset,
908            false,
909            call_result.post_execution_backend.as_deref().unwrap_or_else(|| self.backend()),
910        )
911    }
912
913    /// Like [`Self::is_raw_call_mut_success`] but uses [`Self::is_success_handler_gate`] under
914    /// the hood. Intended for invariant view-call success checks during a campaign where the
915    /// committed `GLOBAL_FAIL_SLOT` may be stale poison from a previously-recorded handler bug.
916    pub fn is_raw_call_mut_success_handler_gate(
917        &self,
918        address: Address,
919        call_result: &mut RawCallResult<FEN>,
920    ) -> bool {
921        if call_result.has_state_snapshot_failure {
922            return false;
923        }
924        let state_changeset = std::mem::take(&mut call_result.state_changeset);
925        self.is_success_raw(
926            address,
927            call_result.reverted,
928            Cow::Owned(state_changeset),
929            true,
930            call_result.post_execution_backend.as_deref().unwrap_or_else(|| self.backend()),
931        )
932    }
933
934    /// Returns `true` if a test can be considered successful.
935    ///
936    /// If the call succeeded, we also have to check the global and local failure flags.
937    ///
938    /// These are set by the test contract itself when an assertion fails, using the internal `fail`
939    /// function. The global flag is located in [`CHEATCODE_ADDRESS`] at slot [`GLOBAL_FAIL_SLOT`],
940    /// and the local flag is located in the test contract at an unspecified slot.
941    ///
942    /// This behavior is inherited from Dapptools, where initially only a public
943    /// `failed` variable was used to track test failures, and later, a global failure flag was
944    /// introduced to track failures across multiple contracts in
945    /// [ds-test#30](https://github.com/dapphub/ds-test/pull/30).
946    ///
947    /// The assumption is that the test runner calls `failed` on the test contract to determine if
948    /// it failed. However, we want to avoid this as much as possible, as it is relatively
949    /// expensive to set up an EVM call just for checking a single boolean flag.
950    ///
951    /// See:
952    /// - Newer DSTest: <https://github.com/dapphub/ds-test/blob/e282159d5170298eb2455a6c05280ab5a73a4ef0/src/test.sol#L47-L63>
953    /// - Older DSTest: <https://github.com/dapphub/ds-test/blob/9ca4ecd48862b40d7b0197b600713f64d337af12/src/test.sol#L38-L49>
954    /// - forge-std: <https://github.com/foundry-rs/forge-std/blob/19891e6a0b5474b9ea6827ddb90bb9388f7acfc0/src/StdAssertions.sol#L38-L44>
955    pub fn is_success(
956        &self,
957        address: Address,
958        reverted: bool,
959        state_changeset: Cow<'_, PendingState>,
960    ) -> bool {
961        self.is_success_raw(address, reverted, state_changeset, false, self.backend())
962    }
963
964    /// Like [`Self::is_success`] but ignores the *committed* `GLOBAL_FAIL_SLOT` and only treats
965    /// the slot as failed when this call's in-flight changeset writes it. Used by the invariant
966    /// runner's per-call handler-success gate, where a `1` already in committed storage is just
967    /// stale poison from a previously-recorded handler bug (separately tracked) and must not
968    /// suppress later `assert_invariants` / `afterInvariant` evaluations.
969    pub fn is_success_handler_gate(
970        &self,
971        address: Address,
972        reverted: bool,
973        state_changeset: Cow<'_, PendingState>,
974    ) -> bool {
975        self.is_success_raw(address, reverted, state_changeset, true, self.backend())
976    }
977
978    #[instrument(name = "is_success", level = "debug", skip_all)]
979    fn is_success_raw(
980        &self,
981        address: Address,
982        reverted: bool,
983        state_changeset: Cow<'_, PendingState>,
984        pending_global_failure_only: bool,
985        source: &Backend<FEN>,
986    ) -> bool {
987        // The call reverted.
988        if reverted {
989            return false;
990        }
991
992        // A failure occurred in a reverted snapshot, which is considered a failed test.
993        if source.has_state_snapshot_failure() {
994            return false;
995        }
996
997        // Check the global failure slot. Callers that already track recorded handler bugs
998        // out-of-band can pass `pending_global_failure_only = true` to ignore the committed
999        // slot (which would otherwise stay `1` for the rest of the run after a non-reverting
1000        // `vm.assert*` under `assertions_revert = false`).
1001        let global_failed = Self::has_pending_global_failure(&state_changeset)
1002            || (!pending_global_failure_only
1003                && source
1004                    .storage(CHEATCODE_ADDRESS, GLOBAL_FAIL_SLOT)
1005                    .is_ok_and(|slot| !slot.is_zero()));
1006        if global_failed {
1007            return false;
1008        }
1009
1010        if !self.legacy_assertions {
1011            return true;
1012        }
1013
1014        // Finally, resort to calling `DSTest::failed`.
1015        {
1016            // Construct a new bare-bones backend to evaluate success.
1017            let mut backend = source.clone_empty();
1018
1019            // We only clone the test contract and cheatcode accounts,
1020            // that's all we need to evaluate success.
1021            for address in [address, CHEATCODE_ADDRESS] {
1022                let Ok(acc) = source.basic(address) else { return false };
1023                backend.insert_account_info(address, acc.unwrap_or_default());
1024            }
1025
1026            // If this test failed any asserts, then this changeset will contain changes
1027            // `false -> true` for the contract's `failed` variable and the `globalFailure` flag
1028            // in the state of the cheatcode address,
1029            // which are both read when we call `"failed()(bool)"` in the next step.
1030            backend.commit_pending(&state_changeset);
1031
1032            // Check if a DSTest assertion failed
1033            let executor = self.clone_with_backend(backend);
1034            let call = executor.call_sol(CALLER, address, &ITest::failedCall {}, U256::ZERO, None);
1035            match call {
1036                Ok(CallResult { raw: _, decoded_result: failed }) => {
1037                    trace!(failed, "DSTest::failed()");
1038                    !failed
1039                }
1040                Err(err) => {
1041                    trace!(%err, "failed to call DSTest::failed()");
1042                    true
1043                }
1044            }
1045        }
1046    }
1047
1048    /// Returns whether the in-flight state changeset for the current call sets the global
1049    /// assertion failure flag.
1050    pub fn has_pending_global_failure(state_changeset: &PendingState) -> bool {
1051        state_changeset.account_changes_for(&CHEATCODE_ADDRESS).is_some_and(|change| {
1052            change
1053                .storage
1054                .slots
1055                .get(&GLOBAL_FAIL_SLOT)
1056                .is_some_and(|slot| !slot.value.current.is_zero())
1057        })
1058    }
1059
1060    /// Returns whether the global assertion failure flag is set either in the in-flight state
1061    /// changeset or in the committed backend state.
1062    pub fn has_global_failure(&self, state_changeset: &PendingState) -> bool {
1063        if Self::has_pending_global_failure(state_changeset) {
1064            return true;
1065        }
1066
1067        self.backend()
1068            .storage(CHEATCODE_ADDRESS, GLOBAL_FAIL_SLOT)
1069            .is_ok_and(|failed_slot| !failed_slot.is_zero())
1070    }
1071
1072    /// Creates the environment and transaction to use when executing a call in a test context.
1073    ///
1074    /// The transaction executes with no fees and the executor's gas limit, from `caller`'s current
1075    /// nonce. If using a backend with cheatcodes, the gas price and block are overwritten by the
1076    /// cheatcode state in between calls.
1077    pub fn prepare_call_env(
1078        &self,
1079        caller: Address,
1080        kind: TxKind,
1081        data: Bytes,
1082        value: U256,
1083    ) -> (EvmEnvFor<FEN>, TransactionRequestFor<FEN>) {
1084        // We always set the gas price to 0 so we can execute the transaction regardless of
1085        // network conditions - the actual gas price is kept in the cheatcode state and is applied
1086        // by the cheatcode handler if it is enabled.
1087        let mut evm_env = self.evm_env;
1088        evm_env.block.basefee = U256::ZERO;
1089        evm_env.block.gas_limit = U256::from(self.gas_limit);
1090
1091        let mut tx = self.tx.clone();
1092        tx.set_from(caller);
1093        tx.set_kind(kind);
1094        tx.set_input(data);
1095        tx.set_value(value);
1096        tx.set_gas_limit(self.gas_limit);
1097        tx.set_chain_id(evm_env.chain_id());
1098        tx.set_nonce(self.get_nonce(caller).unwrap_or_default());
1099        if tx.max_fee_per_gas().is_some() {
1100            tx.set_max_fee_per_gas(0);
1101            tx.set_max_priority_fee_per_gas(0);
1102        } else {
1103            tx.set_gas_price(0);
1104        }
1105
1106        (evm_env, tx)
1107    }
1108
1109    pub fn call_sol_default<C: SolCall>(&self, to: Address, args: &C) -> C::Return
1110    where
1111        C::Return: Default,
1112    {
1113        self.call_sol(CALLER, to, args, U256::ZERO, None)
1114            .map(|c| c.decoded_result)
1115            .inspect_err(|e| warn!(target: "forge::test", "failed calling {:?}: {e}", C::SIGNATURE))
1116            .unwrap_or_default()
1117    }
1118
1119    /// Enables returning retained storage observations from committing setup calls.
1120    /// Disable this before running tests so campaigns do not copy setup-only metadata.
1121    pub const fn set_collect_setup_storage(&mut self, enabled: bool) {
1122        self.collect_setup_storage = enabled;
1123    }
1124}
1125
1126/// Attaches an EIP-7702 authorization list to `tx`, which then executes as a fee-less EIP-7702
1127/// transaction.
1128fn with_authorization_list<B: FoundryTransactionBuilder<N> + TransactionBuilder, N>(
1129    tx: &mut B,
1130    authorization_list: Vec<SignedAuthorization>,
1131) where
1132    N: alloy_network::Network<TransactionRequest = B>,
1133{
1134    tx.set_authorization_list(authorization_list);
1135    tx.set_max_fee_per_gas(0);
1136    tx.set_max_priority_fee_per_gas(0);
1137}
1138
1139/// Installs `env` on `evm`, freshly created over `backend`, which starts with the backend's
1140/// environment.
1141fn install_env<FEN: FoundryEvmNetwork>(
1142    backend: &Backend<FEN>,
1143    evm: &mut FoundryEvmFor<'_, FEN>,
1144    env: EvmEnvFor<FEN>,
1145) {
1146    evm.set_initial_call_depth(env.initial_call_depth);
1147    if same_execution_config::<FEN>(&evm_env(evm), &env) {
1148        evm.set_block(env.block);
1149        backend.lifecycle().sync_database_policy(evm);
1150        return;
1151    }
1152    // The backend's factory carries network configuration, such as Base's activation admin.
1153    let lifecycle = backend.lifecycle();
1154    let factory = lifecycle.factory().configure_for(&lifecycle.forks().active_db(), &env);
1155    let precompiles = factory.precompiles(&env, evm.ext());
1156    let EvmEnv { spec, version, block, .. } = env;
1157    evm.set_block_and_execution_config(
1158        block,
1159        factory.execution_config(spec, version),
1160        spec,
1161        factory.tx_registry(spec),
1162        precompiles,
1163    );
1164    backend.lifecycle().sync_database_policy(evm);
1165}
1166
1167/// Returns whether `current` and `next` build the same execution config: the same spec and every
1168/// field of their runtime [`Version`](evm2::Version), so only the block differs.
1169fn same_execution_config<FEN: FoundryEvmNetwork>(
1170    current: &EvmEnvFor<FEN>,
1171    next: &EvmEnvFor<FEN>,
1172) -> bool {
1173    // `Version` has no `PartialEq`; destructure it so a new field fails to compile here.
1174    let evm2::Version {
1175        gas_params,
1176        features,
1177        chain_id,
1178        tx_gas_limit_cap,
1179        tx_total_gas_cap,
1180        memory_limit,
1181        max_code_size,
1182        max_initcode_size,
1183        max_blobs_per_tx,
1184        _non_exhaustive: (),
1185    } = next.version;
1186    let version = &current.version;
1187    current.spec == next.spec
1188        && version.gas_params == gas_params
1189        && version.features == features
1190        && version.chain_id == chain_id
1191        && version.tx_gas_limit_cap == tx_gas_limit_cap
1192        && version.tx_total_gas_cap == tx_total_gas_cap
1193        && version.memory_limit == memory_limit
1194        && version.max_code_size == max_code_size
1195        && version.max_initcode_size == max_initcode_size
1196        && version.max_blobs_per_tx == max_blobs_per_tx
1197}
1198
1199#[cfg(feature = "monad")]
1200impl Executor<MonadEvmNetwork> {
1201    /// Like [`Executor::transact_with_block_replay`], positioning the prefix and target in the
1202    /// Monad block `context`. The block is trusted history: its canonical protocol transactions
1203    /// replay as protocol system calls, and a non-canonical envelope from the protocol sender is
1204    /// rejected.
1205    #[instrument(name = "transact_monad_block_replay", level = "debug", skip_all)]
1206    pub fn transact_with_monad_block_replay(
1207        &mut self,
1208        mut env: EvmEnvFor<MonadEvmNetwork>,
1209        target: &Recovered<TxFor<MonadEvmNetwork>>,
1210        target_kind: TxKind,
1211        replay: &[(B256, Recovered<TxFor<MonadEvmNetwork>>)],
1212        mut context: BlockContext<MonadEvmNetwork>,
1213    ) -> eyre::Result<RawCallResult<MonadEvmNetwork>> {
1214        let factory = EvmFactoryFor::<MonadEvmNetwork>::default();
1215        self.replay_block_prefix(&mut env, target, target_kind, replay, |evm, tx| {
1216            let mut ext = factory.evm_ext(&evm_env(evm));
1217            context.prepare_next(&mut ext, tx);
1218            ext.set_protocol_replay(ChainFor::<MonadEvmNetwork>::is_protocol_transaction(tx));
1219            *evm.ext_mut() = ext;
1220            context.record_transaction(tx.clone());
1221        })?;
1222        let mut ext = factory.evm_ext(&env);
1223        context.prepare_next(&mut ext, target);
1224        ext.set_protocol_replay(true);
1225        self.transact_tx(env, target, Some(ext))
1226    }
1227}
1228
1229/// A transaction executed by the [`Executor`].
1230struct Execution<FEN: FoundryEvmNetwork> {
1231    /// The transaction result.
1232    result: TxResultFor<FEN>,
1233    /// The transaction's state changes.
1234    state: PendingState,
1235    /// The environment after the transaction.
1236    env: EvmEnvFor<FEN>,
1237    /// Whether the inspectors halted the execution due to cancellation.
1238    cancelled: bool,
1239}
1240
1241/// Executes `tx` and returns its result and EVM for the caller to commit, park or discard.
1242fn execute<FEN: FoundryEvmNetwork>(
1243    backend: &mut dyn CheatcodesBackend<FEN>,
1244    env: EvmEnvFor<FEN>,
1245    tx: &Recovered<TxFor<FEN>>,
1246    ext: Option<ChainFor<FEN>>,
1247    stack: &mut InspectorStack<FEN>,
1248) -> eyre::Result<(Execution<FEN>, FoundryEvmFor<'static, FEN>)> {
1249    let sancov_edges = stack.inner.sancov_edges;
1250    let sancov_trace_cmp = stack.inner.sancov_trace_cmp;
1251    let edgecov_opcode = stack.inner.edgecov_opcode;
1252    let instrumented_edges = stack.inner.instrumented_edges;
1253    let instrumented_cmp_log = stack.inner.instrumented_cmp_log;
1254    let mut evm = backend.backend().create_evm();
1255    install_env::<FEN>(backend.backend(), &mut evm, env);
1256    match ext {
1257        Some(ext) => *evm.ext_mut() = ext,
1258        None => evm.ext_mut().for_next_transaction(tx),
1259    }
1260    let executed = {
1261        let _guard = (sancov_edges || sancov_trace_cmp)
1262            .then(|| SancovGuard::new(sancov_edges, sancov_trace_cmp));
1263        let _edgecov =
1264            edgecov_opcode.then(|| EdgeCovGuard::new(instrumented_edges, instrumented_cmp_log));
1265        evm.set_inspector(stack.as_inspector(&mut *backend));
1266        evm.transact(tx).map(|executed| executed.detach())
1267    };
1268    // SAFETY: The EVM was created by the backend's lifecycle over its owned databases.
1269    let evm: Evm<'_, _> = unsafe { release_inspector(evm) };
1270    let TxResultWithState { result, pending_state, .. } = executed.map_err(handler_error)?;
1271
1272    // A spec or chain ID change deferred by a cheatcode applies from the next transaction.
1273    let mut env = evm_env(&evm);
1274    if let Some(pending) = backend.backend().lifecycle().pending_env() {
1275        env = EvmEnv { spec: pending.spec, version: pending.version, ..env };
1276    }
1277    if let Some(spec) = stack.cheatcodes.as_deref().and_then(|cheats| cheats.execution_evm_version)
1278        && spec != env.spec
1279    {
1280        env = EvmFactoryFor::<FEN>::default().env_with_spec(env, spec);
1281    }
1282    Ok((
1283        Execution { result, state: pending_state, env, cancelled: stack.execution_cancelled() },
1284        evm,
1285    ))
1286}
1287
1288/// Returns the default environment of `FEN`.
1289#[cfg(test)]
1290pub(crate) fn default_env<FEN: FoundryEvmNetwork>() -> EvmEnvFor<FEN> {
1291    let spec = SpecFor::<FEN>::default();
1292    let chain_id = foundry_common::DEV_CHAIN_ID;
1293    EvmEnv::new(spec, EvmFactoryFor::<FEN>::default().version(spec, chain_id), Default::default())
1294}
1295
1296/// Builds an executor over an empty local backend with the default environment of `FEN`.
1297#[cfg(test)]
1298pub(crate) fn test_executor<FEN: FoundryEvmNetwork>(
1299    builder: ExecutorBuilder<FEN>,
1300    networks: NetworkConfigs,
1301) -> Executor<FEN> {
1302    let env = default_env::<FEN>();
1303    builder.build(env, Default::default(), Backend::spawn(None, env).unwrap(), networks)
1304}
1305
1306/// Represents the context after an execution error occurred.
1307#[derive(Debug, thiserror::Error)]
1308#[error("execution reverted: {reason} (gas: {})", raw.gas_used)]
1309pub struct ExecutionErr<FEN: FoundryEvmNetwork = EthEvmNetwork> {
1310    /// The raw result of the call.
1311    pub raw: RawCallResult<FEN>,
1312    /// The revert reason.
1313    pub reason: String,
1314}
1315
1316impl<FEN: FoundryEvmNetwork> std::ops::Deref for ExecutionErr<FEN> {
1317    type Target = RawCallResult<FEN>;
1318
1319    #[inline]
1320    fn deref(&self) -> &Self::Target {
1321        &self.raw
1322    }
1323}
1324
1325impl<FEN: FoundryEvmNetwork> std::ops::DerefMut for ExecutionErr<FEN> {
1326    #[inline]
1327    fn deref_mut(&mut self) -> &mut Self::Target {
1328        &mut self.raw
1329    }
1330}
1331
1332#[derive(Debug, thiserror::Error)]
1333pub enum EvmError<FEN: FoundryEvmNetwork = EthEvmNetwork> {
1334    /// Error which occurred during execution of a transaction.
1335    #[error(transparent)]
1336    Execution(Box<ExecutionErr<FEN>>),
1337    /// Error which occurred during ABI encoding/decoding.
1338    #[error(transparent)]
1339    Abi(#[from] alloy_dyn_abi::Error),
1340    /// Error caused which occurred due to calling the `skip` cheatcode.
1341    #[error("{0}")]
1342    Skip(SkipReason),
1343    /// Any other error.
1344    #[error("{0}")]
1345    Eyre(
1346        #[from]
1347        #[source]
1348        eyre::Report,
1349    ),
1350}
1351
1352impl<FEN: FoundryEvmNetwork> From<ExecutionErr<FEN>> for EvmError<FEN> {
1353    fn from(err: ExecutionErr<FEN>) -> Self {
1354        Self::Execution(Box::new(err))
1355    }
1356}
1357
1358impl<FEN: FoundryEvmNetwork> From<alloy_sol_types::Error> for EvmError<FEN> {
1359    fn from(err: alloy_sol_types::Error) -> Self {
1360        Self::Abi(err.into())
1361    }
1362}
1363
1364/// The result of a deployment.
1365#[derive(Debug)]
1366pub struct DeployResult<FEN: FoundryEvmNetwork = EthEvmNetwork> {
1367    /// The raw result of the deployment.
1368    pub raw: RawCallResult<FEN>,
1369    /// The address of the deployed contract
1370    pub address: Address,
1371}
1372
1373impl<FEN: FoundryEvmNetwork> std::ops::Deref for DeployResult<FEN> {
1374    type Target = RawCallResult<FEN>;
1375
1376    #[inline]
1377    fn deref(&self) -> &Self::Target {
1378        &self.raw
1379    }
1380}
1381
1382impl<FEN: FoundryEvmNetwork> std::ops::DerefMut for DeployResult<FEN> {
1383    #[inline]
1384    fn deref_mut(&mut self) -> &mut Self::Target {
1385        &mut self.raw
1386    }
1387}
1388
1389impl<FEN: FoundryEvmNetwork> From<DeployResult<FEN>> for RawCallResult<FEN> {
1390    fn from(d: DeployResult<FEN>) -> Self {
1391        d.raw
1392    }
1393}
1394
1395/// The result of a raw call.
1396#[derive(Debug)]
1397pub struct RawCallResult<FEN: FoundryEvmNetwork = EthEvmNetwork> {
1398    /// The status of the call
1399    pub exit_reason: Option<InstrStop>,
1400    /// Whether the call was halted by the execution cancellation inspector.
1401    pub execution_cancelled: bool,
1402    /// Whether the call reverted or not
1403    pub reverted: bool,
1404    /// Whether the call includes a snapshot failure
1405    ///
1406    /// This is tracked separately from revert because a snapshot failure can occur without a
1407    /// revert, since assert failures are stored in a global variable (ds-test legacy)
1408    pub has_state_snapshot_failure: bool,
1409    /// The raw result of the call.
1410    pub result: Bytes,
1411    /// Gas consumed by the call, including intrinsic gas, calldata floors and refunds.
1412    /// Excludes unused gas a network may charge.
1413    pub gas_used: u64,
1414    /// Refunded gas
1415    pub gas_refunded: u64,
1416    /// The initial gas stipend for the transaction
1417    pub stipend: u64,
1418    /// The logs emitted during the call
1419    pub logs: Vec<Log>,
1420    /// The labels assigned to addresses during the call
1421    pub labels: AddressHashMap<String>,
1422    /// The traces of the call
1423    pub traces: Option<SparsedTraceArena>,
1424    /// Runtime bytecodes for contracts seen in the trace, used by debug source mapping.
1425    pub debug_bytecodes: AddressHashMap<Bytes>,
1426    /// The line coverage info collected during the call
1427    pub line_coverage: Option<HitMaps>,
1428    /// The edge coverage info collected during the call
1429    pub edge_coverage: Option<EdgeCoverage>,
1430    /// EVM comparison operands collected during the call.
1431    pub evm_cmp_values: Option<Vec<CmpOperands>>,
1432    /// Observed sub-calls collected during the call.
1433    pub observed_calls: Vec<ObservedCall>,
1434    /// Sancov edge coverage from instrumented native Rust crates (e.g. precompiles).
1435    /// Tracked separately from EVM edge coverage to avoid ID-space collisions.
1436    pub sancov_coverage: Option<Vec<u8>>,
1437    /// Comparison operands captured via sancov trace-cmp callbacks.
1438    pub sancov_cmp_values: Option<Vec<foundry_evm_sancov::CmpSample>>,
1439    /// Scripted transactions generated from this call
1440    pub transactions: Option<BroadcastableTransactions<FEN::Network>>,
1441    /// The state changes of the call: every account and storage slot it loaded, with their
1442    /// original and present values.
1443    pub state_changeset: PendingState,
1444    /// Storage keys retained across context switches, with their originating forks. These are
1445    /// observations for setup dictionary guidance, not additional execution state changes.
1446    /// Populated only when setup storage collection is enabled for a committing call.
1447    pub suspended_storage: Vec<(Option<U256>, Address, U256)>,
1448    /// The environment after the call.
1449    pub evm_env: EvmEnvFor<FEN>,
1450    /// The cheatcode states after execution
1451    pub cheatcodes: Option<Box<Cheatcodes<FEN>>>,
1452    /// The address of the contract a successful create deployed.
1453    pub created_address: Option<Address>,
1454    /// The active fork's block number after execution, if any.
1455    pub fork_block_number: Option<u64>,
1456    /// The chisel state
1457    pub chisel_state: Option<(Vec<U256>, Vec<u8>)>,
1458    pub reverter: Option<Address>,
1459    /// Revert payloads minted by the `skip` cheatcode during this call.
1460    ///
1461    /// Moved out of the cheatcode state on conversion since `commit` moves that state back into
1462    /// the executor before results are classified.
1463    pub skip_payloads: Vec<Bytes>,
1464    /// Owned post-call backend, excluding `state_changeset`. Adopted only on commit.
1465    pub(crate) post_execution_backend: Option<Box<Backend<FEN>>>,
1466    /// Message of the first `vm.assert*` cheatcode that failed during this call, even if the call
1467    /// reverted later.
1468    ///
1469    /// Moved out of the cheatcode state on conversion, like `skip_payloads`, so it resets per
1470    /// call.
1471    pub failed_assertion: Option<String>,
1472    /// Value-independent identity of how this call failed, recorded only while
1473    /// [`InspectorStack::collect_failure_identity`] is set: its failed assertions and failed
1474    /// frames, by the sites that failed, in order. Calls with the same identity failed the same
1475    /// way, even if their messages report different values.
1476    ///
1477    /// `None` when not recorded or unknown.
1478    pub failure_identity: Option<B256>,
1479    /// Pc of the instruction that halted this call's frame and the end of the memory that
1480    /// instruction accessed, or zero, recorded only while
1481    /// [`InspectorStack::collect_failure_identity`] is set.
1482    ///
1483    /// `None` when not recorded, when the call succeeded, or when the failure identity is unknown.
1484    pub failure_halt: Option<(usize, U256)>,
1485    /// Where this call failed, recorded only while
1486    /// [`InspectorStack::collect_failure_provenance`] is set: its failed assertions, by the calls
1487    /// that led to them, and its failed frames, by the sites that failed, in order, with their
1488    /// revert data. Unlike
1489    /// `failure_identity`, it depends on values, so only runs of the same input are comparable.
1490    ///
1491    /// `None` when not recorded, or when a frame halted, such as on an invalid jump, at an
1492    /// instruction that is not recorded.
1493    pub failure_provenance: Option<B256>,
1494}
1495
1496#[cfg(test)]
1497impl<FEN: FoundryEvmNetwork> Default for RawCallResult<FEN> {
1498    fn default() -> Self {
1499        Self {
1500            exit_reason: None,
1501            execution_cancelled: false,
1502            reverted: false,
1503            has_state_snapshot_failure: false,
1504            result: Bytes::new(),
1505            gas_used: 0,
1506            gas_refunded: 0,
1507            stipend: 0,
1508            logs: Vec::new(),
1509            labels: HashMap::default(),
1510            traces: None,
1511            debug_bytecodes: HashMap::default(),
1512            line_coverage: None,
1513            edge_coverage: None,
1514            evm_cmp_values: None,
1515            observed_calls: Vec::new(),
1516            sancov_coverage: None,
1517            sancov_cmp_values: None,
1518            transactions: None,
1519            state_changeset: PendingState::default(),
1520            suspended_storage: Vec::new(),
1521            evm_env: default_env::<FEN>(),
1522            cheatcodes: Default::default(),
1523            created_address: None,
1524            fork_block_number: None,
1525            chisel_state: None,
1526            reverter: None,
1527            skip_payloads: Vec::new(),
1528            post_execution_backend: None,
1529            failed_assertion: None,
1530            failure_identity: None,
1531            failure_halt: None,
1532            failure_provenance: None,
1533        }
1534    }
1535}
1536
1537impl<FEN: FoundryEvmNetwork> RawCallResult<FEN> {
1538    /// Unpacks an EVM result.
1539    pub fn from_evm_result(r: Result<Self, EvmError<FEN>>) -> eyre::Result<(Self, Option<String>)> {
1540        match r {
1541            Ok(r) => Ok((r, None)),
1542            Err(EvmError::Execution(e)) => Ok((e.raw, Some(e.reason))),
1543            Err(e) => Err(e.into()),
1544        }
1545    }
1546
1547    /// Returns the skip reason if this call reverted with a genuine `vm.skip` payload.
1548    ///
1549    /// The revert data must byte-equal a payload recorded by the skip cheatcode during this call;
1550    /// a matching `FOUNDRY::SKIP` prefix alone (user-crafted revert data) does not count.
1551    pub fn skip_reason(&self) -> Option<SkipReason> {
1552        if !self.reverted || !self.skip_payloads.contains(&self.result) {
1553            return None;
1554        }
1555        SkipReason::decode(&self.result)
1556    }
1557
1558    /// Converts the result of the call into an `EvmError`.
1559    pub fn into_evm_error(self, rd: Option<&RevertDecoder>) -> EvmError<FEN> {
1560        if let Some(reason) = self.skip_reason() {
1561            return EvmError::Skip(reason);
1562        }
1563        let reason = rd.unwrap_or_default().decode(&self.result, self.exit_reason);
1564        EvmError::Execution(Box::new(self.into_execution_error(reason)))
1565    }
1566
1567    /// Converts the result of the call into an `ExecutionErr`.
1568    pub const fn into_execution_error(self, reason: String) -> ExecutionErr<FEN> {
1569        ExecutionErr { raw: self, reason }
1570    }
1571
1572    /// Returns an `EvmError` if the call failed, otherwise returns `self`.
1573    pub fn into_result(self, rd: Option<&RevertDecoder>) -> Result<Self, EvmError<FEN>> {
1574        if let Some(reason) = self.exit_reason
1575            && reason.is_success()
1576        {
1577            Ok(self)
1578        } else {
1579            Err(self.into_evm_error(rd))
1580        }
1581    }
1582
1583    /// Decodes the result of the call with the given function.
1584    pub fn into_decoded_result(
1585        mut self,
1586        func: &Function,
1587        rd: Option<&RevertDecoder>,
1588    ) -> Result<CallResult<DynSolValue, FEN>, EvmError<FEN>> {
1589        self = self.into_result(rd)?;
1590        let mut result = func.abi_decode_output(&self.result)?;
1591        let decoded_result =
1592            if result.len() == 1 { result.pop().unwrap() } else { DynSolValue::Tuple(result) };
1593        Ok(CallResult { raw: self, decoded_result })
1594    }
1595
1596    /// Returns the transactions generated from this call.
1597    pub fn transactions(&self) -> Option<&BroadcastableTransactions<FEN::Network>> {
1598        self.cheatcodes.as_ref().map(|c| &c.broadcastable_transactions)
1599    }
1600
1601    /// Update provided history map with edge coverage info collected during this call.
1602    pub fn merge_edge_coverage(
1603        &mut self,
1604        history_map: &mut Vec<u8>,
1605        edge_indices: &mut EdgeIndexMap,
1606    ) -> (bool, bool) {
1607        let mut new_coverage = false;
1608        let mut is_edge = false;
1609        if let Some(x) = &mut self.edge_coverage {
1610            match x {
1611                EdgeCoverage::Hash(x) => {
1612                    if history_map.len() < x.len() {
1613                        history_map.resize(x.len(), 0);
1614                    }
1615                    // Iterate over the current map and the history map together and update
1616                    // the history map, if we discover some new coverage, report true
1617                    for (curr, hist) in std::iter::zip(x.iter_mut(), history_map.iter_mut()) {
1618                        Self::merge_edge_count(*curr, hist, &mut new_coverage, &mut is_edge);
1619
1620                        // Hash reuses its map; collision-free drains hits.
1621                        *curr = 0;
1622                    }
1623                }
1624                EdgeCoverage::Instrumented(hits) => {
1625                    // Instrumented edge IDs are dense, so they index the history map directly.
1626                    for hit in hits.drain(..) {
1627                        let index = hit.id as usize;
1628                        if history_map.len() <= index {
1629                            history_map.resize(index + 1, 0);
1630                        }
1631                        Self::merge_edge_count(
1632                            hit.count,
1633                            &mut history_map[index],
1634                            &mut new_coverage,
1635                            &mut is_edge,
1636                        );
1637                    }
1638                }
1639                EdgeCoverage::CollisionFree(hits) => {
1640                    for hit in hits.drain(..) {
1641                        let edge_index = edge_indices.edge_index(hit.edge);
1642                        if history_map.len() <= edge_index {
1643                            history_map.resize(edge_index + 1, 0);
1644                        }
1645                        Self::merge_edge_count(
1646                            hit.count,
1647                            &mut history_map[edge_index],
1648                            &mut new_coverage,
1649                            &mut is_edge,
1650                        );
1651                    }
1652                }
1653            }
1654        }
1655        (new_coverage, is_edge)
1656    }
1657
1658    const fn merge_edge_count(
1659        curr: u8,
1660        hist: &mut u8,
1661        new_coverage: &mut bool,
1662        is_edge: &mut bool,
1663    ) {
1664        let Some(bucket) = Self::bin_count(curr) else {
1665            return;
1666        };
1667
1668        // If the old record for this edge pair is lower, update
1669        if *hist < bucket {
1670            if *hist == 0 {
1671                // Counts as an edge the first time we see it, otherwise it's a feature.
1672                *is_edge = true;
1673            }
1674            *hist = bucket;
1675            *new_coverage = true;
1676        }
1677    }
1678
1679    /// Convert a hitcount into an AFL-style bucket.
1680    /// <https://github.com/h0mbre/Lucid/blob/3026e7323c52b30b3cf12563954ac1eaa9c6981e/src/coverage.rs#L57-L85>
1681    const fn bin_count(count: u8) -> Option<u8> {
1682        match count {
1683            0 => None,
1684            1 => Some(1),
1685            2 => Some(2),
1686            3 => Some(4),
1687            4..=7 => Some(8),
1688            8..=15 => Some(16),
1689            16..=31 => Some(32),
1690            32..=127 => Some(64),
1691            128..=255 => Some(128),
1692        }
1693    }
1694
1695    /// Sets the stipend to the intrinsic gas of `tx` in `evm_env`, with the access list cheatcodes
1696    /// applied to it.
1697    fn set_stipend(&mut self, evm_env: &EvmEnvFor<FEN>, mut tx: TransactionRequestFor<FEN>) {
1698        if let Some(access_list) =
1699            self.cheatcodes.as_ref().and_then(|cheats| cheats.applied_access_list.clone())
1700        {
1701            tx.set_access_list(access_list);
1702        }
1703        self.stipend = calculate_stipend::<FEN>(evm_env, &tx);
1704    }
1705
1706    /// Update provided history map with sancov coverage info collected during this call.
1707    /// Uses AFL-style hitcount binning.
1708    pub fn merge_sancov_coverage(&mut self, history_map: &mut Vec<u8>) -> (bool, bool) {
1709        let mut new_coverage = false;
1710        let mut is_edge = false;
1711        if let Some(x) = &mut self.sancov_coverage {
1712            if history_map.len() < x.len() {
1713                history_map.resize(x.len(), 0);
1714            }
1715            for (curr, hist) in std::iter::zip(x.iter_mut(), history_map.iter_mut()) {
1716                if *curr > 0 {
1717                    if let Some(bucket) = Self::bin_count(*curr)
1718                        && *hist < bucket
1719                    {
1720                        if *hist == 0 {
1721                            is_edge = true;
1722                        }
1723                        *hist = bucket;
1724                        new_coverage = true;
1725                    }
1726                    *curr = 0;
1727                }
1728            }
1729        }
1730        (new_coverage, is_edge)
1731    }
1732
1733    /// Merge both EVM and sancov coverage into their respective history maps.
1734    /// Returns `(new_coverage, is_edge)` — true if either domain produced new coverage.
1735    pub fn merge_all_coverage(
1736        &mut self,
1737        evm_history: &mut Vec<u8>,
1738        evm_edge_indices: &mut EdgeIndexMap,
1739        sancov_history: &mut Vec<u8>,
1740    ) -> (bool, bool) {
1741        let (new_evm, edge_evm) = self.merge_edge_coverage(evm_history, evm_edge_indices);
1742        let (new_san, edge_san) = self.merge_sancov_coverage(sancov_history);
1743        (new_evm || new_san, edge_evm || edge_san)
1744    }
1745
1746    /// Returns the outcome of this call, to check that a replay of the same input reproduced it.
1747    ///
1748    /// `None` when its failure provenance was not recorded.
1749    pub fn raw_failure(&self) -> Option<RawFailure> {
1750        Some(RawFailure {
1751            exit_reason: self.exit_reason,
1752            result: self.result.clone(),
1753            reverter: self.reverter,
1754            gas_used: self.gas_used,
1755            provenance: self.failure_provenance?,
1756        })
1757    }
1758}
1759
1760/// The outcome of a call, see [`RawCallResult::raw_failure`].
1761///
1762/// A replay that took a different path can return identical data with the same gas, such as when
1763/// two `REVERT`s of the same data cost the same, or two instances of a contract fail the same
1764/// assertion, so the provenance tells where it failed.
1765#[derive(Clone, Debug, PartialEq, Eq)]
1766pub struct RawFailure {
1767    /// See [`RawCallResult::exit_reason`].
1768    pub exit_reason: Option<InstrStop>,
1769    /// See [`RawCallResult::result`].
1770    pub result: Bytes,
1771    /// See [`RawCallResult::reverter`].
1772    pub reverter: Option<Address>,
1773    /// See [`RawCallResult::gas_used`].
1774    pub gas_used: u64,
1775    /// See [`RawCallResult::failure_provenance`].
1776    pub provenance: B256,
1777}
1778
1779/// The result of a call.
1780pub struct CallResult<T = DynSolValue, FEN: FoundryEvmNetwork = EthEvmNetwork> {
1781    /// The raw result of the call.
1782    pub raw: RawCallResult<FEN>,
1783    /// The decoded result of the call.
1784    pub decoded_result: T,
1785}
1786
1787impl<T, FEN: FoundryEvmNetwork> std::ops::Deref for CallResult<T, FEN> {
1788    type Target = RawCallResult<FEN>;
1789
1790    #[inline]
1791    fn deref(&self) -> &Self::Target {
1792        &self.raw
1793    }
1794}
1795
1796impl<T, FEN: FoundryEvmNetwork> std::ops::DerefMut for CallResult<T, FEN> {
1797    #[inline]
1798    fn deref_mut(&mut self) -> &mut Self::Target {
1799        &mut self.raw
1800    }
1801}
1802
1803/// Returns the intrinsic gas `tx` pays before execution in `evm_env`.
1804pub fn calculate_stipend<FEN: FoundryEvmNetwork>(
1805    evm_env: &EvmEnvFor<FEN>,
1806    tx: &TransactionRequestFor<FEN>,
1807) -> u64 {
1808    let access_list = tx.access_list();
1809    evm2::ethereum::intrinsic_and_floor_gas(
1810        &evm_env.version,
1811        tx.from().unwrap_or_default(),
1812        tx.kind().unwrap_or(TxKind::Create),
1813        tx.input().unwrap_or_default(),
1814        access_list.map_or(0, |list| list.len() as u64),
1815        access_list.map_or(0, |list| list.iter().map(|item| item.storage_keys.len() as u64).sum()),
1816        tx.value().unwrap_or_default(),
1817    )
1818    .0
1819}
1820
1821/// Converts the data aggregated in the `inspector` and `execution` to a `RawCallResult`.
1822fn convert_executed_result<FEN: FoundryEvmNetwork>(
1823    execution: Execution<FEN>,
1824    mut inspector: InspectorStack<FEN>,
1825    backend: &Backend<FEN>,
1826) -> eyre::Result<RawCallResult<FEN>> {
1827    let Execution { result: tx_result, state: state_changeset, env: evm_env, cancelled } =
1828        execution;
1829    let exit_reason = tx_result.stop;
1830    let gas_refunded = if tx_result.status { tx_result.refunded } else { 0 };
1831    let gas_used = tx_result.tx_gas_used();
1832    let created_address = tx_result.created_address.filter(|_| tx_result.status);
1833    let result = if created_address.is_some() { Bytes::new() } else { tx_result.output };
1834
1835    let sancov_edges = inspector.inner.sancov_edges;
1836    let sancov_trace_cmp = inspector.inner.sancov_trace_cmp;
1837    let instrumented_edges = inspector.inner.instrumented_edges;
1838    let instrumented_cmp_log = inspector.inner.instrumented_cmp_log;
1839    let observed_calls = inspector
1840        .inner
1841        .fuzzer
1842        .as_mut()
1843        .map(|fuzzer| fuzzer.take_observed_calls())
1844        .unwrap_or_default();
1845
1846    let InspectorData {
1847        mut logs,
1848        labels,
1849        traces,
1850        line_coverage,
1851        mut edge_coverage,
1852        mut evm_cmp_values,
1853        mut cheatcodes,
1854        chisel_state,
1855        reverter,
1856    } = inspector.collect();
1857    let fork_block_number = cheatcodes
1858        .as_ref()
1859        .and_then(|cheats| cheats.fork_block_number_override)
1860        .or_else(|| backend.active_fork_block_number());
1861    let debug_bytecodes = collect_debug_bytecodes(traces.as_ref(), backend, &state_changeset);
1862
1863    if logs.is_empty() {
1864        logs = tx_result.logs;
1865    }
1866    // Compiler instrumentation replaces the edge and cmp-log inspectors, which are then off.
1867    if instrumented_edges {
1868        edge_coverage = Some(EdgeCoverage::Instrumented(edgecov::take_edges()));
1869    }
1870    if instrumented_cmp_log {
1871        evm_cmp_values = Some(edgecov::take_cmp_log()).filter(|cmps| !cmps.is_empty());
1872    }
1873
1874    let transactions = cheatcodes
1875        .as_ref()
1876        .map(|c| c.broadcastable_transactions.clone())
1877        .filter(|txs| !txs.is_empty());
1878    let skip_payloads =
1879        cheatcodes.as_mut().map(|c| std::mem::take(&mut c.skip_payloads)).unwrap_or_default();
1880    let failed_assertion = cheatcodes.as_mut().and_then(|c| c.failed_assertion.take());
1881    let failure_halt =
1882        cheatcodes.as_ref().and_then(|c| c.failure_trace.as_ref()).and_then(|trace| trace.halt());
1883    let failure_identity = cheatcodes
1884        .as_mut()
1885        .and_then(|c| c.failure_trace.as_mut())
1886        .and_then(|trace| trace.take_identity(exit_reason, &result));
1887    let failure_provenance =
1888        cheatcodes.as_mut().and_then(|c| c.failure_provenance.as_mut()).and_then(|p| p.take());
1889
1890    let mut raw = RawCallResult {
1891        exit_reason: Some(exit_reason),
1892        execution_cancelled: cancelled,
1893        reverted: !exit_reason.is_success(),
1894        has_state_snapshot_failure: backend.has_state_snapshot_failure(),
1895        result,
1896        gas_used,
1897        gas_refunded,
1898        stipend: 0,
1899        logs,
1900        labels,
1901        traces,
1902        debug_bytecodes,
1903        line_coverage,
1904        edge_coverage,
1905        evm_cmp_values,
1906        observed_calls,
1907        sancov_coverage: None,
1908        sancov_cmp_values: None,
1909        transactions,
1910        state_changeset,
1911        suspended_storage: Vec::new(),
1912        evm_env,
1913        cheatcodes,
1914        created_address,
1915        fork_block_number,
1916        chisel_state,
1917        reverter,
1918        skip_payloads,
1919        post_execution_backend: None,
1920        failed_assertion,
1921        failure_identity,
1922        failure_halt,
1923        failure_provenance,
1924    };
1925    if sancov_edges {
1926        SancovGuard::append_edges_into(&mut raw);
1927    }
1928    if sancov_trace_cmp {
1929        SancovGuard::drain_cmp_into(&mut raw);
1930    }
1931    Ok(raw)
1932}
1933
1934/// Returns the runtime bytecode of every traced account, as of after the call.
1935fn collect_debug_bytecodes<FEN: FoundryEvmNetwork>(
1936    traces: Option<&SparsedTraceArena>,
1937    backend: &Backend<FEN>,
1938    state: &PendingState,
1939) -> AddressHashMap<Bytes> {
1940    let mut bytecodes = HashMap::default();
1941    let Some(traces) = traces else { return bytecodes };
1942
1943    for node in traces.arena.nodes() {
1944        let address = node.trace.address;
1945        if bytecodes.contains_key(&address) {
1946            continue;
1947        }
1948
1949        let account = match state.account_info(&address) {
1950            Some(account) => account.clone(),
1951            None => {
1952                let Ok(Some(account)) = backend.basic(address) else { continue };
1953                account
1954            }
1955        };
1956        let code = match account.code {
1957            Some(code) if !code.is_empty() => Some(code),
1958            _ => backend.code_by_hash(account.code_hash).ok(),
1959        };
1960        let code = code.map(|code| code.original_bytes()).unwrap_or_default();
1961        if !code.is_empty() {
1962            bytecodes.insert(address, code);
1963        }
1964    }
1965
1966    bytecodes
1967}
1968
1969/// Timer for a fuzz test.
1970pub struct FuzzTestTimer {
1971    /// Inner fuzz test timer - (test start time, test duration).
1972    inner: Option<(Instant, Duration)>,
1973}
1974
1975impl FuzzTestTimer {
1976    pub fn new(timeout: Option<u32>) -> Self {
1977        Self { inner: timeout.map(|timeout| (Instant::now(), Duration::from_secs(timeout.into()))) }
1978    }
1979
1980    /// Whether the fuzz test timer is enabled.
1981    pub const fn is_enabled(&self) -> bool {
1982        self.inner.is_some()
1983    }
1984
1985    /// Whether the current fuzz test timed out and should be stopped.
1986    pub fn is_timed_out(&self) -> bool {
1987        self.inner.is_some_and(|(start, duration)| start.elapsed() > duration)
1988    }
1989}
1990
1991/// Helper struct to enable early exit behavior: when one test fails or run is interrupted,
1992/// all other tests stop early.
1993#[derive(Clone, Debug)]
1994pub struct EarlyExit {
1995    /// Shared atomic flag set to `true` when a failure occurs or ctrl-c received.
1996    inner: Arc<AtomicBool>,
1997    /// Whether to exit early on test failure (fail-fast mode).
1998    fail_fast: bool,
1999}
2000
2001impl EarlyExit {
2002    pub fn new(fail_fast: bool) -> Self {
2003        Self { inner: Arc::new(AtomicBool::new(false)), fail_fast }
2004    }
2005
2006    /// Records a test failure. Only triggers early exit if fail-fast mode is enabled.
2007    pub fn record_failure(&self) {
2008        if self.fail_fast {
2009            self.inner.store(true, Ordering::Relaxed);
2010        }
2011    }
2012
2013    /// Records a Ctrl-C interrupt. Always triggers early exit.
2014    pub fn record_ctrl_c(&self) {
2015        self.inner.store(true, Ordering::Relaxed);
2016    }
2017
2018    /// Whether tests should stop and exit early.
2019    pub fn should_stop(&self) -> bool {
2020        self.inner.load(Ordering::Relaxed)
2021    }
2022}
2023
2024/// Shared cancellation state for an active EVM execution.
2025#[derive(Clone, Debug)]
2026pub(crate) enum EvmExecutionCancellation {
2027    /// Cancellation driven only by the process-wide early-exit signal.
2028    EarlyExit(EarlyExit),
2029    /// Cancellation driven by the complete invariant campaign stop condition.
2030    Campaign { early_exit: EarlyExit, stop: Arc<AtomicBool>, deadline: Option<Instant> },
2031}
2032
2033impl EvmExecutionCancellation {
2034    pub(crate) const fn early_exit(early_exit: EarlyExit) -> Self {
2035        Self::EarlyExit(early_exit)
2036    }
2037
2038    pub(crate) const fn campaign(
2039        early_exit: EarlyExit,
2040        stop: Arc<AtomicBool>,
2041        deadline: Option<Instant>,
2042    ) -> Self {
2043        Self::Campaign { early_exit, stop, deadline }
2044    }
2045
2046    /// Returns whether execution should stop, optionally polling a campaign deadline.
2047    pub(crate) fn should_stop(&self, poll_deadline: bool) -> bool {
2048        match self {
2049            Self::EarlyExit(early_exit) => early_exit.should_stop(),
2050            Self::Campaign { early_exit, stop, deadline } => {
2051                if early_exit.should_stop() || stop.load(Ordering::Relaxed) {
2052                    return true;
2053                }
2054                if poll_deadline && deadline.is_some_and(|deadline| Instant::now() > deadline) {
2055                    stop.store(true, Ordering::Relaxed);
2056                    return true;
2057                }
2058                false
2059            }
2060        }
2061    }
2062
2063    pub(crate) fn request_stop(&self) {
2064        if let Self::Campaign { stop, .. } = self {
2065            stop.store(true, Ordering::Relaxed);
2066        }
2067    }
2068
2069    /// Returns whether a campaign stop was requested or its deadline was observed.
2070    pub(crate) fn stop_requested(&self) -> bool {
2071        matches!(self, Self::Campaign { stop, .. } if stop.load(Ordering::Relaxed))
2072    }
2073
2074    pub(crate) const fn early_exit_ref(&self) -> &EarlyExit {
2075        match self {
2076            Self::EarlyExit(early_exit) | Self::Campaign { early_exit, .. } => early_exit,
2077        }
2078    }
2079}
2080
2081/// Returns whether a nested revert can be ignored when fail-on-revert is disabled.
2082#[inline]
2083pub fn should_ignore_revert(
2084    fail_on_revert: bool,
2085    target: Address,
2086    reverter: Option<Address>,
2087    extra_cheatcode_addresses: &[Address],
2088) -> bool {
2089    !fail_on_revert
2090        && reverter.is_some_and(|reverter| {
2091            reverter != target
2092                && reverter != CHEATCODE_ADDRESS
2093                && !extra_cheatcode_addresses.contains(&reverter)
2094        })
2095}
2096
2097/// Derives the deterministic RNG seed for a fuzz or invariant worker.
2098///
2099/// Worker 0 keeps the configured seed, so a single worker replays the same sequence.
2100pub(crate) fn worker_seed(seed: U256, worker_id: u32) -> U256 {
2101    if worker_id == 0 {
2102        seed
2103    } else {
2104        let seed_data = [&seed.to_be_bytes::<32>()[..], &worker_id.to_be_bytes()[..]].concat();
2105        keccak256(seed_data).into()
2106    }
2107}
2108
2109#[cfg(test)]
2110mod tests {
2111    use super::*;
2112    use crate::inspectors::{EdgeCovHit, EdgeKey};
2113    use alloy_eips::eip4788::SYSTEM_ADDRESS;
2114    use alloy_primitives::{address, bytes};
2115    use alloy_rpc_types::TransactionRequest;
2116    use evm2::{OpcodeSet, SpecId, interpreter::opcode::OpCode};
2117    use foundry_cheatcodes::{
2118        CheatsConfig,
2119        Vm::{
2120            assertEq_1Call, assertGt_0Call, assertLt_0Call, assertTrue_1Call,
2121            broadcastRawTransactionCall, loadCall, mockCallRevert_1Call,
2122            revertToStateAndDeleteCall, revertToStateCall, snapshotStateCall, storeCall,
2123        },
2124    };
2125    use foundry_config::Config;
2126    use foundry_evm_core::{
2127        constants::MAGIC_SKIP,
2128        edgecov::{InstrumentedEdgeHit, MAX_CMP_OBSERVATIONS_PER_SITE},
2129        evm::TempoEvmNetwork,
2130        opts::EvmOpts,
2131    };
2132    use foundry_evm_traces::{
2133        InternalTraceMode, StackSnapshotType, TracingInspector, TracingInspectorConfig,
2134    };
2135    use std::{sync::mpsc, thread};
2136
2137    #[cfg(feature = "monad")]
2138    use foundry_evm_core::constants::MONAD_CHEATCODE_ADDRESS;
2139
2140    fn eth_executor(builder: ExecutorBuilder<EthEvmNetwork>) -> Executor<EthEvmNetwork> {
2141        test_executor(builder, NetworkConfigs::default())
2142    }
2143
2144    fn cheats_config() -> Arc<CheatsConfig> {
2145        Arc::new(CheatsConfig::new(&Config::default(), EvmOpts::default(), None, None, false))
2146    }
2147
2148    /// Returns a fee-less legacy transaction from [`CALLER`].
2149    fn replay_tx(
2150        nonce: u64,
2151        kind: TxKind,
2152        input: &'static [u8],
2153    ) -> Recovered<TxFor<EthEvmNetwork>> {
2154        let mut request = TransactionRequest::default()
2155            .from(CALLER)
2156            .nonce(nonce)
2157            .gas_limit(100_000)
2158            .gas_price(0)
2159            .input(Bytes::from_static(input).into());
2160        request.set_kind(kind);
2161        TypesFor::<EthEvmNetwork>::tx_from_request(request).unwrap()
2162    }
2163
2164    fn dense_call(edge: EdgeKey) -> RawCallResult {
2165        RawCallResult {
2166            edge_coverage: Some(EdgeCoverage::CollisionFree(vec![EdgeCovHit { edge, count: 1 }])),
2167            ..Default::default()
2168        }
2169    }
2170
2171    #[test]
2172    fn nested_revert_is_ignored_only_when_allowed() {
2173        let target = Address::repeat_byte(0x11);
2174        let nested = Address::repeat_byte(0x22);
2175
2176        assert!(should_ignore_revert(false, target, Some(nested), &[]));
2177        assert!(!should_ignore_revert(true, target, Some(nested), &[]));
2178        assert!(!should_ignore_revert(false, target, Some(target), &[]));
2179        assert!(!should_ignore_revert(false, target, Some(CHEATCODE_ADDRESS), &[]));
2180        assert!(!should_ignore_revert(false, target, None, &[]));
2181    }
2182
2183    #[cfg(feature = "monad")]
2184    #[test]
2185    fn network_cheatcode_revert_handling_is_monad_specific() {
2186        let target = Address::repeat_byte(0x11);
2187
2188        assert!(should_ignore_revert(false, target, Some(MONAD_CHEATCODE_ADDRESS), &[]));
2189        assert!(!should_ignore_revert(
2190            false,
2191            target,
2192            Some(MONAD_CHEATCODE_ADDRESS),
2193            &[MONAD_CHEATCODE_ADDRESS],
2194        ));
2195    }
2196
2197    #[cfg(feature = "monad")]
2198    #[test]
2199    fn executor_tooling_follows_concrete_builder() {
2200        let ethereum =
2201            test_executor(ExecutorBuilder::<EthEvmNetwork>::new(), NetworkConfigs::with_monad());
2202        assert!(ethereum.backend().networks().is_monad());
2203        assert!(!ethereum.backend().is_persistent(&MONAD_CHEATCODE_ADDRESS));
2204
2205        let monad =
2206            test_executor(ExecutorBuilder::<MonadEvmNetwork>::new(), NetworkConfigs::with_monad());
2207        assert!(monad.backend().networks().is_monad());
2208        assert!(monad.backend().is_persistent(&MONAD_CHEATCODE_ADDRESS));
2209        // Each cheatcode account keeps its fixed code hash.
2210        let code_hash = |address| monad.account(address).unwrap().code_hash;
2211        assert_eq!(code_hash(CHEATCODE_ADDRESS), CHEATCODE_CONTRACT_HASH);
2212        assert_eq!(code_hash(MONAD_CHEATCODE_ADDRESS), keccak256(MONAD_CHEATCODE_ADDRESS));
2213    }
2214
2215    #[test]
2216    fn tempo_labels_follow_concrete_builder() {
2217        let ethereum =
2218            test_executor(ExecutorBuilder::<EthEvmNetwork>::new(), NetworkConfigs::with_tempo());
2219        assert!(ethereum.inspector().tempo_labels.is_none());
2220
2221        let tempo =
2222            test_executor(ExecutorBuilder::<TempoEvmNetwork>::new(), NetworkConfigs::default());
2223        assert!(tempo.inspector().tempo_labels.is_some());
2224    }
2225
2226    #[test]
2227    fn collision_free_edge_merge_uses_stable_indices() {
2228        let first =
2229            EdgeKey { address: Address::ZERO, depth: None, pc: 0, jump_dest: U256::from(10) };
2230        let second =
2231            EdgeKey { address: Address::ZERO, depth: None, pc: 0, jump_dest: U256::from(20) };
2232        let mut history = Vec::new();
2233        let mut edge_indices = EdgeIndexMap::default();
2234
2235        assert_eq!(
2236            dense_call(first).merge_edge_coverage(&mut history, &mut edge_indices),
2237            (true, true)
2238        );
2239        assert_eq!(history, [1]);
2240
2241        assert_eq!(
2242            dense_call(second).merge_edge_coverage(&mut history, &mut edge_indices),
2243            (true, true)
2244        );
2245        assert_eq!(history, [1, 1]);
2246
2247        assert_eq!(
2248            dense_call(first).merge_edge_coverage(&mut history, &mut edge_indices),
2249            (false, false)
2250        );
2251        assert_eq!(history, [1, 1]);
2252    }
2253
2254    #[test]
2255    fn collision_free_edge_merge_handles_sparse_observation_indices() {
2256        let first =
2257            EdgeKey { address: Address::ZERO, depth: None, pc: 0, jump_dest: U256::from(10) };
2258        let second =
2259            EdgeKey { address: Address::ZERO, depth: None, pc: 0, jump_dest: U256::from(20) };
2260        let mut edge_indices = EdgeIndexMap::default();
2261        edge_indices.edge_index(first);
2262        edge_indices.edge_index(second);
2263        let mut history = Vec::new();
2264
2265        assert_eq!(
2266            dense_call(second).merge_edge_coverage(&mut history, &mut edge_indices),
2267            (true, true)
2268        );
2269        assert_eq!(history, [0, 1]);
2270    }
2271
2272    #[test]
2273    fn instrumented_edge_merge_indexes_history_by_id() {
2274        let mut history = Vec::new();
2275        let mut edge_indices = EdgeIndexMap::default();
2276        let mut merge = |hits: &[(u32, u8)]| {
2277            let hits = hits.iter().map(|&(id, count)| InstrumentedEdgeHit { id, count }).collect();
2278            RawCallResult::<EthEvmNetwork> {
2279                edge_coverage: Some(EdgeCoverage::Instrumented(hits)),
2280                ..Default::default()
2281            }
2282            .merge_edge_coverage(&mut history, &mut edge_indices)
2283        };
2284
2285        // First hit of an ID is a new edge, a higher hit-count bucket only a new feature.
2286        assert_eq!(merge(&[(3, 1)]), (true, true));
2287        assert_eq!(merge(&[(3, 1)]), (false, false));
2288        assert_eq!(merge(&[(3, 2)]), (true, false));
2289        assert_eq!(merge(&[(1, 1), (3, 1)]), (true, true));
2290        assert_eq!(history, [0, 1, 0, 2]);
2291        // The ID space is independent of the inspector's edge indices.
2292        assert_eq!(edge_indices.edge_count(), 0);
2293    }
2294
2295    /// Runtime code that hits edge 5 twice and edge 7 once, then stops.
2296    const EDGECOV_CODE: &[u8] = &[
2297        0x61, 0x00, 0x05, 0xc0, // PUSH2 5; EDGECOV
2298        0x61, 0x00, 0x07, 0xc0, // PUSH2 7; EDGECOV
2299        0x61, 0x00, 0x05, 0xc0, // PUSH2 5; EDGECOV
2300        0x00, // STOP
2301    ];
2302
2303    /// An executor that runs the instrumentation opcodes when `opcode` is set, and collects their
2304    /// edges like a campaign with `instrumented_edges` when `collect` is set.
2305    fn edgecov_executor(opcode: bool, collect: bool) -> Executor<EthEvmNetwork> {
2306        let mut executor = eth_executor(ExecutorBuilder::default().gas_limit(1 << 20));
2307        let corpus = foundry_config::FuzzCorpusConfig {
2308            corpus_dir: Some("corpus".into()),
2309            instrumented_edges: collect,
2310            ..Default::default()
2311        };
2312        executor.inspector_mut().collect_edge_coverage_with_config(&corpus);
2313        executor.inspector_mut().enable_edgecov_opcode(opcode);
2314        executor
2315    }
2316
2317    fn instrumented_hits(result: &RawCallResult) -> Vec<(u32, u8)> {
2318        match &result.edge_coverage {
2319            Some(EdgeCoverage::Instrumented(hits)) => {
2320                hits.iter().map(|hit| (hit.id, hit.count)).collect()
2321            }
2322            other => panic!("expected instrumented edges, got {other:?}"),
2323        }
2324    }
2325
2326    #[test]
2327    fn edgecov_opcode_collects_instrumented_edges() {
2328        let mut executor = edgecov_executor(true, true);
2329        let target = Address::repeat_byte(0x11);
2330        executor.set_code(target, Bytecode::new_raw(Bytes::from_static(EDGECOV_CODE))).unwrap();
2331        let stop = Address::repeat_byte(0x12);
2332        executor.set_code(stop, Bytecode::new_raw(Bytes::from_static(&[0x00]))).unwrap();
2333
2334        let result = executor.call_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2335        assert_eq!(result.exit_reason, Some(InstrStop::Stop));
2336        assert_eq!(instrumented_hits(&result), [(5, 2), (7, 1)]);
2337
2338        // Instrumentation is gas-neutral: the same as a bare STOP.
2339        let bare = executor.call_raw(CALLER, stop, Bytes::new(), U256::ZERO).unwrap();
2340        assert_eq!(result.gas_used, bare.gas_used);
2341        // Hits are reset between calls.
2342        assert!(instrumented_hits(&bare).is_empty());
2343        let again = executor.call_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2344        assert_eq!(instrumented_hits(&again), [(5, 2), (7, 1)]);
2345    }
2346
2347    #[test]
2348    fn edgecov_opcode_is_undefined_unless_enabled() {
2349        let target = Address::repeat_byte(0x11);
2350
2351        let mut executor = edgecov_executor(false, false);
2352        executor.set_code(target, Bytecode::new_raw(Bytes::from_static(EDGECOV_CODE))).unwrap();
2353        let result = executor.call_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2354        assert!(result.reverted);
2355        assert_eq!(result.exit_reason, Some(InstrStop::OpcodeNotFound));
2356
2357        // Executing without collecting runs the code and reports no instrumented coverage.
2358        let mut executor = edgecov_executor(true, false);
2359        executor.set_code(target, Bytecode::new_raw(Bytes::from_static(EDGECOV_CODE))).unwrap();
2360        let result = executor.call_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2361        assert_eq!(result.exit_reason, Some(InstrStop::Stop));
2362        assert!(!matches!(result.edge_coverage, Some(EdgeCoverage::Instrumented(_))));
2363    }
2364
2365    /// Runtime code with each comparison opcode once, then a loop whose `EQ` site runs 11 times.
2366    const CMP_CODE: &[u8] = &[
2367        0x60, 0x02, 0x60, 0x01, 0x14, 0x50, // EQ(1, 2)
2368        0x60, 0x02, 0x60, 0x01, 0x10, 0x50, // LT(1, 2)
2369        0x60, 0x02, 0x60, 0x01, 0x11, 0x50, // GT(1, 2)
2370        0x60, 0x02, 0x60, 0x01, 0x12, 0x50, // SLT(1, 2)
2371        0x60, 0x02, 0x60, 0x01, 0x13, 0x50, // SGT(1, 2)
2372        0x60, 0x00, 0x15, 0x50, // ISZERO(0)
2373        0x60, 0x00, // i = 0
2374        0x5b, // 36: JUMPDEST
2375        0x80, 0x60, 0x0a, 0x14, // EQ(10, i)
2376        0x60, 0x32, 0x57, // JUMPI to 50 when i == 10
2377        0x60, 0x01, 0x01, // i += 1
2378        0x60, 0x24, 0x56, // JUMP to 36
2379        0x5b, 0x50, 0x00, // 50: JUMPDEST; POP; STOP
2380    ];
2381
2382    /// [`CMP_CODE`] as a coverage build instruments it: `PUSH2 <site << 8 | opcode>; CMPLOG` before
2383    /// each comparison but `ISZERO`, with sites 1 to 6.
2384    const CMP_PROBED_CODE: &[u8] = &[
2385        0x60, 0x02, 0x60, 0x01, 0x61, 0x01, 0x14, 0xc1, 0x14, 0x50, // EQ(1, 2)
2386        0x60, 0x02, 0x60, 0x01, 0x61, 0x02, 0x10, 0xc1, 0x10, 0x50, // LT(1, 2)
2387        0x60, 0x02, 0x60, 0x01, 0x61, 0x03, 0x11, 0xc1, 0x11, 0x50, // GT(1, 2)
2388        0x60, 0x02, 0x60, 0x01, 0x61, 0x04, 0x12, 0xc1, 0x12, 0x50, // SLT(1, 2)
2389        0x60, 0x02, 0x60, 0x01, 0x61, 0x05, 0x13, 0xc1, 0x13, 0x50, // SGT(1, 2)
2390        0x60, 0x00, 0x15, 0x50, // ISZERO(0)
2391        0x60, 0x00, // i = 0
2392        0x5b, // 56: JUMPDEST
2393        0x80, 0x60, 0x0a, 0x61, 0x06, 0x14, 0xc1, 0x14, // EQ(10, i)
2394        0x60, 0x4a, 0x57, // JUMPI to 74 when i == 10
2395        0x60, 0x01, 0x01, // i += 1
2396        0x60, 0x38, 0x56, // JUMP to 56
2397        0x5b, 0x50, 0x00, // 74: JUMPDEST; POP; STOP
2398    ];
2399
2400    fn cmp_values(executor: &Executor<EthEvmNetwork>, target: Address) -> Vec<CmpOperands> {
2401        let result = executor.call_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2402        assert_eq!(result.exit_reason, Some(InstrStop::Stop));
2403        result.evm_cmp_values.unwrap_or_default()
2404    }
2405
2406    #[test]
2407    fn instrumented_cmp_log_matches_inspector() {
2408        let target = Address::repeat_byte(0x31);
2409        let mut inspected = edgecov_executor(false, false);
2410        inspected.inspector_mut().collect_evm_cmp_log(true);
2411        inspected.set_code(target, Bytecode::new_raw(Bytes::from_static(CMP_CODE))).unwrap();
2412        let expected = cmp_values(&inspected, target);
2413        // Each opcode once, and the loop site capped at its observation limit.
2414        assert_eq!(expected.len(), 6 + usize::from(MAX_CMP_OBSERVATIONS_PER_SITE));
2415        assert_eq!(
2416            expected[..6].iter().map(|cmp| cmp.opcode).collect::<Vec<_>>(),
2417            [0x14, 0x10, 0x11, 0x12, 0x13, 0x15]
2418        );
2419        assert_eq!((expected[0].op1, expected[0].op2), (U256::from(1), U256::from(2)));
2420        assert_eq!(expected[0].address, target);
2421
2422        // Instrumented code reports the same operands from its `CMPLOG` probes, with each site ID
2423        // in place of the comparison's program counter. `ISZERO` is not probed. No inspector steps
2424        // opcodes for them.
2425        let mut instrumented = edgecov_executor(true, true);
2426        instrumented.inspector_mut().collect_evm_cmp_log(true);
2427        assert!(instrumented.inspector().edge_coverage.is_none());
2428        instrumented
2429            .set_code(target, Bytecode::new_raw(Bytes::from_static(CMP_PROBED_CODE)))
2430            .unwrap();
2431        let sites =
2432            (1..=5).chain(std::iter::repeat_n(6, usize::from(MAX_CMP_OBSERVATIONS_PER_SITE)));
2433        let probed = expected
2434            .iter()
2435            .filter(|cmp| cmp.opcode != 0x15)
2436            .zip(sites)
2437            .map(|(cmp, site)| CmpOperands { pc: site, ..*cmp })
2438            .collect::<Vec<_>>();
2439        assert_eq!(cmp_values(&instrumented, target), probed);
2440
2441        // Without cmp-log, the probes still run and record nothing.
2442        instrumented.inspector_mut().collect_evm_cmp_log(false);
2443        assert!(cmp_values(&instrumented, target).is_empty());
2444    }
2445
2446    #[test]
2447    fn cheatcode_skip_payload_is_classified_as_skip() {
2448        let raw = RawCallResult::<EthEvmNetwork> {
2449            reverted: true,
2450            result: Bytes::from_static(b"FOUNDRY::SKIPwith reason"),
2451            skip_payloads: vec![Bytes::from_static(b"FOUNDRY::SKIPwith reason")],
2452            ..Default::default()
2453        };
2454
2455        let err = raw.into_evm_error(None);
2456        assert!(matches!(err, EvmError::Skip(_)));
2457    }
2458
2459    #[test]
2460    fn forged_skip_payload_is_execution_error() {
2461        let raw = RawCallResult::<EthEvmNetwork> {
2462            reverted: true,
2463            result: Bytes::from_static(MAGIC_SKIP),
2464            reverter: Some(CHEATCODE_ADDRESS),
2465            ..Default::default()
2466        };
2467
2468        let err = raw.into_evm_error(None);
2469        assert!(matches!(err, EvmError::Execution(_)));
2470    }
2471
2472    #[test]
2473    fn mismatched_skip_payload_is_execution_error() {
2474        let raw = RawCallResult::<EthEvmNetwork> {
2475            reverted: true,
2476            result: Bytes::from_static(b"FOUNDRY::SKIPforged"),
2477            skip_payloads: vec![Bytes::from_static(b"FOUNDRY::SKIPgenuine")],
2478            ..Default::default()
2479        };
2480
2481        let err = raw.into_evm_error(None);
2482        assert!(matches!(err, EvmError::Execution(_)));
2483    }
2484
2485    #[test]
2486    fn block_replay_commits_prefix_and_traces_only_target() {
2487        let mut executor = eth_executor(ExecutorBuilder::default().gas_limit(1 << 20));
2488        executor.set_balance(CALLER, U256::MAX).unwrap();
2489        executor.set_trace_requirements(TraceRequirements::none().with_calls(true));
2490
2491        let address = Address::repeat_byte(0x11);
2492        // Increment slot zero and return its new value.
2493        executor
2494            .set_code(
2495                address,
2496                Bytecode::new_raw(Bytes::from_static(&[
2497                    0x60, 0x00, 0x54, 0x60, 0x01, 0x01, 0x80, 0x60, 0x00, 0x55, 0x60, 0x00, 0x52,
2498                    0x60, 0x20, 0x60, 0x00, 0xf3,
2499                ])),
2500            )
2501            .unwrap();
2502        let prefix = replay_tx(0, TxKind::Call(address), &[]);
2503        let reverted_create = replay_tx(1, TxKind::Create, &[0x5f, 0x5f, 0xfd]);
2504        let target = replay_tx(2, TxKind::Call(address), &[]);
2505
2506        let env = *executor.evm_env();
2507        let result = executor
2508            .transact_with_block_replay(
2509                env,
2510                &target,
2511                TxKind::Call(address),
2512                &[(B256::repeat_byte(1), prefix), (B256::repeat_byte(2), reverted_create)],
2513            )
2514            .unwrap();
2515
2516        assert_eq!(result.result, Bytes::from(B256::with_last_byte(2).0));
2517        assert_eq!(executor.get_nonce(CALLER).unwrap(), 3);
2518        assert_eq!(executor.backend().storage(address, U256::ZERO).unwrap(), U256::from(2));
2519        assert_eq!(result.traces.unwrap().arena.nodes().len(), 1);
2520    }
2521
2522    #[test]
2523    fn block_replay_initializes_create_target_from_canonical_nonce() {
2524        let mut executor = eth_executor(ExecutorBuilder::default().gas_limit(1 << 20));
2525        executor.set_balance(CALLER, U256::MAX).unwrap();
2526
2527        let prefix = replay_tx(0, TxKind::Call(Address::repeat_byte(0x11)), &[]);
2528        let target = replay_tx(1, TxKind::Create, &[0x00]);
2529        let expected = CALLER.create(1);
2530
2531        let env = *executor.evm_env();
2532        let result = executor
2533            .transact_with_block_replay(
2534                env,
2535                &target,
2536                TxKind::Create,
2537                &[(B256::repeat_byte(1), prefix)],
2538            )
2539            .unwrap();
2540
2541        assert_eq!(result.created_address, Some(expected));
2542        assert!(executor.backend().is_persistent(&expected));
2543        assert!(executor.backend().has_cheatcode_access(&expected));
2544    }
2545
2546    #[test]
2547    fn block_replay_preserves_successful_prefix_deployment() {
2548        let mut executor = eth_executor(ExecutorBuilder::default().gas_limit(1 << 20));
2549        executor.set_balance(CALLER, U256::MAX).unwrap();
2550
2551        let deployed = CALLER.create(0);
2552        let prefix = replay_tx(0, TxKind::Create, &[0x00]);
2553        let target = replay_tx(1, TxKind::Call(deployed), &[]);
2554
2555        let env = *executor.evm_env();
2556        executor
2557            .transact_with_block_replay(
2558                env,
2559                &target,
2560                TxKind::Call(deployed),
2561                &[(B256::repeat_byte(1), prefix)],
2562            )
2563            .unwrap();
2564
2565        assert!(executor.backend().is_persistent(&deployed));
2566    }
2567
2568    #[cfg(feature = "monad")]
2569    #[test]
2570    fn monad_block_replay_executes_canonical_protocol_transactions() {
2571        const STAKING: Address =
2572            alloy_primitives::address!("0x0000000000000000000000000000000000001000");
2573        let system = foundry_common::MONAD_SYSTEM_ADDRESS;
2574        let system_tx = |nonce, gas_limit, input: Vec<u8>| {
2575            Recovered::new_unchecked(
2576                evm2::ethereum::TxEnvelope::Legacy(alloy_consensus::TxLegacy {
2577                    nonce,
2578                    gas_limit,
2579                    to: TxKind::Call(STAKING),
2580                    input: input.into(),
2581                    ..Default::default()
2582                }),
2583                system,
2584            )
2585        };
2586        let snapshot = system_tx(0, 0, keccak256("syscallSnapshot()")[..4].to_vec());
2587        let gas_paying = system_tx(1, 100_000, keccak256("syscallSnapshot()")[..4].to_vec());
2588        let epoch_change = system_tx(
2589            2,
2590            0,
2591            [&keccak256("syscallOnEpochChange(uint64)")[..4], &B256::with_last_byte(1)[..]]
2592                .concat(),
2593        );
2594        let mut executor = test_executor(
2595            ExecutorBuilder::<MonadEvmNetwork>::new().gas_limit(1 << 20),
2596            NetworkConfigs::with_monad(),
2597        );
2598        // Historical staking state is funded; EIP-161 prunes a touched empty account's storage.
2599        executor.set_balance(STAKING, U256::ONE).unwrap();
2600        let env = *executor.evm_env();
2601        let context = || BlockContext::new(Vec::new(), Vec::new(), Vec::new());
2602
2603        // The canonical prefix syscall replays as a protocol call, the gas-paying system envelope
2604        // the caller selected runs as an ordinary transaction, and the canonical target replays
2605        // at the prefix's nonce.
2606        let result = executor
2607            .transact_with_monad_block_replay(
2608                env,
2609                &epoch_change,
2610                TxKind::Call(STAKING),
2611                &[(B256::repeat_byte(1), snapshot), (B256::repeat_byte(2), gas_paying.clone())],
2612                context(),
2613            )
2614            .unwrap();
2615        assert!(!result.reverted);
2616        assert_eq!(result.gas_used, 0);
2617        assert_eq!(executor.get_nonce(system).unwrap(), 3);
2618        assert_eq!(executor.get_balance(system).unwrap(), U256::ZERO);
2619        assert_eq!(executor.get_balance(STAKING).unwrap(), U256::ONE);
2620        let epoch = U256::from(1) << 192;
2621        assert_eq!(executor.backend().storage(STAKING, U256::from(1)).unwrap(), epoch);
2622        assert_eq!(executor.backend().storage(STAKING, U256::from(2)).unwrap(), U256::ZERO);
2623
2624        // Reusing the accepted backend must not retain permission to replay protocol envelopes.
2625        let mut evm = executor.backend().create_evm();
2626        let next_snapshot = system_tx(3, 0, keccak256("syscallSnapshot()")[..4].to_vec());
2627        assert!(matches!(
2628            evm.transact(&next_snapshot),
2629            Err(evm2::registry::HandlerError::IntrinsicGasTooLow { .. })
2630        ));
2631
2632        // A non-canonical target from the system sender is rejected without effects.
2633        let error = executor
2634            .transact_with_monad_block_replay(
2635                env,
2636                &gas_paying,
2637                TxKind::Call(STAKING),
2638                &[],
2639                context(),
2640            )
2641            .unwrap_err();
2642        assert_eq!(
2643            error.root_cause().to_string(),
2644            "invalid Monad protocol transaction: gas limit must be zero, got 100000"
2645        );
2646        assert_eq!(executor.get_nonce(system).unwrap(), 3);
2647    }
2648
2649    #[test]
2650    fn set_spec_id_updates_spec_dependent_cfg_state() {
2651        let mut executor = eth_executor(ExecutorBuilder::default().spec_id(SpecId::HOMESTEAD));
2652        assert_eq!(
2653            executor.evm_env().version.gas_params,
2654            evm2::Version::new(SpecId::HOMESTEAD).gas_params
2655        );
2656        assert!(!executor.evm_env().version.feature(evm2::EvmFeatures::EIP8037));
2657
2658        executor.set_spec_id(SpecId::AMSTERDAM);
2659
2660        assert_eq!(executor.spec_id(), SpecId::AMSTERDAM);
2661        assert_eq!(
2662            executor.evm_env().version.gas_params,
2663            evm2::Version::new(SpecId::AMSTERDAM).gas_params
2664        );
2665        assert!(executor.evm_env().version.feature(evm2::EvmFeatures::EIP8037));
2666    }
2667
2668    #[test]
2669    fn calculate_stipend_uses_eip2780_transaction_context() {
2670        let caller = Address::repeat_byte(0x11);
2671        let recipient = Address::repeat_byte(0x22);
2672        let mut env = EvmFactoryFor::<EthEvmNetwork>::default()
2673            .env_with_spec(default_env::<EthEvmNetwork>(), SpecId::AMSTERDAM);
2674        let tx = TransactionRequest::default().from(caller).to(recipient);
2675
2676        // EIP-2780 base cost plus the EIP-8038 cold recipient access.
2677        assert_eq!(calculate_stipend::<EthEvmNetwork>(&env, &tx), 15_000);
2678        // A self-transfer pays no recipient access.
2679        let self_transfer = tx.clone().to(caller);
2680        assert_eq!(calculate_stipend::<EthEvmNetwork>(&env, &self_transfer), 12_000);
2681
2682        env = EvmFactoryFor::<EthEvmNetwork>::default().env_with_spec(env, SpecId::OSAKA);
2683        assert_eq!(calculate_stipend::<EthEvmNetwork>(&env, &tx), 21_000);
2684    }
2685
2686    #[test]
2687    fn amsterdam_intercepted_create_refunds_state_gas() {
2688        let mut executor = eth_executor(
2689            ExecutorBuilder::default()
2690                .inspectors(|stack| stack.cheatcodes(cheats_config()))
2691                .spec_id(SpecId::AMSTERDAM)
2692                .gas_limit(1_000_000),
2693        );
2694
2695        let target = Address::repeat_byte(0x11);
2696        // PUSH0; PUSH0; PUSH0; CREATE; POP; STOP.
2697        executor
2698            .set_code(
2699                target,
2700                Bytecode::new_raw(Bytes::from_static(&[0x5f, 0x5f, 0x5f, 0xf0, 0x50, 0x00])),
2701            )
2702            .unwrap();
2703        executor.inspector_mut().cheatcodes.as_mut().unwrap().core.intercept_next_create_call =
2704            true;
2705
2706        let result = executor.transact_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2707
2708        assert!(!result.reverted);
2709        // EIP-8037 account creation costs 183600 state gas.
2710        assert!(
2711            result.gas_used < 183_600,
2712            "failed CREATE retained its conditional state-gas charge"
2713        );
2714    }
2715
2716    #[test]
2717    fn amsterdam_mocked_call_revert_refunds_state_gas() {
2718        let mut executor = eth_executor(
2719            ExecutorBuilder::default()
2720                .inspectors(|stack| stack.cheatcodes(cheats_config()))
2721                .spec_id(SpecId::AMSTERDAM)
2722                .gas_limit(1_000_000),
2723        );
2724
2725        let target = Address::repeat_byte(0x11);
2726        let mocked = Address::repeat_byte(0x22);
2727        let mock = executor
2728            .transact_raw(
2729                CALLER,
2730                CHEATCODE_ADDRESS,
2731                mockCallRevert_1Call {
2732                    callee: mocked,
2733                    msgValue: U256::ONE,
2734                    data: Bytes::new(),
2735                    revertData: Bytes::new(),
2736                }
2737                .abi_encode()
2738                .into(),
2739                U256::ZERO,
2740            )
2741            .unwrap();
2742        assert!(!mock.reverted);
2743        executor.set_code(mocked, Bytecode::default()).unwrap();
2744        executor.set_balance(target, U256::ONE).unwrap();
2745
2746        // PUSH0 x4; PUSH1 1; PUSH20 <mocked>; GAS; CALL; POP; STOP.
2747        let mut code = vec![0x5f, 0x5f, 0x5f, 0x5f, 0x60, 0x01, 0x73];
2748        code.extend_from_slice(mocked.as_slice());
2749        code.extend_from_slice(&[0x5a, 0xf1, 0x50, 0x00]);
2750        executor.set_code(target, Bytecode::new_raw(code.into())).unwrap();
2751
2752        let result = executor.transact_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2753
2754        assert!(!result.reverted);
2755        // EIP-8037 account creation costs 183600 state gas.
2756        assert!(
2757            result.gas_used < 183_600,
2758            "reverted mocked CALL retained its conditional state-gas charge"
2759        );
2760    }
2761
2762    #[test]
2763    fn amsterdam_deploy_charges_create_state_gas_at_caller_nonce() {
2764        let mut executor = eth_executor(
2765            ExecutorBuilder::default().spec_id(SpecId::AMSTERDAM).gas_limit(1_000_000),
2766        );
2767        let sender = Address::repeat_byte(0x33);
2768        executor.set_account_nonce(sender, 5).unwrap();
2769        // A non-empty address for nonce 0 must not hide the charge for the address for nonce 5.
2770        executor.set_balance(sender.create(0), U256::ONE).unwrap();
2771
2772        let result = executor.deploy(sender, Bytes::new(), U256::ZERO, None).unwrap();
2773
2774        assert_eq!(result.address, sender.create(5));
2775        // An empty creation pays 24000 regular gas plus 183600 EIP-8037 account-creation gas.
2776        assert_eq!(result.raw.gas_used, 207_600);
2777    }
2778
2779    #[test]
2780    fn set_trace_requirements_replaces_trace_mode_between_transactions() {
2781        let mut executor = eth_executor(ExecutorBuilder::default().gas_limit(1 << 20));
2782        let target = Address::repeat_byte(0x11);
2783        // PUSH1 4; JUMP; STOP; JUMPDEST; PUSH1 1; PUSH1 0; SSTORE; STOP.
2784        executor
2785            .set_code(
2786                target,
2787                Bytecode::new_raw(Bytes::from_static(&[
2788                    0x60, 0x04, 0x56, 0x00, 0x5b, 0x60, 0x01, 0x60, 0x00, 0x55, 0x00,
2789                ])),
2790            )
2791            .unwrap();
2792
2793        let untraced = executor.transact_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2794        assert!(untraced.traces.is_none());
2795
2796        executor.set_trace_requirements(TraceRequirements::none().with_debug(true));
2797        let debug = executor.transact_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2798        let debug_steps = &debug.traces.as_ref().unwrap().nodes()[0].trace.steps;
2799        assert_eq!(debug_steps.len(), 7);
2800        assert!(debug_steps.iter().all(|step| step.stack.is_some() && step.memory.is_some()));
2801
2802        executor.set_trace_requirements(
2803            TraceRequirements::none().with_decode_internal(InternalTraceMode::Full),
2804        );
2805        let internal = executor.transact_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2806        let internal_steps = &internal.traces.as_ref().unwrap().nodes()[0].trace.steps;
2807        assert_eq!(internal_steps.len(), 2);
2808        assert!(internal_steps.iter().all(|step| step.stack.is_some() && step.memory.is_some()));
2809
2810        executor.set_trace_requirements(TraceRequirements::none());
2811        let untraced = executor.transact_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2812        assert!(untraced.traces.is_none());
2813    }
2814
2815    #[test]
2816    fn early_exit_interrupts_active_evm_execution() {
2817        const GAS_LIMIT: u64 = 1 << 24;
2818        let mut executor = eth_executor(ExecutorBuilder::default().gas_limit(GAS_LIMIT));
2819        let early_exit = EarlyExit::new(false);
2820        executor.inspector_mut().set_early_exit(early_exit.clone());
2821
2822        let target = Address::repeat_byte(0x11);
2823        // JUMPDEST; PUSH1 0; JUMP loops until the inspector observes the interrupt.
2824        executor
2825            .set_code(target, Bytecode::new_raw(Bytes::from_static(&[0x5b, 0x60, 0x00, 0x56])))
2826            .unwrap();
2827
2828        let (started_tx, started_rx) = mpsc::channel();
2829        let (result_tx, result_rx) = mpsc::channel();
2830        let handle = thread::spawn(move || {
2831            started_tx.send(()).unwrap();
2832            let result = executor.transact_raw(CALLER, target, Bytes::new(), U256::ZERO);
2833            let _ = result_tx.send(result);
2834        });
2835
2836        started_rx.recv().unwrap();
2837        thread::sleep(Duration::from_millis(1));
2838        early_exit.record_ctrl_c();
2839
2840        let result = result_rx.recv_timeout(Duration::from_secs(1));
2841        handle.join().unwrap();
2842        let result = result.expect("active EVM execution did not observe early exit").unwrap();
2843        assert!(result.execution_cancelled);
2844        assert!(!result.reverted);
2845        assert_eq!(result.exit_reason, Some(InstrStop::Stop));
2846        assert!(result.gas_used > 21_000, "interrupt fired before EVM execution started");
2847        assert!(result.gas_used < GAS_LIMIT, "execution ran out of gas instead of exiting");
2848    }
2849
2850    #[test]
2851    fn completed_execution_is_not_retroactively_cancelled() {
2852        let mut executor = eth_executor(ExecutorBuilder::default().gas_limit(1 << 24));
2853        let early_exit = EarlyExit::new(false);
2854        executor.inspector_mut().set_early_exit(early_exit.clone());
2855
2856        let target = Address::repeat_byte(0x11);
2857        executor.set_code(target, Bytecode::new_raw(Bytes::from_static(&[0x00]))).unwrap();
2858        let result = executor.transact_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2859        early_exit.record_ctrl_c();
2860
2861        assert!(!result.execution_cancelled);
2862        assert!(!result.reverted);
2863    }
2864
2865    #[test]
2866    fn campaign_deadline_interrupts_active_evm_execution() {
2867        const GAS_LIMIT: u64 = 1 << 24;
2868        let mut executor = eth_executor(ExecutorBuilder::default().gas_limit(GAS_LIMIT));
2869        let cancellation = EvmExecutionCancellation::campaign(
2870            EarlyExit::new(false),
2871            Arc::new(AtomicBool::new(false)),
2872            Some(Instant::now()),
2873        );
2874        executor.inspector_mut().set_execution_cancellation(cancellation);
2875
2876        let target = Address::repeat_byte(0x11);
2877        executor
2878            .set_code(target, Bytecode::new_raw(Bytes::from_static(&[0x5b, 0x60, 0x00, 0x56])))
2879            .unwrap();
2880
2881        let result = executor.transact_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2882        assert!(result.execution_cancelled);
2883        assert!(!result.reverted);
2884        assert_eq!(result.exit_reason, Some(InstrStop::Stop));
2885        assert!(result.gas_used < GAS_LIMIT, "execution ran out of gas instead of timing out");
2886    }
2887
2888    #[test]
2889    fn campaign_deadline_is_polled_at_calls() {
2890        let mut executor = eth_executor(ExecutorBuilder::default().gas_limit(1 << 24));
2891        let cancellation = EvmExecutionCancellation::campaign(
2892            EarlyExit::new(false),
2893            Arc::new(AtomicBool::new(false)),
2894            Some(Instant::now()),
2895        );
2896        executor.inspector_mut().set_execution_cancellation(cancellation);
2897
2898        let target = Address::repeat_byte(0x11);
2899        // PUSH0 x5; ADDRESS; GAS; CALL; STOP calls itself without a jump until the call stops.
2900        executor
2901            .set_code(
2902                target,
2903                Bytecode::new_raw(Bytes::from_static(&[
2904                    0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x30, 0x5a, 0xf1, 0x00,
2905                ])),
2906            )
2907            .unwrap();
2908
2909        let result = executor.transact_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2910        assert!(result.execution_cancelled);
2911        assert!(!result.reverted);
2912        assert_eq!(result.exit_reason, Some(InstrStop::Stop));
2913    }
2914
2915    #[test]
2916    fn filtered_tracer_pairs_steps_across_nested_calls_stepped_by_other_hooks() {
2917        let env = default_env::<EthEvmNetwork>();
2918        let mut executor = ExecutorBuilder::<EthEvmNetwork>::default()
2919            .inspectors(|stack| stack.cheatcodes(cheats_config()))
2920            .gas_limit(1 << 20)
2921            .build(
2922                env,
2923                TransactionRequest::default(),
2924                Backend::spawn(None, env).unwrap(),
2925                NetworkConfigs::default(),
2926            );
2927        let (outer, middle, inner) =
2928            (Address::repeat_byte(0x11), Address::repeat_byte(0x22), Address::repeat_byte(0x33));
2929        // The outer contract calls the middle one: PUSH0 x5; PUSH20 middle; GAS; CALL; STOP.
2930        let mut outer_code = vec![0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x73];
2931        outer_code.extend_from_slice(middle.as_slice());
2932        outer_code.extend_from_slice(&[0x5a, 0xf1, 0x00]);
2933        // The middle contract skips a jump, makes a successful static call, then reverts:
2934        // PUSH0; PUSH0; JUMPI; PUSH0 x4; PUSH20 inner; GAS; STATICCALL; PUSH0; PUSH0; REVERT.
2935        let mut middle_code = vec![0x5f, 0x5f, 0x57, 0x5f, 0x5f, 0x5f, 0x5f, 0x73];
2936        middle_code.extend_from_slice(inner.as_slice());
2937        middle_code.extend_from_slice(&[0x5a, 0xfa, 0x5f, 0x5f, 0xfd]);
2938        executor.set_code(outer, Bytecode::new_raw(outer_code.into())).unwrap();
2939        executor.set_code(middle, Bytecode::new_raw(middle_code.into())).unwrap();
2940        executor.set_code(inner, Bytecode::new_raw(Bytes::from_static(&[0x00]))).unwrap();
2941
2942        // The tracer steps only CALL, while the failure identity makes the cheatcodes step
2943        // everything and the edge coverage steps JUMPI. So the STATICCALL is stepped by the
2944        // cheatcodes alone, and the JUMPI by the cheatcodes and the edge coverage.
2945        let mut config =
2946            TracingInspectorConfig::none().steps().set_stack_snapshots(StackSnapshotType::Pushes);
2947        config.record_opcodes_filter =
2948            Some([OpCode::CALL.get()].into_iter().collect::<OpcodeSet>());
2949        executor.inspector_mut().set_tracer(Some(Box::new(TracingInspector::new(config))));
2950        executor.inspector_mut().collect_failure_identity(true);
2951        executor.inspector_mut().collect_edge_coverage(true);
2952
2953        let result = executor.call_raw(CALLER, outer, Bytes::new(), U256::ZERO).unwrap();
2954        let arena = result.traces.unwrap().arena;
2955        let steps = arena
2956            .nodes()
2957            .iter()
2958            .flat_map(|node| node.trace.steps.iter().map(move |step| (node.trace.address, step)))
2959            .collect::<Vec<_>>();
2960        assert_eq!(steps.len(), 1);
2961        let (address, call) = steps[0];
2962        assert_eq!(address, outer);
2963        assert_eq!(call.op, OpCode::CALL);
2964        // The outer CALL pushes 0, since the middle contract reverted.
2965        assert_eq!(call.push_stack.as_deref(), Some(&[U256::ZERO][..]));
2966    }
2967
2968    #[test]
2969    fn gas_price_opcode_reads_configured_gas_price() {
2970        let mut env = default_env::<EthEvmNetwork>();
2971        env.set_chain_id(1);
2972        let mut executor = ExecutorBuilder::<EthEvmNetwork>::default()
2973            .inspectors(|stack| stack.cheatcodes(cheats_config()))
2974            .gas_limit(1 << 20)
2975            .build(
2976                env,
2977                TransactionRequest::default().gas_price(7),
2978                Backend::spawn(None, env).unwrap(),
2979                NetworkConfigs::default(),
2980            );
2981        let target = Address::repeat_byte(0x11);
2982        // GASPRICE; PUSH0; MSTORE; PUSH1 32; PUSH0; RETURN.
2983        executor
2984            .set_code(
2985                target,
2986                Bytecode::new_raw(Bytes::from_static(&[0x3a, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3])),
2987            )
2988            .unwrap();
2989
2990        // Executions are fee-less, but the opcode reads the configured price.
2991        let result = executor.call_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
2992        assert_eq!(result.result, Bytes::from(B256::with_last_byte(7).0));
2993
2994        let sender = address!("5316812db67073c4d4af8bb3000c5b86c2877e94");
2995        let replay_target = address!("6fd0a0cff9a87adf51695b40b4fa267855a8f4c6");
2996        executor.set_balance(sender, U256::from(10u64.pow(18))).unwrap();
2997        // GASPRICE; PUSH0; SSTORE; STOP.
2998        executor.set_code(replay_target, Bytecode::new_raw(bytes!("3a5f5500"))).unwrap();
2999        // The signed transaction pays 100 wei per gas, independently of the configured price.
3000        let input = broadcastRawTransactionCall {
3001            data: bytes!("f860806483030d40946fd0a0cff9a87adf51695b40b4fa267855a8f4c6118025a03ebeabbcfe43c2c982e99b376b5fb6e765059d7f215533c8751218cac99bbd80a00a56cf5c382442466770a756e81272d06005c9e90fb8dbc5b53af499d5aca856"),
3002        }
3003        .abi_encode()
3004        .into();
3005        let result = executor.transact_raw(CALLER, CHEATCODE_ADDRESS, input, U256::ZERO).unwrap();
3006        assert!(!result.reverted, "{result:?}");
3007        assert_eq!(executor.backend().storage(replay_target, U256::ZERO).unwrap(), U256::from(100));
3008
3009        // The replay does not consume the outer transaction's configured price.
3010        let result = executor.call_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
3011        assert_eq!(result.result, Bytes::from(B256::with_last_byte(7).0));
3012    }
3013
3014    #[test]
3015    fn beacon_root_system_call_does_not_persist_system_address() {
3016        let mut executor = eth_executor(ExecutorBuilder::default().spec_id(SpecId::CANCUN));
3017        let before = executor.backend().basic(SYSTEM_ADDRESS).unwrap();
3018        let root = B256::repeat_byte(0x11);
3019
3020        executor.apply_beacon_root(root).unwrap();
3021
3022        assert_eq!(
3023            executor.backend().basic(SYSTEM_ADDRESS).unwrap(),
3024            before,
3025            "EIP-4788 system calls must not persist the system caller account",
3026        );
3027    }
3028
3029    #[test]
3030    fn storage_stored_on_absent_account_survives_commit() {
3031        let mut executor = eth_executor(
3032            ExecutorBuilder::default()
3033                .inspectors(|stack| stack.cheatcodes(cheats_config()))
3034                .gas_limit(1_000_000),
3035        );
3036        let target = Address::with_last_byte(0x31);
3037        let value = B256::with_last_byte(1);
3038        let store = storeCall { target, slot: B256::ZERO, value }.abi_encode();
3039        let stored = executor.transact_raw(CALLER, CHEATCODE_ADDRESS, store.into(), U256::ZERO);
3040        assert!(!stored.unwrap().reverted);
3041
3042        let load = loadCall { target, slot: B256::ZERO }.abi_encode();
3043        let loaded = executor.call_raw(CALLER, CHEATCODE_ADDRESS, load.into(), U256::ZERO).unwrap();
3044        assert_eq!(loaded.result, Bytes::from(value.0));
3045    }
3046
3047    #[test]
3048    fn worker_seed_preserves_master_seed_and_derives_workers() {
3049        let seed = U256::from(0x1234);
3050
3051        assert_eq!(worker_seed(seed, 0), seed);
3052        assert_ne!(worker_seed(seed, 1), seed);
3053        assert_ne!(worker_seed(seed, 1), worker_seed(seed, 2));
3054        assert_ne!(worker_seed(seed, 1), worker_seed(U256::from(0x5678), 1));
3055    }
3056
3057    #[test]
3058    fn call_commit_preserves_lifecycle_state() {
3059        let mut executor = eth_executor(
3060            ExecutorBuilder::default()
3061                .inspectors(|stack| stack.cheatcodes(cheats_config()))
3062                .gas_limit(1_000_000),
3063        );
3064        let target = Address::with_last_byte(0x31);
3065        executor.set_balance(target, U256::ONE).unwrap();
3066        // The cheatcode inspector cancels root-call nonce increments.
3067        executor.set_account_nonce(CALLER, 5).unwrap();
3068        let snapshot = snapshotStateCall {}.abi_encode();
3069        let restore = revertToStateCall { snapshotId: U256::ZERO }.abi_encode();
3070
3071        // Discarded calls must not retain snapshots.
3072        executor.call_raw(CALLER, CHEATCODE_ADDRESS, snapshot.clone().into(), U256::ZERO).unwrap();
3073        let missing = executor
3074            .call_raw(CALLER, CHEATCODE_ADDRESS, restore.clone().into(), U256::ZERO)
3075            .unwrap();
3076        assert_eq!(U256::from_be_slice(&missing.result), U256::ZERO);
3077
3078        let mut captured =
3079            executor.call_raw(CALLER, CHEATCODE_ADDRESS, snapshot.into(), U256::ZERO).unwrap();
3080        executor.commit(&mut captured);
3081        let store = storeCall { target, slot: B256::ZERO, value: B256::with_last_byte(7) };
3082        let mut written = executor
3083            .call_raw(CALLER, CHEATCODE_ADDRESS, store.abi_encode().into(), U256::ZERO)
3084            .unwrap();
3085        executor.commit(&mut written);
3086        assert_eq!(executor.backend().storage(target, U256::ZERO).unwrap(), U256::from(7));
3087
3088        let mut restored =
3089            executor.call_raw(CALLER, CHEATCODE_ADDRESS, restore.into(), U256::ZERO).unwrap();
3090        assert_eq!(U256::from_be_slice(&restored.result), U256::ONE);
3091        // Restored state stays detached until commit.
3092        assert_eq!(executor.backend().storage(target, U256::ZERO).unwrap(), U256::from(7));
3093        executor.commit(&mut restored);
3094        assert_eq!(executor.backend().storage(target, U256::ZERO).unwrap(), U256::ZERO);
3095        assert_eq!(executor.get_nonce(CALLER).unwrap(), 5);
3096    }
3097
3098    #[test]
3099    fn call_success_checks_restored_assertion_state() {
3100        for legacy in [false, true] {
3101            let mut executor = eth_executor(
3102                ExecutorBuilder::default()
3103                    .inspectors(|stack| stack.cheatcodes(cheats_config()))
3104                    .legacy_assertions(legacy)
3105                    .gas_limit(1_000_000),
3106            );
3107            let target = Address::with_last_byte(0x31);
3108            // DSTest-style failed(): return storage slot zero.
3109            let code = Bytes::from_static(&[0x5f, 0x54, 0x5f, 0x52, 0x60, 0x20, 0x5f, 0xf3]);
3110            executor.set_code(target, Bytecode::new_raw(code)).unwrap();
3111            let (account, slot) =
3112                if legacy { (target, U256::ZERO) } else { (CHEATCODE_ADDRESS, GLOBAL_FAIL_SLOT) };
3113            executor.backend_mut().insert_account_storage(account, slot, U256::ONE);
3114            let snapshot = snapshotStateCall {}.abi_encode();
3115            let captured = executor
3116                .transact_raw(CALLER, CHEATCODE_ADDRESS, snapshot.into(), U256::ZERO)
3117                .unwrap();
3118            let restore = revertToStateCall { snapshotId: U256::from_be_slice(&captured.result) }
3119                .abi_encode();
3120            executor.backend_mut().insert_account_storage(account, slot, U256::ZERO);
3121
3122            let mut restored =
3123                executor.call_raw(CALLER, CHEATCODE_ADDRESS, restore.into(), U256::ZERO).unwrap();
3124            assert!(!restored.reverted);
3125            // Legacy failed() ignores committed flags; the global check includes them.
3126            let pending = Cow::Borrowed(&restored.state_changeset);
3127            assert_eq!(executor.is_raw_call_success(target, pending, &restored), legacy);
3128            executor.commit(&mut restored);
3129            assert_eq!(executor.is_raw_call_mut_success(target, &mut restored), legacy);
3130        }
3131    }
3132
3133    #[cfg(feature = "monad")]
3134    #[test]
3135    fn monad_simulation_reports_consumption_for_success_revert_and_halt() {
3136        let target = Address::repeat_byte(0x11);
3137        for limit in [100_000, 1_000_000] {
3138            let mut executor = test_executor::<MonadEvmNetwork>(
3139                ExecutorBuilder::default().gas_limit(limit),
3140                NetworkConfigs::with_monad(),
3141            );
3142            for (code, stop, gas_used) in [
3143                (bytes!("00"), InstrStop::Stop, 21_000),
3144                (bytes!("5f5ffd"), InstrStop::Revert, 21_004),
3145                (bytes!("fe"), InstrStop::InvalidFEOpcode, limit),
3146            ] {
3147                executor.set_code(target, Bytecode::new_raw(code)).unwrap();
3148                let result = executor.call_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
3149                assert_eq!(result.exit_reason, Some(stop));
3150                assert_eq!(result.gas_used, gas_used);
3151                assert_eq!(result.gas_refunded, 0);
3152            }
3153        }
3154    }
3155
3156    #[test]
3157    fn simulation_retains_enabled_calldata_floor() {
3158        let executor =
3159            eth_executor(ExecutorBuilder::default().spec_id(SpecId::PRAGUE).gas_limit(100_000));
3160        let result = executor
3161            .call_raw(CALLER, Address::repeat_byte(0x11), vec![1; 1_000].into(), U256::ZERO)
3162            .unwrap();
3163        assert!(!result.reverted);
3164        assert_eq!(result.gas_used, 61_000);
3165    }
3166
3167    /// Returns code that forwards its calldata to `target` `calls` times and bubbles the error of
3168    /// the last call.
3169    fn forwarder(target: Address, calls: usize) -> Bytes {
3170        // Copy calldata to memory.
3171        let mut code = vec![0x36, 0x5f, 0x5f, 0x37];
3172        for i in 0..calls {
3173            if i > 0 {
3174                code.push(0x50);
3175            }
3176            code.extend_from_slice(&[0x5f, 0x5f, 0x36, 0x5f, 0x5f, 0x73]);
3177            code.extend_from_slice(target.as_slice());
3178            code.extend_from_slice(&[0x5a, 0xf1]);
3179        }
3180        // Stop on success, otherwise revert with the returned data.
3181        let stop = u8::try_from(code.len() + 10).unwrap();
3182        code.extend_from_slice(&[
3183            0x60, stop, 0x57, 0x3d, 0x5f, 0x5f, 0x3e, 0x3d, 0x5f, 0xfd, 0x5b, 0x00,
3184        ]);
3185        code.into()
3186    }
3187
3188    /// Returns code that makes each of `calls` to the cheatcode address, ignoring their results,
3189    /// then runs `end`.
3190    fn vm_script(calls: &[Vec<u8>], end: &[u8]) -> Bytes {
3191        const CALL_LEN: usize = 37;
3192        let mut code = Vec::new();
3193        let mut data_offset = CALL_LEN * calls.len() + end.len();
3194        for call in calls {
3195            let len = u8::try_from(call.len()).unwrap();
3196            // Copy the embedded calldata to memory, call with it and pop the success flag.
3197            code.extend_from_slice(&[0x60, len, 0x61]);
3198            code.extend_from_slice(&u16::try_from(data_offset).unwrap().to_be_bytes());
3199            code.extend_from_slice(&[0x5f, 0x39, 0x5f, 0x5f, 0x60, len, 0x5f, 0x5f, 0x73]);
3200            code.extend_from_slice(CHEATCODE_ADDRESS.as_slice());
3201            code.extend_from_slice(&[0x5a, 0xf1, 0x50]);
3202            data_offset += call.len();
3203        }
3204        code.extend_from_slice(end);
3205        code.extend(calls.iter().flatten());
3206        code.into()
3207    }
3208
3209    fn failure_identity_executor(assertions_revert: bool) -> Executor<EthEvmNetwork> {
3210        let config = Config { assertions_revert, ..Default::default() };
3211        let cheats_config =
3212            Arc::new(CheatsConfig::new(&config, EvmOpts::default(), None, None, false));
3213        let mut executor = eth_executor(
3214            ExecutorBuilder::default()
3215                .inspectors(|stack| stack.cheatcodes(cheats_config))
3216                .gas_limit(1_000_000),
3217        );
3218        executor.inspector_mut().collect_failure_identity(true);
3219        executor
3220    }
3221
3222    #[test]
3223    fn failure_identity_ignores_only_assertion_values() {
3224        let mut executor = failure_identity_executor(true);
3225        let [once, twice] = [0x31, 0x32].map(Address::with_last_byte);
3226        for (target, calls) in [(once, 1), (twice, 2)] {
3227            executor
3228                .set_code(target, Bytecode::new_raw(forwarder(CHEATCODE_ADDRESS, calls)))
3229                .unwrap();
3230        }
3231        let identity = |target, call: Vec<u8>| {
3232            let result = executor.call_raw(CALLER, target, call.into(), U256::ZERO).unwrap();
3233            assert!(result.reverted);
3234            result.failure_identity
3235        };
3236        let gt = |left: u64, right: u64| {
3237            assertGt_0Call { left: U256::from(left), right: U256::from(right) }.abi_encode()
3238        };
3239        let eq = |err: &str| {
3240            assertEq_1Call { left: true, right: false, err: err.to_string() }.abi_encode()
3241        };
3242
3243        // The same assertion reporting other values fails the same way.
3244        let expected = identity(once, gt(0, 1)).unwrap();
3245        assert_eq!(identity(once, gt(2, 3)), Some(expected));
3246        // Another assertion from the same site does not.
3247        let lt = assertLt_0Call { left: U256::ONE, right: U256::ONE }.abi_encode();
3248        assert_ne!(identity(once, lt).unwrap(), expected);
3249        // Custom messages are compared in full, even when they look like formatted values.
3250        assert_ne!(
3251            identity(once, eq("assertion failed: early")).unwrap(),
3252            identity(once, eq("assertion failed: intended")).unwrap()
3253        );
3254        // Either of two identical failures could have produced the revert data.
3255        assert_eq!(identity(twice, gt(0, 1)), None);
3256    }
3257
3258    #[test]
3259    fn failure_identity_tracks_non_reverting_assertions() {
3260        let mut executor = failure_identity_executor(false);
3261        let [first, second, parent, a] = [0x31, 0x32, 0x33, 0x34].map(Address::with_last_byte);
3262        let assertion = assertTrue_1Call { condition: false, err: "failed".to_string() };
3263
3264        // The same assertion from another call site fails another way.
3265        let identities = [first, second].map(|target| {
3266            executor.set_code(target, Bytecode::new_raw(forwarder(CHEATCODE_ADDRESS, 1))).unwrap();
3267            let call = assertion.abi_encode().into();
3268            let result = executor.call_raw(CALLER, target, call, U256::ZERO).unwrap();
3269            assert_eq!(result.exit_reason, Some(InstrStop::Stop));
3270            result.failure_identity.unwrap()
3271        });
3272        assert_ne!(identities[0], identities[1]);
3273
3274        // Call `a` with 2, then 1, and stop.
3275        let mut code = vec![0x60, 0x02, 0x5b, 0x80, 0x5f, 0x52, 0x5f, 0x5f, 0x60, 0x20, 0x5f, 0x5f];
3276        code.push(0x73);
3277        code.extend_from_slice(a.as_slice());
3278        code.extend_from_slice(&[0x5a, 0xf1, 0x50, 0x60, 0x01, 0x90, 0x03, 0x80, 0x60, 0x02]);
3279        code.extend_from_slice(&[0x57, 0x00]);
3280        executor.set_code(parent, Bytecode::new_raw(code.into())).unwrap();
3281        // Assert when called with storage slot zero, then revert when called with slot one.
3282        let mut child = vec![0x5f, 0x35, 0x80, 0x5f, 0x54, 0x14, 0x60, 0x16, 0x57, 0x5b, 0x60];
3283        child.extend_from_slice(&[0x01, 0x54, 0x14, 0x60, 0x12, 0x57, 0x00, 0x5b, 0x5f, 0x5f]);
3284        child.extend_from_slice(&[0xfd, 0x5b]);
3285        let mut assert = vm_script(&[assertion.abi_encode()], &[])[..37].to_vec();
3286        // Point the calldata copy at the end of the child.
3287        assert[4] = 0x3f;
3288        child.extend(assert);
3289        child.extend_from_slice(&[0x60, 0x09, 0x56]);
3290        assert_eq!([child[0x09], child[0x12], child[0x16]], [0x5b; 3]);
3291        assert_eq!(child.len(), 0x3f);
3292        child.extend(assertion.abi_encode());
3293        executor.set_code(a, Bytecode::new_raw(child.into())).unwrap();
3294        let identities = [1, 2].map(|reverting| {
3295            let account = |slot: u64, value: u64| (a, U256::from(slot), U256::from(value));
3296            for (account, slot, value) in [account(0, 2), account(1, reverting)] {
3297                executor.backend_mut().insert_account_storage(account, slot, value);
3298            }
3299            let result = executor.call_raw(CALLER, parent, Bytes::new(), U256::ZERO).unwrap();
3300            assert_eq!(result.exit_reason, Some(InstrStop::Stop));
3301            result.failure_identity.unwrap()
3302        });
3303        // The same assertion survives and a later call reverts, or the call that asserted reverts.
3304        assert_ne!(identities[0], identities[1]);
3305    }
3306
3307    #[test]
3308    fn failure_identity_tells_apart_failure_sites() {
3309        let mut executor = failure_identity_executor(true);
3310        let [target, reverts, invalid_jump, out_of_gas] =
3311            [0x31, 0x32, 0x33, 0x34].map(Address::with_last_byte);
3312        for (callee, code) in [
3313            (reverts, &[0x5f, 0x5f, 0xfd][..]),
3314            (invalid_jump, &[0x5f, 0x56]),
3315            (out_of_gas, &[0x5b, 0x5f, 0x56]),
3316        ] {
3317            executor.set_code(callee, Bytecode::new_raw(Bytes::copy_from_slice(code))).unwrap();
3318        }
3319        let mut identity = |code: &[u8], calldata: U256| {
3320            executor.set_code(target, Bytecode::new_raw(Bytes::copy_from_slice(code))).unwrap();
3321            let calldata = Bytes::from(calldata.to_be_bytes_vec());
3322            let result = executor.call_raw(CALLER, target, calldata, U256::ZERO).unwrap();
3323            assert!(result.reverted);
3324            result.failure_identity.unwrap()
3325        };
3326        let gt = |left: u64, right: u64| {
3327            assertGt_0Call { left: U256::from(left), right: U256::from(right) }.abi_encode()
3328        };
3329
3330        // Two `REVERT`s of the same data in one frame.
3331        let two_reverts = [0x5f, 0x35, 0x60, 0x08, 0x57, 0x5f, 0x5f, 0xfd, 0x5b, 0x5f, 0x5f, 0xfd];
3332        assert_ne!(identity(&two_reverts, U256::ZERO), identity(&two_reverts, U256::ONE));
3333        // Two checks that branch to one shared `REVERT`, as optimized code does.
3334        let mut shared = vec![0x5f, 0x35, 0x80, 0x60, 0x01, 0x14, 0x60, 0x10, 0x57, 0x60, 0x02];
3335        shared.extend_from_slice(&[0x14, 0x60, 0x10, 0x57, 0x00, 0x5b, 0x5f, 0x5f, 0xfd]);
3336        assert_eq!(shared[0x10], 0x5b);
3337        assert_ne!(identity(&shared, U256::ONE), identity(&shared, U256::from(2)));
3338
3339        // The same `CALL` reaching contracts that halt for different reasons, then reverting.
3340        let forward = [0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x35, 0x5a, 0xf1, 0x5f, 0x5f, 0xfd];
3341        let [invalid_jump, out_of_gas] =
3342            [invalid_jump, out_of_gas].map(|callee| U256::from_be_slice(callee.as_slice()));
3343        assert_ne!(identity(&forward, invalid_jump), identity(&forward, out_of_gas));
3344
3345        // Two invalid `JUMP`s, which halt with the same reason and data.
3346        let jumps = [0x5f, 0x35, 0x60, 0x07, 0x57, 0x5f, 0x56, 0x5b, 0x5f, 0x56];
3347        assert_ne!(identity(&jumps, U256::ZERO), identity(&jumps, U256::ONE));
3348
3349        // Initcode reverting at either of two sites, whose failure the creator then replaces.
3350        let create = [0x36, 0x5f, 0x5f, 0x37, 0x36, 0x5f, 0x5f, 0xf0, 0x50, 0x5f, 0x5f, 0xfd];
3351        let [first, second] = [&[0x5f, 0x5f, 0xfd][..], &[0x60, 0x01, 0x50, 0x5f, 0x5f, 0xfd]]
3352            .map(|initcode| U256::from_be_bytes(B256::right_padding_from(initcode).0));
3353        assert_ne!(identity(&create, first), identity(&create, second));
3354        // Constructor arguments past the executed code are ignored.
3355        let args = U256::from_be_bytes(B256::right_padding_from(&[0x5f, 0x5f, 0xfd, 0x01]).0);
3356        assert_eq!(identity(&create, first), identity(&create, args));
3357        // Even when they change the `CREATE2` address.
3358        let create2 =
3359            [0x36, 0x5f, 0x5f, 0x37, 0x5f, 0x36, 0x5f, 0x5f, 0xf5, 0x50, 0x5f, 0x5f, 0xfd];
3360        assert_eq!(identity(&create2, first), identity(&create2, args));
3361
3362        // The same contract reverting from two calls, whose failure the caller then replaces.
3363        let mut caught = vec![0x5f, 0x35, 0x60, 0x25, 0x57];
3364        for jump in [true, false] {
3365            caught.extend_from_slice(&[0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x73]);
3366            caught.extend_from_slice(reverts.as_slice());
3367            caught.extend_from_slice(&[0x5a, 0xf1, 0x50]);
3368            if jump {
3369                caught.extend_from_slice(&[0x60, 0x43, 0x56, 0x5b]);
3370            }
3371        }
3372        caught.extend_from_slice(&[0x5b, 0x5f, 0x5f, 0xfd]);
3373        assert_eq!([caught[0x25], caught[0x43]], [0x5b, 0x5b]);
3374        assert_ne!(identity(&caught, U256::ZERO), identity(&caught, U256::ONE));
3375
3376        // An internal function asserting for two callers, told apart by their return labels. It
3377        // copies the asserting calldata at the end of the code to memory, calls the cheatcode
3378        // address with it and reverts with its error.
3379        let mut wrapper = vec![0x5f, 0x35, 0x60, 0x0c, 0x57];
3380        wrapper.extend_from_slice(&[0x60, 0x0a, 0x60, 0x14, 0x56, 0x5b, 0x00]);
3381        wrapper.extend_from_slice(&[0x5b, 0x60, 0x12, 0x60, 0x14, 0x56, 0x5b, 0x00, 0x5b]);
3382        wrapper.extend_from_slice(&[0x60, 0x44, 0x60, 0x3f, 0x5f, 0x39, 0x5f, 0x5f, 0x60, 0x44]);
3383        wrapper.extend_from_slice(&[0x5f, 0x5f, 0x73]);
3384        wrapper.extend_from_slice(CHEATCODE_ADDRESS.as_slice());
3385        wrapper.extend_from_slice(&[0x5a, 0xf1, 0x3d, 0x5f, 0x5f, 0x3e, 0x3d, 0x5f, 0xfd]);
3386        assert_eq!([wrapper[0x0a], wrapper[0x0c], wrapper[0x12], wrapper[0x14]], [0x5b; 4]);
3387        assert_eq!(wrapper.len(), 0x3f);
3388        wrapper.extend(gt(0, 1));
3389        assert_ne!(identity(&wrapper, U256::ZERO), identity(&wrapper, U256::ONE));
3390
3391        // Rethrowing either of two caught assertions.
3392        let mut rethrow = Vec::new();
3393        for (offset, ret) in [(0x00, 0x02), (0x44, 0x03)] {
3394            // Copy the calldata, then call with it, keeping its error at `ret * 0x100`.
3395            rethrow.extend_from_slice(&[0x60, 0x44, 0x60, 0x5f + offset, 0x60, offset, 0x39]);
3396            rethrow.extend_from_slice(&[0x60, 0x64, 0x61, ret, 0x00, 0x60, 0x44, 0x60, offset]);
3397            rethrow.extend_from_slice(&[0x5f, 0x73]);
3398            rethrow.extend_from_slice(CHEATCODE_ADDRESS.as_slice());
3399            rethrow.extend_from_slice(&[0x5a, 0xf1, 0x50]);
3400        }
3401        // Revert with the error at `0x200 + calldata * 0x100`.
3402        rethrow.extend_from_slice(&[0x60, 0x64, 0x5f, 0x35, 0x61, 0x01, 0x00, 0x02]);
3403        rethrow.extend_from_slice(&[0x61, 0x02, 0x00, 0x01, 0xfd]);
3404        assert_eq!(rethrow.len(), 0x5f);
3405        rethrow.extend(gt(0, 1));
3406        rethrow.extend(gt(2, 3));
3407        assert_ne!(identity(&rethrow, U256::ZERO), identity(&rethrow, U256::ONE));
3408    }
3409
3410    #[test]
3411    fn failure_identity_needs_a_recorded_origin() {
3412        let target = Address::with_last_byte(0x31);
3413        let identity = |executor: &mut Executor<EthEvmNetwork>, calls: &[Vec<u8>]| {
3414            let code = Bytecode::new_raw(vm_script(calls, &[0x00]));
3415            executor.set_code(target, code).unwrap();
3416            let mut result = executor.call_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
3417            assert!(!executor.is_raw_call_mut_success(target, &mut result));
3418            result.failure_identity
3419        };
3420        let assertion = assertTrue_1Call { condition: false, err: "failed".to_string() };
3421        let snapshot = snapshotStateCall {}.abi_encode();
3422
3423        // A restore can make another path look like this one. The first snapshot of a new
3424        // executor has id zero.
3425        for restore in [
3426            revertToStateCall { snapshotId: U256::ZERO }.abi_encode(),
3427            revertToStateAndDeleteCall { snapshotId: U256::ZERO }.abi_encode(),
3428        ] {
3429            let calls = [snapshot.clone(), restore, assertion.abi_encode()];
3430            assert_eq!(identity(&mut failure_identity_executor(false), &calls), None);
3431        }
3432        let mut executor = failure_identity_executor(false);
3433        assert!(identity(&mut executor, &[snapshot, assertion.abi_encode()]).is_some());
3434
3435        // A `fail()` is identified by its call site, even after a caught assertion that reverted
3436        // and so did not fail the call.
3437        let mut executor = failure_identity_executor(true);
3438        let fail = storeCall {
3439            target: CHEATCODE_ADDRESS,
3440            slot: GLOBAL_FAIL_SLOT.into(),
3441            value: B256::with_last_byte(1),
3442        }
3443        .abi_encode();
3444        // Catch the assertion, then call `fail()` at either of two sites chosen by the calldata.
3445        let assertion = assertion.abi_encode();
3446        let data = 119;
3447        let block = |call: &[u8], offset: usize| {
3448            let mut block = vm_script(&[call.to_vec()], &[])[..37].to_vec();
3449            block[3..5].copy_from_slice(&u16::try_from(offset).unwrap().to_be_bytes());
3450            block
3451        };
3452        let mut code = block(&assertion, data);
3453        code.extend_from_slice(&[0x5f, 0x35, 0x60, 0x50, 0x57]);
3454        code.extend(block(&fail, data + assertion.len()));
3455        code.extend_from_slice(&[0x00, 0x5b]);
3456        code.extend(block(&fail, data + assertion.len()));
3457        code.push(0x00);
3458        assert_eq!((code[0x50], code.len()), (0x5b, data));
3459        code.extend_from_slice(&assertion);
3460        code.extend(fail);
3461        executor.set_code(target, Bytecode::new_raw(code.into())).unwrap();
3462        executor.inspector_mut().collect_failure_provenance(true);
3463        let [first, second] = [U256::ZERO, U256::ONE].map(|site| {
3464            let calldata = site.to_be_bytes_vec().into();
3465            let mut result = executor.call_raw(CALLER, target, calldata, U256::ZERO).unwrap();
3466            assert!(!executor.is_raw_call_mut_success(target, &mut result));
3467            (result.failure_identity.unwrap(), result.failure_provenance.unwrap())
3468        });
3469        assert_ne!(first.0, second.0);
3470        // A replay can check which `fail()` it reached too.
3471        assert_ne!(first.1, second.1);
3472        // The caught assertion alone is identified too, as it fails invariant handlers.
3473        let code = Bytecode::new_raw(vm_script(&[assertion], &[0x00]));
3474        executor.set_code(target, code).unwrap();
3475        let result = executor.call_raw(CALLER, target, Bytes::new(), U256::ZERO).unwrap();
3476        assert!(result.failed_assertion.is_some() && result.failure_identity.is_some());
3477    }
3478
3479    #[test]
3480    fn failure_provenance_tells_apart_equal_raw_failures() {
3481        let mut executor = failure_identity_executor(false);
3482        let [
3483            check,
3484            forward,
3485            first,
3486            second,
3487            halt,
3488            wrapper,
3489            other_wrapper,
3490            callee,
3491            sites,
3492            branch,
3493            checks,
3494        ] = [0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b]
3495            .map(Address::with_last_byte);
3496        // Jump to the calldata and revert empty at pc 6 from 3, or at pc 10 from 7.
3497        let code =
3498            Bytes::from_static(&[0x5f, 0x35, 0x56, 0x5b, 0x5f, 0x5f, 0xfd, 0x5b, 0x5f, 0x5f, 0xfd]);
3499        executor.set_code(check, Bytecode::new_raw(code)).unwrap();
3500        executor.set_code(forward, Bytecode::new_raw(forwarder(check, 1))).unwrap();
3501        // Jump to the calldata, call a reverting callee from pc 0x1f from 3, or from pc 0x3f from
3502        // 0x23, at equal cost, then revert empty at a shared pc.
3503        executor
3504            .set_code(callee, Bytecode::new_raw(Bytes::from_static(&[0x5f, 0x5f, 0xfd])))
3505            .unwrap();
3506        let mut code = vec![0x5f, 0x35, 0x56];
3507        for _ in 0..2 {
3508            code.extend_from_slice(&[0x5b, 0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x73]);
3509            code.extend_from_slice(callee.as_slice());
3510            code.extend_from_slice(&[0x5a, 0xf1, 0x60, 0x43, 0x56]);
3511        }
3512        code.extend_from_slice(&[0x5b, 0x5f, 0x5f, 0xfd]);
3513        executor.set_code(sites, Bytecode::new_raw(code.into())).unwrap();
3514        // Jump to the calldata and branch from pc 8 from 3, or from pc 0xf from 0xa, to a shared
3515        // block that calls a contract that branches and returns, then reverts empty.
3516        let code = Bytes::from_static(&[0x60, 0x01, 0x60, 0x05, 0x57, 0x5b, 0x00]);
3517        executor.set_code(branch, Bytecode::new_raw(code)).unwrap();
3518        let mut code = vec![0x5f, 0x35, 0x56];
3519        for _ in 0..2 {
3520            code.extend_from_slice(&[0x5b, 0x60, 0x01, 0x60, 0x11, 0x57, 0x00]);
3521        }
3522        code.extend_from_slice(&[0x5b, 0x5f, 0x5f, 0x5f, 0x5f, 0x5f, 0x73]);
3523        code.extend_from_slice(branch.as_slice());
3524        code.extend_from_slice(&[0x5a, 0xf1, 0x5f, 0x5f, 0xfd]);
3525        executor.set_code(checks, Bytecode::new_raw(code.into())).unwrap();
3526        // Two instances of a contract failing an assertion that does not revert.
3527        for target in [first, second] {
3528            executor.set_code(target, Bytecode::new_raw(forwarder(CHEATCODE_ADDRESS, 1))).unwrap();
3529        }
3530        // Two wrappers making the same assertion through the first contract.
3531        for target in [wrapper, other_wrapper] {
3532            executor.set_code(target, Bytecode::new_raw(forwarder(first, 1))).unwrap();
3533        }
3534        let assertion =
3535            assertTrue_1Call { condition: false, err: "failed".to_string() }.abi_encode();
3536        let runs = [
3537            (forward, U256::from(3).to_be_bytes_vec()),
3538            (forward, U256::from(7).to_be_bytes_vec()),
3539            (sites, U256::from(0x03).to_be_bytes_vec()),
3540            (sites, U256::from(0x23).to_be_bytes_vec()),
3541            (checks, U256::from(0x03).to_be_bytes_vec()),
3542            (checks, U256::from(0x0a).to_be_bytes_vec()),
3543            (first, assertion.clone()),
3544            (second, assertion.clone()),
3545            (wrapper, assertion.clone()),
3546            (other_wrapper, assertion),
3547        ];
3548        let raw_failures = |executor: &mut Executor<EthEvmNetwork>| {
3549            runs.clone().map(|(target, calldata)| {
3550                let result =
3551                    executor.call_raw(CALLER, target, calldata.into(), U256::ZERO).unwrap();
3552                result.raw_failure()
3553            })
3554        };
3555
3556        // Without provenance, a replay cannot be checked.
3557        assert!(raw_failures(&mut executor).iter().all(Option::is_none));
3558
3559        executor.inspector_mut().collect_failure_provenance(true);
3560        let anchors = raw_failures(&mut executor).map(Option::unwrap);
3561        let exits = anchors.each_ref().map(|failure| failure.exit_reason.unwrap());
3562        assert_eq!(
3563            exits,
3564            [
3565                InstrStop::Revert,
3566                InstrStop::Revert,
3567                InstrStop::Revert,
3568                InstrStop::Revert,
3569                InstrStop::Revert,
3570                InstrStop::Revert,
3571                InstrStop::Stop,
3572                InstrStop::Stop,
3573                InstrStop::Stop,
3574                InstrStop::Stop
3575            ]
3576        );
3577        // Campaigns, which do not record failure identities, record the same provenance as
3578        // replays that do.
3579        executor.inspector_mut().collect_failure_identity(false);
3580        assert_eq!(raw_failures(&mut executor).map(Option::unwrap), anchors);
3581
3582        // A halt's instruction is not recorded, so replays of a call that halted cannot be
3583        // checked.
3584        executor.set_code(halt, Bytecode::new_raw(Bytes::from_static(&[0x5f, 0x56]))).unwrap();
3585        executor.set_code(forward, Bytecode::new_raw(forwarder(halt, 1))).unwrap();
3586        let result = executor.call_raw(CALLER, forward, Bytes::new(), U256::ZERO).unwrap();
3587        assert_eq!(result.exit_reason, Some(InstrStop::Revert));
3588        assert_eq!(result.raw_failure(), None);
3589
3590        // Each pair differs only in where it failed.
3591        for [a, b] in anchors.as_chunks::<2>().0 {
3592            assert_ne!(a.provenance, b.provenance);
3593            assert_eq!(
3594                RawFailure { provenance: B256::ZERO, ..a.clone() },
3595                RawFailure { provenance: B256::ZERO, ..b.clone() }
3596            );
3597        }
3598    }
3599}