foundry_evm/executors/invariant/
mod.rs

1use crate::{
2    executors::{Executor, RawCallResult},
3    inspectors::Fuzzer,
4};
5use alloy_primitives::{Address, Bytes, FixedBytes, Selector, U256, map::HashMap};
6use alloy_sol_types::{SolCall, sol};
7use eyre::{ContextCompat, Result, eyre};
8use foundry_common::contracts::{ContractsByAddress, ContractsByArtifact};
9use foundry_config::InvariantConfig;
10use foundry_evm_core::{
11    constants::{
12        CALLER, CHEATCODE_ADDRESS, DEFAULT_CREATE2_DEPLOYER, HARDHAT_CONSOLE_ADDRESS, MAGIC_ASSUME,
13    },
14    precompiles::PRECOMPILES,
15};
16use foundry_evm_fuzz::{
17    FuzzCase, FuzzFixtures, FuzzedCases,
18    invariant::{
19        ArtifactFilters, BasicTxDetails, FuzzRunIdentifiedContracts, InvariantContract,
20        RandomCallGenerator, SenderFilters, TargetedContract, TargetedContracts,
21    },
22    strategies::{EvmFuzzState, invariant_strat, override_call_strat},
23};
24use foundry_evm_traces::{CallTraceArena, SparsedTraceArena};
25use indicatif::ProgressBar;
26use parking_lot::RwLock;
27use proptest::{strategy::Strategy, test_runner::TestRunner};
28use result::{assert_after_invariant, assert_invariants, can_continue};
29use revm::state::Account;
30use shrink::shrink_sequence;
31use std::{
32    cell::RefCell,
33    collections::{HashMap as Map, btree_map::Entry},
34    sync::Arc,
35    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
36};
37
38mod error;
39pub use error::{InvariantFailures, InvariantFuzzError};
40use foundry_evm_coverage::HitMaps;
41
42mod replay;
43pub use replay::{replay_error, replay_run};
44
45mod result;
46use foundry_common::{TestFunctionExt, sh_println};
47pub use result::InvariantFuzzTestResult;
48use serde::{Deserialize, Serialize};
49use serde_json::json;
50
51mod corpus;
52
53mod shrink;
54use crate::executors::{EvmError, FuzzTestTimer, invariant::corpus::TxCorpusManager};
55pub use shrink::check_sequence;
56
57sol! {
58    interface IInvariantTest {
59        #[derive(Default)]
60        struct FuzzSelector {
61            address addr;
62            bytes4[] selectors;
63        }
64
65        #[derive(Default)]
66        struct FuzzArtifactSelector {
67            string artifact;
68            bytes4[] selectors;
69        }
70
71        #[derive(Default)]
72        struct FuzzInterface {
73            address addr;
74            string[] artifacts;
75        }
76
77        function afterInvariant() external;
78
79        #[derive(Default)]
80        function excludeArtifacts() public view returns (string[] memory excludedArtifacts);
81
82        #[derive(Default)]
83        function excludeContracts() public view returns (address[] memory excludedContracts);
84
85        #[derive(Default)]
86        function excludeSelectors() public view returns (FuzzSelector[] memory excludedSelectors);
87
88        #[derive(Default)]
89        function excludeSenders() public view returns (address[] memory excludedSenders);
90
91        #[derive(Default)]
92        function targetArtifacts() public view returns (string[] memory targetedArtifacts);
93
94        #[derive(Default)]
95        function targetArtifactSelectors() public view returns (FuzzArtifactSelector[] memory targetedArtifactSelectors);
96
97        #[derive(Default)]
98        function targetContracts() public view returns (address[] memory targetedContracts);
99
100        #[derive(Default)]
101        function targetSelectors() public view returns (FuzzSelector[] memory targetedSelectors);
102
103        #[derive(Default)]
104        function targetSenders() public view returns (address[] memory targetedSenders);
105
106        #[derive(Default)]
107        function targetInterfaces() public view returns (FuzzInterface[] memory targetedInterfaces);
108    }
109}
110
111const DURATION_BETWEEN_METRICS_REPORT: Duration = Duration::from_secs(5);
112
113/// Contains invariant metrics for a single fuzzed selector.
114#[derive(Default, Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
115pub struct InvariantMetrics {
116    // Count of fuzzed selector calls.
117    pub calls: usize,
118    // Count of fuzzed selector reverts.
119    pub reverts: usize,
120    // Count of fuzzed selector discards (through assume cheatcodes).
121    pub discards: usize,
122}
123
124/// Contains data collected during invariant test runs.
125pub struct InvariantTestData {
126    // Consumed gas and calldata of every successful fuzz call.
127    pub fuzz_cases: Vec<FuzzedCases>,
128    // Data related to reverts or failed assertions of the test.
129    pub failures: InvariantFailures,
130    // Calldata in the last invariant run.
131    pub last_run_inputs: Vec<BasicTxDetails>,
132    // Additional traces for gas report.
133    pub gas_report_traces: Vec<Vec<CallTraceArena>>,
134    // Last call results of the invariant test.
135    pub last_call_results: Option<RawCallResult>,
136    // Line coverage information collected from all fuzzed calls.
137    pub line_coverage: Option<HitMaps>,
138    // Metrics for each fuzzed selector.
139    pub metrics: Map<String, InvariantMetrics>,
140
141    // Proptest runner to query for random values.
142    // The strategy only comes with the first `input`. We fill the rest of the `inputs`
143    // until the desired `depth` so we can use the evolving fuzz dictionary
144    // during the run.
145    pub branch_runner: TestRunner,
146}
147
148/// Contains invariant test data.
149pub struct InvariantTest {
150    // Fuzz state of invariant test.
151    pub fuzz_state: EvmFuzzState,
152    // Contracts fuzzed by the invariant test.
153    pub targeted_contracts: FuzzRunIdentifiedContracts,
154    // Data collected during invariant runs.
155    pub execution_data: RefCell<InvariantTestData>,
156}
157
158impl InvariantTest {
159    /// Instantiates an invariant test.
160    pub fn new(
161        fuzz_state: EvmFuzzState,
162        targeted_contracts: FuzzRunIdentifiedContracts,
163        failures: InvariantFailures,
164        last_call_results: Option<RawCallResult>,
165        branch_runner: TestRunner,
166    ) -> Self {
167        let mut fuzz_cases = vec![];
168        if last_call_results.is_none() {
169            fuzz_cases.push(FuzzedCases::new(vec![]));
170        }
171        let execution_data = RefCell::new(InvariantTestData {
172            fuzz_cases,
173            failures,
174            last_run_inputs: vec![],
175            gas_report_traces: vec![],
176            last_call_results,
177            line_coverage: None,
178            metrics: Map::default(),
179            branch_runner,
180        });
181        Self { fuzz_state, targeted_contracts, execution_data }
182    }
183
184    /// Returns number of invariant test reverts.
185    pub fn reverts(&self) -> usize {
186        self.execution_data.borrow().failures.reverts
187    }
188
189    /// Whether invariant test has errors or not.
190    pub fn has_errors(&self) -> bool {
191        self.execution_data.borrow().failures.error.is_some()
192    }
193
194    /// Set invariant test error.
195    pub fn set_error(&self, error: InvariantFuzzError) {
196        self.execution_data.borrow_mut().failures.error = Some(error);
197    }
198
199    /// Set last invariant test call results.
200    pub fn set_last_call_results(&self, call_result: Option<RawCallResult>) {
201        self.execution_data.borrow_mut().last_call_results = call_result;
202    }
203
204    /// Set last invariant run call sequence.
205    pub fn set_last_run_inputs(&self, inputs: &Vec<BasicTxDetails>) {
206        self.execution_data.borrow_mut().last_run_inputs.clone_from(inputs);
207    }
208
209    /// Merge current collected line coverage with the new coverage from last fuzzed call.
210    pub fn merge_coverage(&self, new_coverage: Option<HitMaps>) {
211        HitMaps::merge_opt(&mut self.execution_data.borrow_mut().line_coverage, new_coverage);
212    }
213
214    /// Update metrics for a fuzzed selector, extracted from tx details.
215    /// Always increments number of calls; discarded runs (through assume cheatcodes) are tracked
216    /// separated from reverts.
217    pub fn record_metrics(&self, tx_details: &BasicTxDetails, reverted: bool, discarded: bool) {
218        if let Some(metric_key) =
219            self.targeted_contracts.targets.lock().fuzzed_metric_key(tx_details)
220        {
221            let test_metrics = &mut self.execution_data.borrow_mut().metrics;
222            let invariant_metrics = test_metrics.entry(metric_key).or_default();
223            invariant_metrics.calls += 1;
224            if discarded {
225                invariant_metrics.discards += 1;
226            } else if reverted {
227                invariant_metrics.reverts += 1;
228            }
229        }
230    }
231
232    /// End invariant test run by collecting results, cleaning collected artifacts and reverting
233    /// created fuzz state.
234    pub fn end_run(&self, run: InvariantTestRun, gas_samples: usize) {
235        // We clear all the targeted contracts created during this run.
236        self.targeted_contracts.clear_created_contracts(run.created_contracts);
237
238        let mut invariant_data = self.execution_data.borrow_mut();
239        if invariant_data.gas_report_traces.len() < gas_samples {
240            invariant_data
241                .gas_report_traces
242                .push(run.run_traces.into_iter().map(|arena| arena.arena).collect());
243        }
244        invariant_data.fuzz_cases.push(FuzzedCases::new(run.fuzz_runs));
245
246        // Revert state to not persist values between runs.
247        self.fuzz_state.revert();
248    }
249}
250
251/// Contains data for an invariant test run.
252pub struct InvariantTestRun {
253    // Invariant run call sequence.
254    pub inputs: Vec<BasicTxDetails>,
255    // Current invariant run executor.
256    pub executor: Executor,
257    // Invariant run stat reports (eg. gas usage).
258    pub fuzz_runs: Vec<FuzzCase>,
259    // Contracts created during current invariant run.
260    pub created_contracts: Vec<Address>,
261    // Traces of each call of the invariant run call sequence.
262    pub run_traces: Vec<SparsedTraceArena>,
263    // Current depth of invariant run.
264    pub depth: u32,
265    // Current assume rejects of the invariant run.
266    pub assume_rejects_counter: u32,
267    // Whether new coverage was discovered during this run.
268    pub new_coverage: bool,
269}
270
271impl InvariantTestRun {
272    /// Instantiates an invariant test run.
273    pub fn new(first_input: BasicTxDetails, executor: Executor, depth: usize) -> Self {
274        Self {
275            inputs: vec![first_input],
276            executor,
277            fuzz_runs: Vec::with_capacity(depth),
278            created_contracts: vec![],
279            run_traces: vec![],
280            depth: 0,
281            assume_rejects_counter: 0,
282            new_coverage: false,
283        }
284    }
285}
286
287/// Wrapper around any [`Executor`] implementer which provides fuzzing support using [`proptest`].
288///
289/// After instantiation, calling `invariant_fuzz` will proceed to hammer the deployed smart
290/// contracts with inputs, until it finds a counterexample sequence. The provided [`TestRunner`]
291/// contains all the configuration which can be overridden via [environment
292/// variables](proptest::test_runner::Config)
293pub struct InvariantExecutor<'a> {
294    pub executor: Executor,
295    /// Proptest runner.
296    runner: TestRunner,
297    /// The invariant configuration
298    config: InvariantConfig,
299    /// Contracts deployed with `setUp()`
300    setup_contracts: &'a ContractsByAddress,
301    /// Contracts that are part of the project but have not been deployed yet. We need the bytecode
302    /// to identify them from the stateset changes.
303    project_contracts: &'a ContractsByArtifact,
304    /// Filters contracts to be fuzzed through their artifact identifiers.
305    artifact_filters: ArtifactFilters,
306    /// History of binned hitcount of edges seen during fuzzing.
307    history_map: Vec<u8>,
308}
309const COVERAGE_MAP_SIZE: usize = 65536;
310
311impl<'a> InvariantExecutor<'a> {
312    /// Instantiates a fuzzed executor EVM given a testrunner
313    pub fn new(
314        executor: Executor,
315        runner: TestRunner,
316        config: InvariantConfig,
317        setup_contracts: &'a ContractsByAddress,
318        project_contracts: &'a ContractsByArtifact,
319    ) -> Self {
320        Self {
321            executor,
322            runner,
323            config,
324            setup_contracts,
325            project_contracts,
326            artifact_filters: ArtifactFilters::default(),
327            history_map: vec![0u8; COVERAGE_MAP_SIZE],
328        }
329    }
330
331    /// Fuzzes any deployed contract and checks any broken invariant at `invariant_address`.
332    pub fn invariant_fuzz(
333        &mut self,
334        invariant_contract: InvariantContract<'_>,
335        fuzz_fixtures: &FuzzFixtures,
336        deployed_libs: &[Address],
337        progress: Option<&ProgressBar>,
338    ) -> Result<InvariantFuzzTestResult> {
339        // Throw an error to abort test run if the invariant function accepts input params
340        if !invariant_contract.invariant_function.inputs.is_empty() {
341            return Err(eyre!("Invariant test function should have no inputs"));
342        }
343
344        let (invariant_test, mut corpus_manager) =
345            self.prepare_test(&invariant_contract, fuzz_fixtures, deployed_libs)?;
346
347        // Start timer for this invariant test.
348        let mut runs = 0;
349        let timer = FuzzTestTimer::new(self.config.timeout);
350        let mut last_metrics_report = Instant::now();
351        let continue_campaign = |runs: u32| {
352            // If timeout is configured, then perform invariant runs until expires.
353            if self.config.timeout.is_some() {
354                return !timer.is_timed_out();
355            }
356            // If no timeout configured then loop until configured runs.
357            runs < self.config.runs
358        };
359
360        'stop: while continue_campaign(runs) {
361            let initial_seq = corpus_manager.new_sequence(&invariant_test)?;
362
363            // Create current invariant run data.
364            let mut current_run = InvariantTestRun::new(
365                initial_seq[0].clone(),
366                // Before each run, we must reset the backend state.
367                self.executor.clone(),
368                self.config.depth as usize,
369            );
370
371            // We stop the run immediately if we have reverted, and `fail_on_revert` is set.
372            if self.config.fail_on_revert && invariant_test.reverts() > 0 {
373                return Err(eyre!("call reverted"));
374            }
375
376            while current_run.depth < self.config.depth {
377                // Check if the timeout has been reached.
378                if timer.is_timed_out() {
379                    // Since we never record a revert here the test is still considered
380                    // successful even though it timed out. We *want*
381                    // this behavior for now, so that's ok, but
382                    // future developers should be aware of this.
383                    break 'stop;
384                }
385
386                let tx = current_run
387                    .inputs
388                    .last()
389                    .ok_or_else(|| eyre!("no input generated to call fuzzed target."))?;
390
391                // Execute call from the randomly generated sequence without committing state.
392                // State is committed only if call is not a magic assume.
393                let mut call_result = current_run
394                    .executor
395                    .call_raw(
396                        tx.sender,
397                        tx.call_details.target,
398                        tx.call_details.calldata.clone(),
399                        U256::ZERO,
400                    )
401                    .map_err(|e| eyre!(format!("Could not make raw evm call: {e}")))?;
402
403                let discarded = call_result.result.as_ref() == MAGIC_ASSUME;
404                if self.config.show_metrics {
405                    invariant_test.record_metrics(tx, call_result.reverted, discarded);
406                }
407
408                // Collect line coverage from last fuzzed call.
409                invariant_test.merge_coverage(call_result.line_coverage.clone());
410                // If coverage guided fuzzing is enabled then merge edge count with current history
411                // map and set new coverage in current run.
412                if self.config.corpus_dir.is_some() {
413                    let (new_coverage, is_edge) =
414                        call_result.merge_edge_coverage(&mut self.history_map);
415                    if new_coverage {
416                        current_run.new_coverage = true;
417                        corpus_manager.update_seen_metrics(is_edge);
418                    }
419                }
420
421                if discarded {
422                    current_run.inputs.pop();
423                    current_run.assume_rejects_counter += 1;
424                    if current_run.assume_rejects_counter > self.config.max_assume_rejects {
425                        invariant_test.set_error(InvariantFuzzError::MaxAssumeRejects(
426                            self.config.max_assume_rejects,
427                        ));
428                        break 'stop;
429                    }
430                } else {
431                    // Commit executed call result.
432                    current_run.executor.commit(&mut call_result);
433
434                    // Collect data for fuzzing from the state changeset.
435                    // This step updates the state dictionary and therefore invalidates the
436                    // ValueTree in use by the current run. This manifestsitself in proptest
437                    // observing a different input case than what it was called with, and creates
438                    // inconsistencies whenever proptest tries to use the input case after test
439                    // execution.
440                    // See <https://github.com/foundry-rs/foundry/issues/9764>.
441                    let mut state_changeset = call_result.state_changeset.clone();
442                    if !call_result.reverted {
443                        collect_data(
444                            &invariant_test,
445                            &mut state_changeset,
446                            tx,
447                            &call_result,
448                            self.config.depth,
449                        );
450                    }
451
452                    // Collect created contracts and add to fuzz targets only if targeted contracts
453                    // are updatable.
454                    if let Err(error) =
455                        &invariant_test.targeted_contracts.collect_created_contracts(
456                            &state_changeset,
457                            self.project_contracts,
458                            self.setup_contracts,
459                            &self.artifact_filters,
460                            &mut current_run.created_contracts,
461                        )
462                    {
463                        warn!(target: "forge::test", "{error}");
464                    }
465                    current_run.fuzz_runs.push(FuzzCase {
466                        calldata: tx.call_details.calldata.clone(),
467                        gas: call_result.gas_used,
468                        stipend: call_result.stipend,
469                    });
470
471                    // Determine if test can continue or should exit.
472                    let result = can_continue(
473                        &invariant_contract,
474                        &invariant_test,
475                        &mut current_run,
476                        &self.config,
477                        call_result,
478                        &state_changeset,
479                    )
480                    .map_err(|e| eyre!(e.to_string()))?;
481                    if !result.can_continue || current_run.depth == self.config.depth - 1 {
482                        invariant_test.set_last_run_inputs(&current_run.inputs);
483                    }
484                    // If test cannot continue then stop current run and exit test suite.
485                    if !result.can_continue {
486                        break 'stop;
487                    }
488
489                    invariant_test.set_last_call_results(result.call_result);
490                    current_run.depth += 1;
491                }
492
493                current_run.inputs.push(corpus_manager.generate_next_input(
494                    &invariant_test,
495                    &initial_seq,
496                    discarded,
497                    current_run.depth as usize,
498                )?);
499            }
500
501            // Extend corpus with current run data.
502            corpus_manager.collect_inputs(&current_run);
503
504            // Call `afterInvariant` only if it is declared and test didn't fail already.
505            if invariant_contract.call_after_invariant && !invariant_test.has_errors() {
506                assert_after_invariant(
507                    &invariant_contract,
508                    &invariant_test,
509                    &current_run,
510                    &self.config,
511                )
512                .map_err(|_| eyre!("Failed to call afterInvariant"))?;
513            }
514
515            // End current invariant test run.
516            invariant_test.end_run(current_run, self.config.gas_report_samples as usize);
517
518            if let Some(progress) = progress {
519                // If running with progress then increment completed runs.
520                progress.inc(1);
521                // Display metrics in progress bar.
522                if self.config.corpus_dir.is_some() {
523                    progress.set_message(format!("{}", &corpus_manager.metrics));
524                }
525            } else if self.config.corpus_dir.is_some()
526                && last_metrics_report.elapsed() > DURATION_BETWEEN_METRICS_REPORT
527            {
528                // Display metrics inline if corpus dir set.
529                let metrics = json!({
530                    "timestamp": SystemTime::now()
531                        .duration_since(UNIX_EPOCH)?
532                        .as_secs(),
533                    "invariant": invariant_contract.invariant_function.name,
534                    "metrics": &corpus_manager.metrics,
535                });
536                let _ = sh_println!("{}", serde_json::to_string(&metrics)?);
537                last_metrics_report = Instant::now();
538            }
539
540            runs += 1;
541        }
542
543        trace!(?fuzz_fixtures);
544        invariant_test.fuzz_state.log_stats();
545
546        let result = invariant_test.execution_data.into_inner();
547        Ok(InvariantFuzzTestResult {
548            error: result.failures.error,
549            cases: result.fuzz_cases,
550            reverts: result.failures.reverts,
551            last_run_inputs: result.last_run_inputs,
552            gas_report_traces: result.gas_report_traces,
553            line_coverage: result.line_coverage,
554            metrics: result.metrics,
555            failed_corpus_replays: corpus_manager.failed_replays(),
556        })
557    }
558
559    /// Prepares certain structures to execute the invariant tests:
560    /// * Invariant Fuzz Test.
561    /// * Invariant Corpus Manager.
562    fn prepare_test(
563        &mut self,
564        invariant_contract: &InvariantContract<'_>,
565        fuzz_fixtures: &FuzzFixtures,
566        deployed_libs: &[Address],
567    ) -> Result<(InvariantTest, TxCorpusManager)> {
568        // Finds out the chosen deployed contracts and/or senders.
569        self.select_contract_artifacts(invariant_contract.address)?;
570        let (targeted_senders, targeted_contracts) =
571            self.select_contracts_and_senders(invariant_contract.address)?;
572
573        // Stores fuzz state for use with [fuzz_calldata_from_state].
574        let fuzz_state = EvmFuzzState::new(
575            self.executor.backend().mem_db(),
576            self.config.dictionary,
577            deployed_libs,
578        );
579
580        // Creates the invariant strategy.
581        let strategy = invariant_strat(
582            fuzz_state.clone(),
583            targeted_senders,
584            targeted_contracts.clone(),
585            self.config.dictionary.dictionary_weight,
586            fuzz_fixtures.clone(),
587        )
588        .no_shrink();
589
590        // Allows `override_call_strat` to use the address given by the Fuzzer inspector during
591        // EVM execution.
592        let mut call_generator = None;
593        if self.config.call_override {
594            let target_contract_ref = Arc::new(RwLock::new(Address::ZERO));
595
596            call_generator = Some(RandomCallGenerator::new(
597                invariant_contract.address,
598                self.runner.clone(),
599                override_call_strat(
600                    fuzz_state.clone(),
601                    targeted_contracts.clone(),
602                    target_contract_ref.clone(),
603                    fuzz_fixtures.clone(),
604                ),
605                target_contract_ref,
606            ));
607        }
608
609        self.executor.inspector_mut().fuzzer =
610            Some(Fuzzer { call_generator, fuzz_state: fuzz_state.clone(), collect: true });
611
612        // Let's make sure the invariant is sound before actually starting the run:
613        // We'll assert the invariant in its initial state, and if it fails, we'll
614        // already know if we can early exit the invariant run.
615        // This does not count as a fuzz run. It will just register the revert.
616        let mut failures = InvariantFailures::new();
617        let last_call_results = assert_invariants(
618            invariant_contract,
619            &self.config,
620            &targeted_contracts,
621            &self.executor,
622            &[],
623            &mut failures,
624        )?;
625        if let Some(error) = failures.error {
626            return Err(eyre!(error.revert_reason().unwrap_or_default()));
627        }
628
629        let corpus_manager = TxCorpusManager::new(
630            &self.config,
631            &invariant_contract.invariant_function.name,
632            &targeted_contracts,
633            strategy.boxed(),
634            &self.executor,
635            &mut self.history_map,
636        )?;
637
638        let invariant_test = InvariantTest::new(
639            fuzz_state,
640            targeted_contracts,
641            failures,
642            last_call_results,
643            self.runner.clone(),
644        );
645
646        Ok((invariant_test, corpus_manager))
647    }
648
649    /// Fills the `InvariantExecutor` with the artifact identifier filters (in `path:name` string
650    /// format). They will be used to filter contracts after the `setUp`, and more importantly,
651    /// during the runs.
652    ///
653    /// Also excludes any contract without any mutable functions.
654    ///
655    /// Priority:
656    ///
657    /// targetArtifactSelectors > excludeArtifacts > targetArtifacts
658    pub fn select_contract_artifacts(&mut self, invariant_address: Address) -> Result<()> {
659        let targeted_artifact_selectors = self
660            .executor
661            .call_sol_default(invariant_address, &IInvariantTest::targetArtifactSelectorsCall {});
662
663        // Insert them into the executor `targeted_abi`.
664        for IInvariantTest::FuzzArtifactSelector { artifact, selectors } in
665            targeted_artifact_selectors
666        {
667            let identifier = self.validate_selected_contract(artifact, &selectors)?;
668            self.artifact_filters.targeted.entry(identifier).or_default().extend(selectors);
669        }
670
671        let targeted_artifacts = self
672            .executor
673            .call_sol_default(invariant_address, &IInvariantTest::targetArtifactsCall {});
674        let excluded_artifacts = self
675            .executor
676            .call_sol_default(invariant_address, &IInvariantTest::excludeArtifactsCall {});
677
678        // Insert `excludeArtifacts` into the executor `excluded_abi`.
679        for contract in excluded_artifacts {
680            let identifier = self.validate_selected_contract(contract, &[])?;
681
682            if !self.artifact_filters.excluded.contains(&identifier) {
683                self.artifact_filters.excluded.push(identifier);
684            }
685        }
686
687        // Exclude any artifact without mutable functions.
688        for (artifact, contract) in self.project_contracts.iter() {
689            if contract
690                .abi
691                .functions()
692                .filter(|func| {
693                    !matches!(
694                        func.state_mutability,
695                        alloy_json_abi::StateMutability::Pure
696                            | alloy_json_abi::StateMutability::View
697                    )
698                })
699                .count()
700                == 0
701                && !self.artifact_filters.excluded.contains(&artifact.identifier())
702            {
703                self.artifact_filters.excluded.push(artifact.identifier());
704            }
705        }
706
707        // Insert `targetArtifacts` into the executor `targeted_abi`, if they have not been seen
708        // before.
709        for contract in targeted_artifacts {
710            let identifier = self.validate_selected_contract(contract, &[])?;
711
712            if !self.artifact_filters.targeted.contains_key(&identifier)
713                && !self.artifact_filters.excluded.contains(&identifier)
714            {
715                self.artifact_filters.targeted.insert(identifier, vec![]);
716            }
717        }
718        Ok(())
719    }
720
721    /// Makes sure that the contract exists in the project. If so, it returns its artifact
722    /// identifier.
723    fn validate_selected_contract(
724        &mut self,
725        contract: String,
726        selectors: &[FixedBytes<4>],
727    ) -> Result<String> {
728        if let Some((artifact, contract_data)) =
729            self.project_contracts.find_by_name_or_identifier(&contract)?
730        {
731            // Check that the selectors really exist for this contract.
732            for selector in selectors {
733                contract_data
734                    .abi
735                    .functions()
736                    .find(|func| func.selector().as_slice() == selector.as_slice())
737                    .wrap_err(format!("{contract} does not have the selector {selector:?}"))?;
738            }
739
740            return Ok(artifact.identifier());
741        }
742        eyre::bail!(
743            "{contract} not found in the project. Allowed format: `contract_name` or `contract_path:contract_name`."
744        );
745    }
746
747    /// Selects senders and contracts based on the contract methods `targetSenders() -> address[]`,
748    /// `targetContracts() -> address[]` and `excludeContracts() -> address[]`.
749    pub fn select_contracts_and_senders(
750        &self,
751        to: Address,
752    ) -> Result<(SenderFilters, FuzzRunIdentifiedContracts)> {
753        let targeted_senders =
754            self.executor.call_sol_default(to, &IInvariantTest::targetSendersCall {});
755        let mut excluded_senders =
756            self.executor.call_sol_default(to, &IInvariantTest::excludeSendersCall {});
757        // Extend with default excluded addresses - https://github.com/foundry-rs/foundry/issues/4163
758        excluded_senders.extend([
759            CHEATCODE_ADDRESS,
760            HARDHAT_CONSOLE_ADDRESS,
761            DEFAULT_CREATE2_DEPLOYER,
762        ]);
763        // Extend with precompiles - https://github.com/foundry-rs/foundry/issues/4287
764        excluded_senders.extend(PRECOMPILES);
765        let sender_filters = SenderFilters::new(targeted_senders, excluded_senders);
766
767        let selected = self.executor.call_sol_default(to, &IInvariantTest::targetContractsCall {});
768        let excluded = self.executor.call_sol_default(to, &IInvariantTest::excludeContractsCall {});
769
770        let contracts = self
771            .setup_contracts
772            .iter()
773            .filter(|&(addr, (identifier, _))| {
774                // Include to address if explicitly set as target.
775                if *addr == to && selected.contains(&to) {
776                    return true;
777                }
778
779                *addr != to
780                    && *addr != CHEATCODE_ADDRESS
781                    && *addr != HARDHAT_CONSOLE_ADDRESS
782                    && (selected.is_empty() || selected.contains(addr))
783                    && (excluded.is_empty() || !excluded.contains(addr))
784                    && self.artifact_filters.matches(identifier)
785            })
786            .map(|(addr, (identifier, abi))| {
787                (*addr, TargetedContract::new(identifier.clone(), abi.clone()))
788            })
789            .collect();
790        let mut contracts = TargetedContracts { inner: contracts };
791
792        self.target_interfaces(to, &mut contracts)?;
793
794        self.select_selectors(to, &mut contracts)?;
795
796        // There should be at least one contract identified as target for fuzz runs.
797        if contracts.is_empty() {
798            eyre::bail!("No contracts to fuzz.");
799        }
800
801        Ok((sender_filters, FuzzRunIdentifiedContracts::new(contracts, selected.is_empty())))
802    }
803
804    /// Extends the contracts and selectors to fuzz with the addresses and ABIs specified in
805    /// `targetInterfaces() -> (address, string[])[]`. Enables targeting of addresses that are
806    /// not deployed during `setUp` such as when fuzzing in a forked environment. Also enables
807    /// targeting of delegate proxies and contracts deployed with `create` or `create2`.
808    pub fn target_interfaces(
809        &self,
810        invariant_address: Address,
811        targeted_contracts: &mut TargetedContracts,
812    ) -> Result<()> {
813        let interfaces = self
814            .executor
815            .call_sol_default(invariant_address, &IInvariantTest::targetInterfacesCall {});
816
817        // Since `targetInterfaces` returns a tuple array there is no guarantee
818        // that the addresses are unique this map is used to merge functions of
819        // the specified interfaces for the same address. For example:
820        // `[(addr1, ["IERC20", "IOwnable"])]` and `[(addr1, ["IERC20"]), (addr1, ("IOwnable"))]`
821        // should be equivalent.
822        let mut combined = TargetedContracts::new();
823
824        // Loop through each address and its associated artifact identifiers.
825        // We're borrowing here to avoid taking full ownership.
826        for IInvariantTest::FuzzInterface { addr, artifacts } in &interfaces {
827            // Identifiers are specified as an array, so we loop through them.
828            for identifier in artifacts {
829                // Try to find the contract by name or identifier in the project's contracts.
830                if let Some(abi) = self.project_contracts.find_abi_by_name_or_identifier(identifier)
831                {
832                    combined
833                        // Check if there's an entry for the given key in the 'combined' map.
834                        .entry(*addr)
835                        // If the entry exists, extends its ABI with the function list.
836                        .and_modify(|entry| {
837                            // Extend the ABI's function list with the new functions.
838                            entry.abi.functions.extend(abi.functions.clone());
839                        })
840                        // Otherwise insert it into the map.
841                        .or_insert_with(|| TargetedContract::new(identifier.to_string(), abi));
842                }
843            }
844        }
845
846        targeted_contracts.extend(combined.inner);
847
848        Ok(())
849    }
850
851    /// Selects the functions to fuzz based on the contract method `targetSelectors()` and
852    /// `targetArtifactSelectors()`.
853    pub fn select_selectors(
854        &self,
855        address: Address,
856        targeted_contracts: &mut TargetedContracts,
857    ) -> Result<()> {
858        for (address, (identifier, _)) in self.setup_contracts {
859            if let Some(selectors) = self.artifact_filters.targeted.get(identifier) {
860                self.add_address_with_functions(*address, selectors, false, targeted_contracts)?;
861            }
862        }
863
864        let mut target_test_selectors = vec![];
865        let mut excluded_test_selectors = vec![];
866
867        // Collect contract functions marked as target for fuzzing campaign.
868        let selectors =
869            self.executor.call_sol_default(address, &IInvariantTest::targetSelectorsCall {});
870        for IInvariantTest::FuzzSelector { addr, selectors } in selectors {
871            if addr == address {
872                target_test_selectors = selectors.clone();
873            }
874            self.add_address_with_functions(addr, &selectors, false, targeted_contracts)?;
875        }
876
877        // Collect contract functions excluded from fuzzing campaign.
878        let excluded_selectors =
879            self.executor.call_sol_default(address, &IInvariantTest::excludeSelectorsCall {});
880        for IInvariantTest::FuzzSelector { addr, selectors } in excluded_selectors {
881            if addr == address {
882                // If fuzz selector address is the test contract, then record selectors to be
883                // later excluded if needed.
884                excluded_test_selectors = selectors.clone();
885            }
886            self.add_address_with_functions(addr, &selectors, true, targeted_contracts)?;
887        }
888
889        if target_test_selectors.is_empty()
890            && let Some(target) = targeted_contracts.get(&address)
891        {
892            // If test contract is marked as a target and no target selector explicitly set, then
893            // include only state-changing functions that are not reserved and selectors that are
894            // not explicitly excluded.
895            let selectors: Vec<_> = target
896                .abi
897                .functions()
898                .filter_map(|func| {
899                    if matches!(
900                        func.state_mutability,
901                        alloy_json_abi::StateMutability::Pure
902                            | alloy_json_abi::StateMutability::View
903                    ) || func.is_reserved()
904                        || excluded_test_selectors.contains(&func.selector())
905                    {
906                        None
907                    } else {
908                        Some(func.selector())
909                    }
910                })
911                .collect();
912            self.add_address_with_functions(address, &selectors, false, targeted_contracts)?;
913        }
914
915        Ok(())
916    }
917
918    /// Adds the address and fuzzed or excluded functions to `TargetedContracts`.
919    fn add_address_with_functions(
920        &self,
921        address: Address,
922        selectors: &[Selector],
923        should_exclude: bool,
924        targeted_contracts: &mut TargetedContracts,
925    ) -> eyre::Result<()> {
926        // Do not add address in target contracts if no function selected.
927        if selectors.is_empty() {
928            return Ok(());
929        }
930
931        let contract = match targeted_contracts.entry(address) {
932            Entry::Occupied(entry) => entry.into_mut(),
933            Entry::Vacant(entry) => {
934                let (identifier, abi) = self.setup_contracts.get(&address).ok_or_else(|| {
935                    eyre::eyre!(
936                        "[{}] address does not have an associated contract: {}",
937                        if should_exclude { "excludeSelectors" } else { "targetSelectors" },
938                        address
939                    )
940                })?;
941                entry.insert(TargetedContract::new(identifier.clone(), abi.clone()))
942            }
943        };
944        contract.add_selectors(selectors.iter().copied(), should_exclude)?;
945        Ok(())
946    }
947}
948
949/// Collects data from call for fuzzing. However, it first verifies that the sender is not an EOA
950/// before inserting it into the dictionary. Otherwise, we flood the dictionary with
951/// randomly generated addresses.
952fn collect_data(
953    invariant_test: &InvariantTest,
954    state_changeset: &mut HashMap<Address, Account>,
955    tx: &BasicTxDetails,
956    call_result: &RawCallResult,
957    run_depth: u32,
958) {
959    // Verify it has no code.
960    let mut has_code = false;
961    if let Some(Some(code)) =
962        state_changeset.get(&tx.sender).map(|account| account.info.code.as_ref())
963    {
964        has_code = !code.is_empty();
965    }
966
967    // We keep the nonce changes to apply later.
968    let mut sender_changeset = None;
969    if !has_code {
970        sender_changeset = state_changeset.remove(&tx.sender);
971    }
972
973    // Collect values from fuzzed call result and add them to fuzz dictionary.
974    invariant_test.fuzz_state.collect_values_from_call(
975        &invariant_test.targeted_contracts,
976        tx,
977        &call_result.result,
978        &call_result.logs,
979        &*state_changeset,
980        run_depth,
981    );
982
983    // Re-add changes
984    if let Some(changed) = sender_changeset {
985        state_changeset.insert(tx.sender, changed);
986    }
987}
988
989/// Calls the `afterInvariant()` function on a contract.
990/// Returns call result and if call succeeded.
991/// The state after the call is not persisted.
992pub(crate) fn call_after_invariant_function(
993    executor: &Executor,
994    to: Address,
995) -> Result<(RawCallResult, bool), EvmError> {
996    let calldata = Bytes::from_static(&IInvariantTest::afterInvariantCall::SELECTOR);
997    let mut call_result = executor.call_raw(CALLER, to, calldata, U256::ZERO)?;
998    let success = executor.is_raw_call_mut_success(to, &mut call_result, false);
999    Ok((call_result, success))
1000}
1001
1002/// Calls the invariant function and returns call result and if succeeded.
1003pub(crate) fn call_invariant_function(
1004    executor: &Executor,
1005    address: Address,
1006    calldata: Bytes,
1007) -> Result<(RawCallResult, bool)> {
1008    let mut call_result = executor.call_raw(CALLER, address, calldata, U256::ZERO)?;
1009    let success = executor.is_raw_call_mut_success(address, &mut call_result, false);
1010    Ok((call_result, success))
1011}