Skip to main content

foundry_evm/executors/invariant/
replay.rs

1use super::{call_after_invariant_function, call_invariant_function};
2use crate::executors::{
3    EarlyExit, Executor,
4    campaign::execute_invariant_tx,
5    corpus::persist_campaign_optimization,
6    invariant::shrink::{
7        CheckSequenceOutcome, ShrinkProgress, shrink_sequence, shrink_sequence_value,
8    },
9};
10use alloy_dyn_abi::JsonAbiExt;
11use alloy_json_abi::Function;
12use alloy_primitives::{
13    Address, Bytes, I256, Log,
14    map::{AddressHashMap, HashMap},
15};
16use eyre::Result;
17use foundry_common::{ContractsByAddress, ContractsByArtifact};
18use foundry_config::InvariantConfig;
19use foundry_evm_core::{decode::RevertDecoder, evm::FoundryEvmNetwork};
20use foundry_evm_coverage::HitMaps;
21use foundry_evm_fuzz::{BaseCounterExample, BasicTxDetails, invariant::InvariantContract};
22use foundry_evm_traces::{TraceKind, TraceRequirements, Traces, load_contracts};
23use indicatif::ProgressBar;
24use parking_lot::RwLock;
25use std::{sync::Arc, time::Instant};
26
27pub struct ReplayErrorResult {
28    pub counterexample_sequence: Vec<BaseCounterExample>,
29    pub check_result: Option<CheckSequenceOutcome>,
30    pub fork_block_number: Option<u64>,
31    /// Optimization value of the shrunk sequence, which can exceed the campaign best.
32    pub optimization_value: Option<I256>,
33}
34
35/// Replays a call sequence for collecting logs and traces.
36/// Returns counterexample to be used when the call sequence is a failed scenario.
37#[expect(clippy::too_many_arguments)]
38pub fn replay_run<FEN: FoundryEvmNetwork>(
39    invariant_contract: &InvariantContract<'_>,
40    target_invariant: &Function,
41    mut executor: Executor<FEN>,
42    known_contracts: &ContractsByArtifact,
43    mut ided_contracts: ContractsByAddress,
44    logs: &mut Vec<Log>,
45    traces: &mut Traces,
46    debug_bytecodes: &mut AddressHashMap<Bytes>,
47    line_coverage: &mut Option<HitMaps>,
48    deprecated_cheatcodes: &mut HashMap<&'static str, Option<&'static str>>,
49    inputs: &[BasicTxDetails],
50    show_solidity: bool,
51) -> Result<ReplayErrorResult> {
52    // We want traces for a failed case.
53    if executor.inspector().tracer.is_none() {
54        executor.set_trace_requirements(TraceRequirements::none().with_calls(true));
55    }
56
57    let mut counterexample_sequence = vec![];
58
59    // Replay each call from the sequence, collect logs, traces and coverage.
60    for tx in inputs {
61        // The counterexample reports the value actually sent, which replay clamps to the sender's
62        // balance, as for campaign inputs.
63        let mut tx = tx.clone();
64        let mut call_result = execute_invariant_tx(&mut executor, &mut tx)?;
65        logs.append(&mut call_result.logs);
66        debug_bytecodes.extend(std::mem::take(&mut call_result.debug_bytecodes));
67        traces.push((TraceKind::Execution, call_result.traces.clone().unwrap()));
68        HitMaps::merge_opt(line_coverage, call_result.line_coverage.take());
69
70        // Commit state changes to persist across calls in the sequence.
71        executor.commit(&mut call_result);
72
73        // Identify newly generated contracts, if they exist.
74        ided_contracts
75            .extend(load_contracts(call_result.traces.iter().map(|a| &a.arena), known_contracts));
76
77        // Create counter example to be used in failed case.
78        counterexample_sequence.push(BaseCounterExample::from_invariant_call(
79            &tx,
80            &ided_contracts,
81            call_result.traces,
82            show_solidity,
83        ));
84    }
85
86    // Replay invariant to collect logs and traces.
87    // We do this only once at the end of the replayed sequence.
88    // Checking after each call doesn't add valuable info for passing scenario
89    // (invariant call result is always success) nor for failed scenarios
90    // (invariant call result is always success until the last call that breaks it).
91    let (invariant_result, invariant_success) = call_invariant_function(
92        &executor,
93        invariant_contract.address,
94        target_invariant.abi_encode_input(&[])?.into(),
95    )?;
96    let fork_block_number = invariant_result.fork_block_number;
97    debug_bytecodes.extend(invariant_result.debug_bytecodes);
98    traces.push((TraceKind::Execution, invariant_result.traces.unwrap()));
99    logs.extend(invariant_result.logs);
100    deprecated_cheatcodes.extend(
101        invariant_result
102            .cheatcodes
103            .as_ref()
104            .map_or_else(Default::default, |cheats| cheats.deprecated.clone()),
105    );
106
107    // Collect after invariant logs and traces.
108    if invariant_contract.call_after_invariant && invariant_success {
109        let (after_invariant_result, _) =
110            call_after_invariant_function(&executor, invariant_contract.address)?;
111        debug_bytecodes.extend(after_invariant_result.debug_bytecodes);
112        traces.push((TraceKind::Execution, after_invariant_result.traces.unwrap()));
113        logs.extend(after_invariant_result.logs);
114    }
115
116    Ok(ReplayErrorResult {
117        counterexample_sequence,
118        check_result: None,
119        fork_block_number,
120        optimization_value: None,
121    })
122}
123
124/// Replays and shrinks a call sequence, collecting logs and traces.
125///
126/// For check mode (target_value=None): shrinks to find shortest failing sequence.
127/// For optimization mode (target_value=Some): shrinks to find shortest sequence producing target.
128/// `targets` are the campaign's fuzz targets, used to score optimization candidates.
129#[expect(clippy::too_many_arguments)]
130pub fn replay_error<FEN: FoundryEvmNetwork>(
131    config: InvariantConfig,
132    mut executor: Executor<FEN>,
133    calls: &[BasicTxDetails],
134    inner_sequence: Option<Vec<Option<BasicTxDetails>>>,
135    expect_assertion_failure: bool,
136    rd: Option<&RevertDecoder>,
137    target_value: Option<I256>,
138    targets: &[Address],
139    invariant_contract: &InvariantContract<'_>,
140    target_invariant: &Function,
141    known_contracts: &ContractsByArtifact,
142    ided_contracts: ContractsByAddress,
143    logs: &mut Vec<Log>,
144    traces: &mut Traces,
145    debug_bytecodes: &mut AddressHashMap<Bytes>,
146    line_coverage: &mut Option<HitMaps>,
147    deprecated_cheatcodes: &mut HashMap<&'static str, Option<&'static str>>,
148    progress: Option<&ProgressBar>,
149    early_exit: &EarlyExit,
150    shrink_deadline: Option<Instant>,
151    position: Option<(usize, usize)>,
152) -> Result<ReplayErrorResult> {
153    // Multi-invariant runs include `[i/N]` in the shrink progress message so users see how many
154    // shrinkers are queued behind the current one.
155    let shrink_progress = ShrinkProgress::new(
156        &config,
157        progress,
158        &target_invariant.name,
159        position,
160        Some(&ided_contracts),
161        config.show_solidity,
162    );
163
164    // Every shrink attempt would append its steps to the shared step table, so only the replay of
165    // the shrunk sequence records them.
166    let recorder = executor.inspector_mut().debug_recorder.take();
167    let (calls, check_result, optimization_value) = if let Some(target) = target_value {
168        let (calls, value) = shrink_sequence_value(
169            &config,
170            invariant_contract,
171            target_invariant,
172            calls,
173            &executor,
174            target,
175            targets,
176            &shrink_progress,
177            early_exit,
178            shrink_deadline,
179        )?;
180        (calls, None, Some(value))
181    } else {
182        let shrunk = shrink_sequence(
183            &config,
184            invariant_contract,
185            target_invariant,
186            calls,
187            expect_assertion_failure,
188            &executor,
189            rd,
190            &shrink_progress,
191            early_exit,
192            shrink_deadline,
193        )?;
194        (shrunk.calls, shrunk.result, None)
195    };
196    executor.inspector_mut().debug_recorder = recorder;
197
198    if let Some(sequence) = inner_sequence {
199        set_up_inner_replay(&mut executor, &sequence);
200    }
201
202    let mut replay = replay_run(
203        invariant_contract,
204        target_invariant,
205        executor,
206        known_contracts,
207        ided_contracts,
208        logs,
209        traces,
210        debug_bytecodes,
211        line_coverage,
212        deprecated_cheatcodes,
213        &calls,
214        config.show_solidity,
215    )?;
216
217    persist_campaign_optimization(&config.corpus, optimization_value, &calls);
218    replay.check_result = check_result;
219    replay.optimization_value = optimization_value;
220    Ok(replay)
221}
222
223/// Sets up the calls generated by the internal fuzzer, if they exist.
224fn set_up_inner_replay<FEN: FoundryEvmNetwork>(
225    executor: &mut Executor<FEN>,
226    inner_sequence: &[Option<BasicTxDetails>],
227) {
228    if let Some(fuzzer) = &mut executor.inspector_mut().fuzzer
229        && let Some(call_generator) = &mut fuzzer.call_generator
230    {
231        call_generator.last_sequence = Arc::new(RwLock::new(inner_sequence.to_owned()));
232        call_generator.set_replay(true);
233    }
234}