Skip to main content

foundry_evm_fuzz/strategies/
invariants.rs

1use super::TxGenerator;
2use crate::{CallDetails, FuzzFixtures, strategies::EvmFuzzState};
3use alloy_json_abi::Function;
4use alloy_primitives::Address;
5use parking_lot::RwLock;
6use proptest::prelude::*;
7use rand::seq::IteratorRandom;
8use std::sync::Arc;
9
10/// Given a target address, we generate random calldata.
11pub fn override_call_strat(
12    fuzz_state: EvmFuzzState,
13    contracts: Vec<(Address, Vec<Function>)>,
14    target: Arc<RwLock<Address>>,
15    fuzz_fixtures: FuzzFixtures,
16    dictionary_weight: u32,
17    payable_value_weight: u32,
18) -> impl Strategy<Value = CallDetails> + Send + Sync + 'static {
19    // Each generated call owns its function-selection strategy. Share the functions so
20    // constructing that strategy does not clone the entire target ABI on every call.
21    let contracts = Arc::new(
22        contracts
23            .into_iter()
24            .map(|(address, functions)| (address, Arc::new(functions)))
25            .collect::<Vec<_>>(),
26    );
27    let contracts_ref = contracts.clone();
28    proptest::prop_oneof![
29        80 => proptest::strategy::LazyJust::new(move || *target.read()),
30        20 => any::<prop::sample::Selector>()
31            .prop_map(move |selector| {
32                let (target, _) = selector.select(contracts_ref.iter());
33                *target
34            }),
35    ]
36    .prop_perturb(|target_address, rng| (target_address, rng))
37    .prop_flat_map(move |(target_address, mut rng)| {
38        let fuzz_state = fuzz_state.clone();
39        let fuzz_fixtures = fuzz_fixtures.clone();
40        let contracts = contracts.clone();
41
42        let (actual_target, func) = {
43            // If the target address is in the contracts map, use it directly.
44            // Otherwise, fall back to a random contract from the targeted contracts.
45            // This can happen when call_override sets target_reference to a contract
46            // that is not in targetContracts (e.g., the protocol contract during reentrancy).
47            let (actual_target, fuzzed_functions) = contracts
48                .iter()
49                .find(|(address, _)| *address == target_address)
50                .map(|(address, functions)| (*address, functions.clone()))
51                .unwrap_or_else(|| {
52                    let (address, functions) =
53                        contracts.iter().choose(&mut rng).expect("at least one target contract");
54                    (*address, functions.clone())
55                });
56            (
57                actual_target,
58                any::<prop::sample::Index>()
59                    .prop_map(move |index| index.get(&fuzzed_functions).clone()),
60            )
61        };
62
63        func.prop_flat_map(move |func| {
64            TxGenerator::call_strategy(
65                &fuzz_state,
66                &fuzz_fixtures,
67                actual_target,
68                func,
69                dictionary_weight,
70                payable_value_weight,
71            )
72        })
73    })
74}
75
76#[cfg(test)]
77mod tests {
78    use super::*;
79    use proptest::{strategy::ValueTree, test_runner::TestRunner};
80
81    #[test]
82    fn untargeted_reference_falls_back_deterministically() {
83        let function = Function::parse("fuzz(uint256)").unwrap();
84        let contracts = (1..=4)
85            .map(|byte| (Address::with_last_byte(byte), vec![function.clone()]))
86            .collect::<Vec<_>>();
87        let strategy = override_call_strat(
88            EvmFuzzState::test(),
89            contracts,
90            Arc::new(RwLock::new(Address::with_last_byte(0xff))),
91            FuzzFixtures::default(),
92            40,
93            0,
94        );
95        let targets = || {
96            let mut runner = TestRunner::deterministic();
97            (0..32)
98                .map(|_| strategy.new_tree(&mut runner).unwrap().current().target)
99                .collect::<Vec<_>>()
100        };
101        assert_eq!(targets(), targets());
102    }
103}