Skip to main content

foundry_evm/executors/
campaign.rs

1//! Worker-local call execution policy shared by stateless and invariant fuzz campaigns.
2
3use super::{Executor, RawCallResult};
4use alloy_network::TransactionBuilder;
5use alloy_primitives::{TxKind, U256};
6use evm2::registry::HandlerError;
7use eyre::{Result, eyre};
8use foundry_evm_core::{
9    backend::TransactionValidationError,
10    constants::MAGIC_ASSUME,
11    evm::{BlockEnvFor, FoundryEvmNetwork},
12};
13use foundry_evm_fuzz::BasicTxDetails;
14
15/// The small set of execution policies which differ between fuzzing modes.
16#[derive(Clone, Copy, Debug)]
17pub(crate) enum FuzzCampaignMode {
18    /// Stateless calls never mutate the worker executor.
19    Stateless,
20    /// Accepted invariant calls mutate it and predicates run at the configured cadence.
21    Invariant { check_interval: u32, optimization: bool },
22}
23
24/// Classification produced by the common call loop.
25#[derive(Clone, Copy, Debug, PartialEq, Eq)]
26pub(crate) enum CampaignCallKind {
27    Accepted,
28    AssumptionRejected,
29}
30
31pub(crate) enum CampaignEvent<'a, FEN: FoundryEvmNetwork> {
32    Feedback(&'a mut RawCallResult<FEN>),
33    Check { result: &'a mut Option<RawCallResult<FEN>>, kind: CampaignCallKind, should_check: bool },
34    Advance,
35    Next { discarded: bool, depth: u32 },
36    PostCheck,
37}
38
39#[derive(Clone, Copy, Debug, PartialEq, Eq)]
40pub(crate) enum CampaignControl {
41    Continue,
42    Stop,
43}
44
45#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub(crate) enum CampaignSequenceOutcome {
47    Complete,
48    Cancelled,
49    Stopped,
50}
51
52/// Concrete worker-local campaign execution policy.
53pub(crate) struct FuzzCampaign {
54    mode: FuzzCampaignMode,
55}
56
57impl FuzzCampaign {
58    pub(crate) const fn new(mode: FuzzCampaignMode) -> Self {
59        Self { mode }
60    }
61
62    /// Drives one concrete sequence, including execution, classification, and lifecycle events.
63    pub(crate) fn run_sequence<S, FEN, Parts, Depth, Stop, Event>(
64        &self,
65        state: &mut S,
66        run_depth: u32,
67        mut parts: Parts,
68        mut depth: Depth,
69        mut should_stop: Stop,
70        mut on_event: Event,
71    ) -> Result<CampaignSequenceOutcome>
72    where
73        FEN: FoundryEvmNetwork,
74        Parts: for<'a> FnMut(&'a mut S) -> (&'a mut Executor<FEN>, &'a mut BasicTxDetails),
75        Depth: FnMut(&S) -> u32,
76        Stop: FnMut(&S) -> bool,
77        Event: for<'a> FnMut(&mut S, CampaignEvent<'a, FEN>) -> Result<CampaignControl>,
78    {
79        let outcome = loop {
80            if depth(state) >= run_depth {
81                break CampaignSequenceOutcome::Complete;
82            }
83            if should_stop(state) {
84                return Ok(CampaignSequenceOutcome::Cancelled);
85            }
86            let current_depth = depth(state);
87            let last_call = current_depth == run_depth - 1;
88            let (mut result, block_snapshot) = {
89                let (executor, tx) = parts(state);
90                let snapshot = matches!(self.mode, FuzzCampaignMode::Invariant { .. })
91                    .then(|| BlockSnapshot::for_delayed_call(executor, tx))
92                    .flatten();
93                let result = match self.mode {
94                    FuzzCampaignMode::Stateless => executor.call_raw(
95                        tx.sender,
96                        tx.call_details.target,
97                        tx.call_details.calldata.clone(),
98                        tx.call_details.value.unwrap_or_default(),
99                    )?,
100                    FuzzCampaignMode::Invariant { .. } => execute_invariant_tx(executor, tx)?,
101                };
102                (result, snapshot)
103            };
104            if result.execution_cancelled {
105                if let Some(snapshot) = block_snapshot {
106                    let (executor, _) = parts(state);
107                    snapshot.restore(executor);
108                }
109                return Ok(CampaignSequenceOutcome::Cancelled);
110            }
111            on_event(state, CampaignEvent::Feedback(&mut result))?;
112            let kind = match self.mode {
113                FuzzCampaignMode::Invariant { .. } => {
114                    let (executor, _) = parts(state);
115                    transition_invariant_call(executor, &mut result, block_snapshot)
116                }
117                FuzzCampaignMode::Stateless => {
118                    if result.result.as_ref() == MAGIC_ASSUME {
119                        CampaignCallKind::AssumptionRejected
120                    } else {
121                        CampaignCallKind::Accepted
122                    }
123                }
124            };
125            let discarded = kind == CampaignCallKind::AssumptionRejected;
126            let should_check = match self.mode {
127                FuzzCampaignMode::Stateless => true,
128                FuzzCampaignMode::Invariant { optimization: true, .. } => true,
129                FuzzCampaignMode::Invariant { check_interval: 0, .. } => last_call,
130                FuzzCampaignMode::Invariant { check_interval, .. } => {
131                    check_interval == 1
132                        || (current_depth + 1).is_multiple_of(check_interval)
133                        || last_call
134                }
135            };
136            let mut result = Some(result);
137            if on_event(state, CampaignEvent::Check { result: &mut result, kind, should_check })?
138                == CampaignControl::Stop
139            {
140                break CampaignSequenceOutcome::Stopped;
141            }
142            if !discarded {
143                on_event(state, CampaignEvent::Advance)?;
144            }
145            let next_depth = depth(state);
146            on_event(state, CampaignEvent::Next { discarded, depth: next_depth })?;
147        };
148        on_event(state, CampaignEvent::PostCheck)?;
149        Ok(outcome)
150    }
151}
152
153struct BlockSnapshot<FEN: FoundryEvmNetwork> {
154    env: BlockEnvFor<FEN>,
155    cheatcode: Option<BlockEnvFor<FEN>>,
156}
157
158impl<FEN: FoundryEvmNetwork> BlockSnapshot<FEN> {
159    fn for_delayed_call(executor: &Executor<FEN>, tx: &BasicTxDetails) -> Option<Self> {
160        let has_delay = tx.warp.is_some_and(|delay| !delay.is_zero())
161            || tx.roll.is_some_and(|delay| !delay.is_zero());
162        has_delay.then(|| Self::new(executor))
163    }
164
165    fn new(executor: &Executor<FEN>) -> Self {
166        Self {
167            env: executor.evm_env().block,
168            cheatcode: executor.inspector().cheatcodes.as_ref().and_then(|c| c.block),
169        }
170    }
171
172    fn restore(self, executor: &mut Executor<FEN>) {
173        executor.evm_env_mut().block = self.env;
174        if let Some(cheatcodes) = executor.inspector_mut().cheatcodes.as_mut() {
175            cheatcodes.block = self.cheatcode;
176        }
177    }
178}
179
180fn transition_invariant_call<FEN: FoundryEvmNetwork>(
181    executor: &mut Executor<FEN>,
182    result: &mut RawCallResult<FEN>,
183    block_snapshot: Option<BlockSnapshot<FEN>>,
184) -> CampaignCallKind {
185    if result.result.as_ref() == MAGIC_ASSUME {
186        if let Some(snapshot) = block_snapshot {
187            snapshot.restore(executor);
188        }
189        CampaignCallKind::AssumptionRejected
190    } else {
191        executor.commit(result);
192        CampaignCallKind::Accepted
193    }
194}
195
196/// Executes and commits one invariant replay call with live campaign semantics.
197pub(super) fn execute_invariant_replay_tx<FEN: FoundryEvmNetwork>(
198    executor: &mut Executor<FEN>,
199    tx: &BasicTxDetails,
200) -> Result<(CampaignCallKind, RawCallResult<FEN>)> {
201    let block_snapshot = BlockSnapshot::for_delayed_call(executor, tx);
202    let mut result = execute_invariant_tx(executor, &mut tx.clone())?;
203    if result.execution_cancelled {
204        if let Some(snapshot) = block_snapshot {
205            snapshot.restore(executor);
206        }
207        return Err(eyre!("invariant replay call was cancelled"));
208    }
209    let kind = transition_invariant_call(executor, &mut result, block_snapshot);
210    Ok((kind, result))
211}
212
213pub(super) fn execute_invariant_tx<FEN: FoundryEvmNetwork>(
214    executor: &mut Executor<FEN>,
215    tx: &mut BasicTxDetails,
216) -> Result<RawCallResult<FEN>> {
217    apply_block_delay(executor, tx.warp.unwrap_or_default(), tx.roll.unwrap_or_default());
218    let value = match tx.call_details.value {
219        Some(requested) if !requested.is_zero() => requested.min(executor.get_balance(tx.sender)?),
220        _ => U256::ZERO,
221    };
222    // Persist exactly what was sent so replay, shrinking, and corpus entries do not claim an
223    // unavailable value was executed.
224    tx.call_details.value = (!value.is_zero()).then_some(value);
225    let (mut evm_env, mut tx_request) = executor.prepare_call_env(
226        tx.sender,
227        TxKind::Call(tx.call_details.target),
228        tx.call_details.calldata.clone(),
229        value,
230    );
231    // The network rejects a transaction whose gas limit is below its intrinsic gas or, from
232    // Prague, the EIP-7623 calldata floor. Large fuzzed arrays or network-specific charges reach
233    // them under a low `call_gas_limit` or project `gas_limit`, and the error would abort the
234    // campaign, so the call runs again with the gas the network requires. Intrinsic gas is checked
235    // before the floor, so at most two retries are needed.
236    let mut result = executor.call_with_env(evm_env, tx_request.clone());
237    for _ in 0..2 {
238        let Err(error) = &result else { break };
239        let Some(
240            &(HandlerError::IntrinsicGasTooLow { required, .. }
241            | HandlerError::GasLimitBelowFloor { required, .. }),
242        ) = error.chain().find_map(|cause| {
243            cause.downcast_ref::<HandlerError>().or_else(|| {
244                cause.downcast_ref::<TransactionValidationError>().map(|error| &error.error)
245            })
246        })
247        else {
248            break;
249        };
250        tx_request.set_gas_limit(required);
251        evm_env.block.gas_limit = evm_env.block.gas_limit.max(U256::from(required));
252        result = executor.call_with_env(evm_env, tx_request.clone());
253    }
254    result.map_err(|error| eyre!("Could not make raw evm call: {error}"))
255}
256
257/// Advances the execution block environment and the cheatcode block override by an invariant
258/// call's warp and roll delays.
259pub(super) fn apply_block_delay<FEN: FoundryEvmNetwork>(
260    executor: &mut Executor<FEN>,
261    warp: U256,
262    roll: U256,
263) {
264    if warp.is_zero() && roll.is_zero() {
265        return;
266    }
267    let needs_cheatcode_block = executor
268        .inspector()
269        .cheatcodes
270        .as_ref()
271        .is_some_and(|cheatcodes| cheatcodes.block.is_none());
272    let block_env = {
273        let block_env = &mut executor.evm_env_mut().block;
274        block_env.timestamp += warp;
275        block_env.number += roll;
276        needs_cheatcode_block.then_some(*block_env)
277    };
278    if let Some(cheatcodes) = executor.inspector_mut().cheatcodes.as_mut() {
279        if let Some(block) = cheatcodes.block.as_mut() {
280            block.timestamp += warp;
281            block.number += roll;
282        } else {
283            cheatcodes.block = Some(block_env.unwrap());
284        }
285    }
286}