Skip to main content

foundry_evm_fuzz/strategies/
param.rs

1use super::{UintStrategy, state::DictionaryRead};
2use crate::{
3    invariant::SenderFilters,
4    strategies::mutators::{
5        BitMutator, GaussianNoiseMutator, IncrementDecrementMutator, InterestingWordMutator,
6    },
7};
8use alloy_dyn_abi::{DynSolType, DynSolValue, Word};
9use alloy_primitives::{Address, B256, I256, U256};
10use proptest::{prelude::*, strategy::ValueTree, test_runner::TestRunner};
11use rand::{SeedableRng, prelude::IndexedMutRandom, rngs::StdRng};
12use std::mem::replace;
13
14/// The max length of arrays we fuzz for is 256.
15const MAX_ARRAY_LEN: usize = 256;
16
17/// Given a parameter type, returns a strategy for generating values for that type.
18///
19/// See [`fuzz_param_with_fixtures`] for more information.
20pub fn fuzz_param(param: &DynSolType) -> BoxedStrategy<DynSolValue> {
21    fuzz_param_inner(param, None)
22}
23
24/// Given a parameter type and configured fixtures for param name, returns a strategy for generating
25/// values for that type.
26///
27/// Fixtures can be currently generated for uint, int, address, bytes and
28/// string types and are defined for parameter name.
29/// For example, fixtures for parameter `owner` of type `address` can be defined in a function with
30/// a `function fixture_owner() public returns (address[] memory)` signature.
31///
32/// Fixtures are matched on parameter name, hence fixtures defined in
33/// `fixture_owner` function can be used in a fuzzed test function with a signature like
34/// `function testFuzz_ownerAddress(address owner, uint amount)`.
35///
36/// Raises an error if all the fixture types are not of the same type as the input parameter.
37///
38/// Works with ABI Encoder v2 tuples.
39pub fn fuzz_param_with_fixtures(
40    param: &DynSolType,
41    fixtures: Option<&[DynSolValue]>,
42    name: &str,
43) -> BoxedStrategy<DynSolValue> {
44    fuzz_param_inner(param, fixtures.map(|f| (f, name)))
45}
46
47fn fuzz_param_inner(
48    param: &DynSolType,
49    mut fuzz_fixtures: Option<(&[DynSolValue], &str)>,
50) -> BoxedStrategy<DynSolValue> {
51    if let Some((fixtures, name)) = fuzz_fixtures
52        && !fixtures.iter().all(|f| f.matches(param))
53    {
54        error!("fixtures for {name:?} do not match type {param}");
55        fuzz_fixtures = None;
56    }
57    let fuzz_fixtures = fuzz_fixtures.map(|(f, _)| f);
58
59    let value = || {
60        let default_strategy = param.value_strategy();
61        if let Some(fixtures) = fuzz_fixtures {
62            proptest::prop_oneof![
63                50 => {
64                    let fixtures = fixtures.to_vec();
65                    any::<prop::sample::Index>()
66                        .prop_map(move |index| index.get(&fixtures).clone())
67                },
68                50 => default_strategy,
69            ]
70            .boxed()
71        } else {
72            default_strategy.boxed()
73        }
74    };
75
76    match *param {
77        DynSolType::Address => value(),
78        DynSolType::Int(n @ 8..=256) => super::IntStrategy::new(n, fuzz_fixtures)
79            .prop_map(move |x| DynSolValue::Int(x, n))
80            .boxed(),
81        DynSolType::Uint(n @ 8..=256) => super::UintStrategy::new(n, fuzz_fixtures)
82            .prop_map(move |x| DynSolValue::Uint(x, n))
83            .boxed(),
84        DynSolType::Function | DynSolType::Bool => param.value_strategy().boxed(),
85        DynSolType::Bytes => value(),
86        DynSolType::FixedBytes(_size @ 1..=32) => value(),
87        DynSolType::String => {
88            let default_strategy = param.value_strategy().prop_map(move |value| {
89                DynSolValue::String(
90                    value.as_str().unwrap().trim().trim_end_matches('\0').to_string(),
91                )
92            });
93            if let Some(fixtures) = fuzz_fixtures {
94                let fixtures = fixtures.to_vec();
95                proptest::prop_oneof![
96                    50 => any::<prop::sample::Index>()
97                        .prop_map(move |index| index.get(&fixtures).clone()),
98                    50 => default_strategy,
99                ]
100                .boxed()
101            } else {
102                default_strategy.boxed()
103            }
104        }
105        DynSolType::Tuple(ref params) => params
106            .iter()
107            .map(|param| fuzz_param_inner(param, None))
108            .collect::<Vec<_>>()
109            .prop_map(DynSolValue::Tuple)
110            .boxed(),
111        DynSolType::FixedArray(ref param, size) => {
112            proptest::collection::vec(fuzz_param_inner(param, None), size)
113                .prop_map(DynSolValue::FixedArray)
114                .boxed()
115        }
116        DynSolType::Array(ref param) => {
117            proptest::collection::vec(fuzz_param_inner(param, None), 0..MAX_ARRAY_LEN)
118                .prop_map(DynSolValue::Array)
119                .boxed()
120        }
121        _ => panic!("unsupported fuzz param type: {param}"),
122    }
123}
124
125/// Given a parameter type, returns a strategy for generating values for that type, given some EVM
126/// fuzz state.
127///
128/// Works with ABI Encoder v2 tuples.
129pub(crate) fn fuzz_param_from_state(
130    param: &DynSolType,
131    state: &impl DictionaryRead,
132) -> BoxedStrategy<DynSolValue> {
133    // Value strategy that uses the state.
134    let value = || {
135        let state = state.clone();
136        let param = param.clone();
137        // Generate a bias and use it to pick samples or non-persistent values (50 / 50).
138        // Use `Index` instead of `Selector` when selecting a value to avoid iterating over the
139        // entire dictionary.
140        any::<(bool, prop::sample::Index)>().prop_map(move |(bias, index)| {
141            state.with_dictionary(|dict| {
142                let values = if bias { dict.samples(&param) } else { None }
143                    .unwrap_or_else(|| dict.values())
144                    .as_slice();
145                values[index.index(values.len())]
146            })
147        })
148    };
149
150    // Convert the value based on the parameter type
151    match *param {
152        DynSolType::Address => {
153            let deployed_libs = state.deployed_libs().to_vec();
154            value()
155                .prop_map(move |value| {
156                    let mut fuzzed_addr = Address::from_word(value);
157                    if deployed_libs.contains(&fuzzed_addr) {
158                        let mut rng = StdRng::seed_from_u64(0x1337); // use deterministic rng
159
160                        // Do not use addresses of deployed libraries as fuzz input, instead return
161                        // a deterministically random address. We cannot filter out this value (via
162                        // `prop_filter_map`) as proptest can invoke this closure after test
163                        // execution, and returning a `None` will cause it to panic.
164                        // See <https://github.com/foundry-rs/foundry/issues/9764> and <https://github.com/foundry-rs/foundry/issues/8639>.
165                        loop {
166                            fuzzed_addr.randomize_with(&mut rng);
167                            if !deployed_libs.contains(&fuzzed_addr) {
168                                break;
169                            }
170                        }
171                    }
172                    DynSolValue::Address(fuzzed_addr)
173                })
174                .boxed()
175        }
176        DynSolType::Function => value()
177            .prop_map(move |value| {
178                DynSolValue::Function(alloy_primitives::Function::from_word(value))
179            })
180            .boxed(),
181        DynSolType::FixedBytes(size @ 1..=32) => value()
182            .prop_map(move |mut v| {
183                v[size..].fill(0);
184                DynSolValue::FixedBytes(B256::from(v), size)
185            })
186            .boxed(),
187        DynSolType::Bool => param.value_strategy().boxed(),
188        DynSolType::String => {
189            let state = state.clone();
190            (proptest::bool::weighted(0.3), any::<prop::sample::Index>())
191                .prop_flat_map(move |(use_ast, select_index)| {
192                    if let Some(value) = state.with_dictionary(|dict| {
193                        // AST string literals available: 30% probability
194                        let ast_strings = dict.ast_strings();
195                        if use_ast && !ast_strings.is_empty() {
196                            let s = &ast_strings.as_slice()[select_index.index(ast_strings.len())];
197                            return Some(DynSolValue::String(s.clone()));
198                        }
199                        None
200                    }) {
201                        return Just(value).boxed();
202                    }
203
204                    // Fallback to random string generation
205                    DynSolType::String
206                        .value_strategy()
207                        .prop_map(|value| {
208                            DynSolValue::String(
209                                value.as_str().unwrap().trim().trim_end_matches('\0').to_string(),
210                            )
211                        })
212                        .boxed()
213                })
214                .boxed()
215        }
216        DynSolType::Bytes => {
217            let state_clone = state.clone();
218            (
219                value(),
220                proptest::bool::weighted(0.1),
221                proptest::bool::weighted(0.2),
222                any::<prop::sample::Index>(),
223            )
224                .prop_map(move |(word, use_ast_string, use_ast_bytes, select_index)| {
225                    if let Some(value) = state_clone.with_dictionary(|dict| {
226                        // Try string literals as bytes: 10% chance
227                        let ast_strings = dict.ast_strings();
228                        if use_ast_string && !ast_strings.is_empty() {
229                            let s = &ast_strings.as_slice()[select_index.index(ast_strings.len())];
230                            return Some(DynSolValue::Bytes(s.as_bytes().to_vec()));
231                        }
232
233                        // Try hex literals: 20% chance
234                        let ast_bytes = dict.ast_bytes();
235                        if use_ast_bytes && !ast_bytes.is_empty() {
236                            let bytes = &ast_bytes.as_slice()[select_index.index(ast_bytes.len())];
237                            return Some(DynSolValue::Bytes(bytes.to_vec()));
238                        }
239                        None
240                    }) {
241                        return value;
242                    }
243
244                    // Fallback to the generated word from the dictionary: 70% chance
245                    DynSolValue::Bytes(word.0.into())
246                })
247                .boxed()
248        }
249        DynSolType::Int(n @ 8..=256) => match n / 8 {
250            32 => value()
251                .prop_map(move |value| DynSolValue::Int(I256::from_raw(value.into()), 256))
252                .boxed(),
253            1..=31 => value()
254                .prop_map(move |value| {
255                    // Extract lower N bits
256                    let uint_n = Into::<U256>::into(value) % U256::ONE.wrapping_shl(n);
257                    // Interpret as signed int (two's complement) --> check sign bit (bit N-1).
258                    let sign_bit = U256::ONE << (n - 1);
259                    let num = if uint_n >= sign_bit {
260                        // Negative number in two's complement
261                        let modulus = U256::ONE << n;
262                        I256::from_raw(uint_n.wrapping_sub(modulus))
263                    } else {
264                        // Positive number
265                        I256::from_raw(uint_n)
266                    };
267
268                    DynSolValue::Int(num, n)
269                })
270                .boxed(),
271            _ => unreachable!(),
272        },
273        DynSolType::Uint(n @ 8..=256) => match n / 8 {
274            32 => value().prop_map(move |value| DynSolValue::Uint(value.into(), 256)).boxed(),
275            1..=31 => value()
276                .prop_map(move |value| {
277                    let uint = Into::<U256>::into(value) % U256::ONE.wrapping_shl(n);
278                    DynSolValue::Uint(uint, n)
279                })
280                .boxed(),
281            _ => unreachable!(),
282        },
283        DynSolType::Tuple(ref params) => params
284            .iter()
285            .map(|p| fuzz_param_from_state(p, state))
286            .collect::<Vec<_>>()
287            .prop_map(DynSolValue::Tuple)
288            .boxed(),
289        DynSolType::FixedArray(ref param, size) => {
290            proptest::collection::vec(fuzz_param_from_state(param, state), size)
291                .prop_map(DynSolValue::FixedArray)
292                .boxed()
293        }
294        DynSolType::Array(ref param) => {
295            proptest::collection::vec(fuzz_param_from_state(param, state), 0..MAX_ARRAY_LEN)
296                .prop_map(DynSolValue::Array)
297                .boxed()
298        }
299        _ => panic!("unsupported fuzz param type: {param}"),
300    }
301}
302
303/// Selects a random address for mutation, respecting sender filters if provided.
304///
305/// Priority:
306/// 1. If `senders` has targeted addresses, pick randomly from those
307/// 2. Otherwise, pick from the dictionary state values (excluding any in `senders.excluded`)
308/// 3. Returns `None` if no suitable address is found or if the selected address equals `current`
309fn select_random_address(
310    current: Address,
311    test_runner: &mut TestRunner,
312    state: &impl DictionaryRead,
313    senders: Option<&SenderFilters>,
314) -> Option<Address> {
315    if let Some(senders) = senders {
316        if !senders.targeted.is_empty() {
317            // Pick from targeted senders
318            let index = test_runner.rng().random_range(0..senders.targeted.len());
319            let addr = senders.targeted[index];
320            return (addr != current).then_some(addr);
321        }
322
323        // Pick from dictionary state values, excluding addresses in the exclusion list
324        state.with_dictionary(|dict| {
325            let values = dict.values();
326            if values.is_empty() {
327                return None;
328            }
329
330            // Try a few times to find a non-excluded address
331            for _ in 0..10 {
332                let index = test_runner.rng().random_range(0..values.len());
333                let addr = Address::from_word(values[index]);
334                if addr != current && !senders.excluded.contains(&addr) {
335                    return Some(addr);
336                }
337            }
338            None
339        })
340    } else {
341        // No sender filters, just pick from dictionary state values
342        state.with_dictionary(|dict| {
343            let values = dict.values();
344            if values.is_empty() {
345                None
346            } else {
347                let index = test_runner.rng().random_range(0..values.len());
348                let addr = Address::from_word(values[index]);
349                (addr != current).then_some(addr)
350            }
351        })
352    }
353}
354
355/// Mutates the current value of the given parameter type and value.
356pub(crate) fn mutate_param_value(
357    param: &DynSolType,
358    value: DynSolValue,
359    test_runner: &mut TestRunner,
360    state: &impl DictionaryRead,
361) -> DynSolValue {
362    mutate_param_value_inner(param, value, test_runner, state, None)
363}
364
365fn mutate_param_value_inner(
366    param: &DynSolType,
367    value: DynSolValue,
368    test_runner: &mut TestRunner,
369    state: &impl DictionaryRead,
370    senders: Option<&SenderFilters>,
371) -> DynSolValue {
372    let new_value = |param: &DynSolType, test_runner: &mut TestRunner| {
373        fuzz_param_from_state(param, state)
374            .new_tree(test_runner)
375            .expect("Could not generate case")
376            .current()
377    };
378
379    match value {
380        DynSolValue::Bool(val) => {
381            // flip boolean value
382            trace!(target: "mutator", "Bool flip {val}");
383            Some(DynSolValue::Bool(!val))
384        }
385        DynSolValue::Uint(val, size) => match test_runner.rng().random_range(0..=6) {
386            0 => U256::increment_decrement(val, size, test_runner),
387            1 => U256::flip_random_bit(val, size, test_runner),
388            2 => U256::mutate_interesting_byte(val, size, test_runner),
389            3 => U256::mutate_interesting_word(val, size, test_runner),
390            4 => U256::mutate_interesting_dword(val, size, test_runner),
391            5 => U256::mutate_with_gaussian_noise(val, size, test_runner),
392            6 => None,
393            _ => unreachable!(),
394        }
395        .map(|v| DynSolValue::Uint(v, size)),
396        DynSolValue::Int(val, size) => match test_runner.rng().random_range(0..=6) {
397            0 => I256::increment_decrement(val, size, test_runner),
398            1 => I256::flip_random_bit(val, size, test_runner),
399            2 => I256::mutate_interesting_byte(val, size, test_runner),
400            3 => I256::mutate_interesting_word(val, size, test_runner),
401            4 => I256::mutate_interesting_dword(val, size, test_runner),
402            5 => I256::mutate_with_gaussian_noise(val, size, test_runner),
403            6 => None,
404            _ => unreachable!(),
405        }
406        .map(|v| DynSolValue::Int(v, size)),
407        DynSolValue::Address(val) => match test_runner.rng().random_range(0..=5) {
408            0 => Address::flip_random_bit(val, 20, test_runner),
409            1 => Address::mutate_interesting_byte(val, 20, test_runner),
410            2 => Address::mutate_interesting_word(val, 20, test_runner),
411            3 => Address::mutate_interesting_dword(val, 20, test_runner),
412            // Replace with a random address from targeted senders or dictionary.
413            4 => select_random_address(val, test_runner, state, senders),
414            5 => None,
415            _ => unreachable!(),
416        }
417        .map(DynSolValue::Address),
418        DynSolValue::Array(mut values) => {
419            if let DynSolType::Array(param_type) = param
420                && !values.is_empty()
421            {
422                match test_runner.rng().random_range(0..=2) {
423                    // Decrease array size by removing a random element.
424                    0 => {
425                        values.remove(test_runner.rng().random_range(0..values.len()));
426                    }
427                    // Increase array size.
428                    1 => values.push(new_value(param_type, test_runner)),
429                    // Mutate random array element.
430                    2 => mutate_random_array_value(
431                        &mut values,
432                        param_type,
433                        test_runner,
434                        state,
435                        senders,
436                    ),
437                    _ => unreachable!(),
438                }
439                Some(DynSolValue::Array(values))
440            } else {
441                None
442            }
443        }
444        DynSolValue::FixedArray(mut values) => {
445            if let DynSolType::FixedArray(param_type, _size) = param
446                && !values.is_empty()
447            {
448                mutate_random_array_value(&mut values, param_type, test_runner, state, senders);
449                Some(DynSolValue::FixedArray(values))
450            } else {
451                None
452            }
453        }
454        DynSolValue::FixedBytes(word, size) => match test_runner.rng().random_range(0..=4) {
455            0 => Word::flip_random_bit(word, size, test_runner),
456            1 => Word::mutate_interesting_byte(word, size, test_runner),
457            2 => Word::mutate_interesting_word(word, size, test_runner),
458            3 => Word::mutate_interesting_dword(word, size, test_runner),
459            4 => None,
460            _ => unreachable!(),
461        }
462        .map(|word| DynSolValue::FixedBytes(word, size)),
463        DynSolValue::CustomStruct { name, prop_names, tuple: mut values } => {
464            if let DynSolType::CustomStruct { name: _, prop_names: _, tuple: tuple_types }
465            | DynSolType::Tuple(tuple_types) = param
466                && !values.is_empty()
467            {
468                // Mutate random struct element.
469                mutate_random_tuple_value(&mut values, tuple_types, test_runner, state, senders);
470                Some(DynSolValue::CustomStruct { name, prop_names, tuple: values })
471            } else {
472                None
473            }
474        }
475        DynSolValue::Tuple(mut values) => {
476            if let DynSolType::Tuple(tuple_types) = param
477                && !values.is_empty()
478            {
479                // Mutate random tuple element.
480                mutate_random_tuple_value(&mut values, tuple_types, test_runner, state, senders);
481                Some(DynSolValue::Tuple(values))
482            } else {
483                None
484            }
485        }
486        _ => None,
487    }
488    .unwrap_or_else(|| new_value(param, test_runner))
489}
490
491/// Mutates random value from given tuples.
492fn mutate_random_tuple_value(
493    tuple_values: &mut [DynSolValue],
494    tuple_types: &[DynSolType],
495    test_runner: &mut TestRunner,
496    state: &impl DictionaryRead,
497    senders: Option<&SenderFilters>,
498) {
499    let id = test_runner.rng().random_range(0..tuple_values.len());
500    let param_type = &tuple_types[id];
501    let old_val = replace(&mut tuple_values[id], DynSolValue::Bool(false));
502    let new_val = mutate_param_value_inner(param_type, old_val, test_runner, state, senders);
503    tuple_values[id] = new_val;
504}
505
506/// Mutates random value from given array.
507fn mutate_random_array_value(
508    array_values: &mut [DynSolValue],
509    element_type: &DynSolType,
510    test_runner: &mut TestRunner,
511    state: &impl DictionaryRead,
512    senders: Option<&SenderFilters>,
513) {
514    let elem = array_values.choose_mut(&mut test_runner.rng()).unwrap();
515    let old_val = replace(elem, DynSolValue::Bool(false));
516    let new_val = mutate_param_value_inner(element_type, old_val, test_runner, state, senders);
517    *elem = new_val;
518}
519
520/// Returns a proptest strategy for generating random msg.value for payable functions.
521///
522/// Most calls carry no value. The configured non-zero percent delegates to [`UintStrategy`],
523/// which biases toward edge cases (around 0 / max) and dictionary fixtures, with
524/// random fallback. Over-budget values are clamped to sender balance at execute time.
525pub fn fuzz_msg_value(payable_value_weight: u32) -> BoxedStrategy<Option<U256>> {
526    match payable_value_weight.min(100) {
527        0 => proptest::strategy::Just(None).boxed(),
528        100 => UintStrategy::new(256, None).prop_map(Some).boxed(),
529        payable_value_weight => proptest::prop_oneof![
530            100 - payable_value_weight => proptest::strategy::Just(None),
531            payable_value_weight       => UintStrategy::new(256, None).prop_map(Some),
532        ]
533        .boxed(),
534    }
535}
536
537/// Generates a msg.value for payable functions using `TestRunner`'s RNG (corpus mutation path).
538///
539/// Mirrors [`fuzz_msg_value`] by sampling from [`UintStrategy`]. The configured mutation gate is
540/// applied at the call site in `corpus.rs`. Over-budget values are clamped to sender
541/// balance at execute time.
542pub fn generate_msg_value(test_runner: &mut TestRunner) -> U256 {
543    UintStrategy::new(256, None)
544        .new_tree(test_runner)
545        .expect("UintStrategy::new_tree is infallible")
546        .current()
547}
548
549#[cfg(test)]
550mod tests {
551    use crate::{
552        FuzzFixtures,
553        strategies::{EvmFuzzState, fuzz_calldata, fuzz_calldata_from_state},
554    };
555    use alloy_dyn_abi::{DynSolType, DynSolValue};
556    use alloy_primitives::{B256, U256};
557    use foundry_common::abi::get_func;
558    use foundry_config::FuzzDictionaryConfig;
559    use proptest::{
560        strategy::{Strategy, ValueTree},
561        test_runner::TestRunner,
562    };
563    use revm::database::InMemoryDB;
564    use std::collections::HashSet;
565
566    #[test]
567    fn payable_value_weight_controls_non_zero_msg_value() {
568        use super::fuzz_msg_value;
569
570        let cfg = proptest::test_runner::Config { failure_persistence: None, ..Default::default() };
571        let mut runner = proptest::test_runner::TestRunner::new(cfg);
572
573        for _ in 0..32 {
574            assert!(fuzz_msg_value(0).new_tree(&mut runner).unwrap().current().is_none());
575            assert!(fuzz_msg_value(100).new_tree(&mut runner).unwrap().current().is_some());
576            assert!(fuzz_msg_value(250).new_tree(&mut runner).unwrap().current().is_some());
577        }
578    }
579
580    #[test]
581    fn can_fuzz_array() {
582        let f = "testArray(uint64[2] calldata values)";
583        let func = get_func(f).unwrap();
584        let state = EvmFuzzState::test();
585        let strategy = proptest::prop_oneof![
586            60 => fuzz_calldata(func.clone(), &FuzzFixtures::default()),
587            40 => fuzz_calldata_from_state(func, &state, &FuzzFixtures::default()),
588        ];
589        let cfg = proptest::test_runner::Config { failure_persistence: None, ..Default::default() };
590        let mut runner = proptest::test_runner::TestRunner::new(cfg);
591        let _ = runner.run(&strategy, |_| Ok(()));
592    }
593
594    #[test]
595    fn can_fuzz_from_zero_capacity_dictionary() {
596        let state = EvmFuzzState::new(
597            &[],
598            &InMemoryDB::default(),
599            FuzzDictionaryConfig { max_fuzz_dictionary_values: 0, ..Default::default() },
600            None,
601        );
602        let strategy = super::fuzz_param_from_state(&DynSolType::Uint(256), &state);
603        let mut runner = TestRunner::default();
604
605        assert_eq!(
606            strategy.new_tree(&mut runner).unwrap().current(),
607            DynSolValue::Uint(U256::ZERO, 256)
608        );
609    }
610
611    #[test]
612    fn string_fixtures_are_emitted_verbatim() {
613        let fixture = DynSolValue::String("  padded fixture  \0".to_string());
614        let strategy = super::fuzz_param_with_fixtures(
615            &DynSolType::String,
616            Some(std::slice::from_ref(&fixture)),
617            "value",
618        );
619        let mut runner = TestRunner::deterministic();
620
621        let emitted =
622            (0..1000).any(|_| strategy.new_tree(&mut runner).unwrap().current() == fixture);
623
624        assert!(emitted, "string fixture was never emitted verbatim");
625    }
626
627    #[test]
628    fn can_fuzz_string_and_bytes_with_ast_literals_and_hashes() {
629        use super::fuzz_param_from_state;
630        use crate::strategies::LiteralMaps;
631        use alloy_dyn_abi::DynSolType;
632        use alloy_primitives::keccak256;
633        use proptest::strategy::Strategy;
634
635        // Seed dict with string values and their hashes --> mimic `CheatcodeAnalysis` behavior.
636        let mut literals = LiteralMaps::default();
637        literals.strings.insert("hello".to_string());
638        literals.strings.insert("world".to_string());
639        literals.words.entry(DynSolType::FixedBytes(32)).or_default().insert(keccak256("hello"));
640        literals.words.entry(DynSolType::FixedBytes(32)).or_default().insert(keccak256("world"));
641
642        let mut state = EvmFuzzState::test();
643        state.seed_literals(literals);
644
645        let cfg = proptest::test_runner::Config { failure_persistence: None, ..Default::default() };
646        let mut runner = proptest::test_runner::TestRunner::new(cfg);
647
648        // Verify strategies generates the seeded AST literals
649        let mut generated_bytes = HashSet::new();
650        let mut generated_hashes = HashSet::new();
651        let mut generated_strings = HashSet::new();
652        let bytes_strategy = fuzz_param_from_state(&DynSolType::Bytes, &state);
653        let string_strategy = fuzz_param_from_state(&DynSolType::String, &state);
654        let bytes32_strategy = fuzz_param_from_state(&DynSolType::FixedBytes(32), &state);
655
656        for _ in 0..256 {
657            let tree = bytes_strategy.new_tree(&mut runner).unwrap();
658            if let Some(bytes) = tree.current().as_bytes()
659                && let Ok(s) = std::str::from_utf8(bytes)
660            {
661                generated_bytes.insert(s.to_string());
662            }
663
664            let tree = string_strategy.new_tree(&mut runner).unwrap();
665            if let Some(s) = tree.current().as_str() {
666                generated_strings.insert(s.to_string());
667            }
668
669            let tree = bytes32_strategy.new_tree(&mut runner).unwrap();
670            if let Some((bytes, size)) = tree.current().as_fixed_bytes()
671                && size == 32
672            {
673                generated_hashes.insert(B256::from_slice(bytes));
674            }
675        }
676
677        assert!(generated_bytes.contains("hello"));
678        assert!(generated_bytes.contains("world"));
679        assert!(generated_strings.contains("hello"));
680        assert!(generated_strings.contains("world"));
681        assert!(generated_hashes.contains(&keccak256("hello")));
682        assert!(generated_hashes.contains(&keccak256("world")));
683    }
684
685    #[test]
686    fn mutate_address_can_select_from_dictionary() {
687        use super::mutate_param_value;
688        use alloy_dyn_abi::{DynSolType, DynSolValue};
689        use alloy_primitives::Address;
690
691        let mut state = EvmFuzzState::test();
692
693        // Add addresses to dictionary via state values.
694        let addr1 = Address::repeat_byte(0x11);
695        let addr2 = Address::repeat_byte(0x22);
696        let addr3 = Address::repeat_byte(0x33);
697        state.collect_values([addr1.into_word(), addr2.into_word(), addr3.into_word()]);
698
699        let cfg = proptest::test_runner::Config { failure_persistence: None, ..Default::default() };
700        let mut runner = proptest::test_runner::TestRunner::new(cfg);
701
702        // Mutate an address many times and verify we can get addresses from the dictionary.
703        let original = Address::repeat_byte(0xff);
704        let mut got_addr1 = false;
705        let mut got_addr2 = false;
706        let mut got_addr3 = false;
707
708        for _ in 0..1000 {
709            let mutated = mutate_param_value(
710                &DynSolType::Address,
711                DynSolValue::Address(original),
712                &mut runner,
713                &state,
714            );
715            if let DynSolValue::Address(addr) = mutated {
716                if addr == addr1 {
717                    got_addr1 = true;
718                }
719                if addr == addr2 {
720                    got_addr2 = true;
721                }
722                if addr == addr3 {
723                    got_addr3 = true;
724                }
725            }
726            if got_addr1 && got_addr2 && got_addr3 {
727                break;
728            }
729        }
730
731        // We should have seen at least one dictionary address in 1000 iterations.
732        assert!(
733            got_addr1 || got_addr2 || got_addr3,
734            "Address mutation should select addresses from dictionary"
735        );
736    }
737
738    #[test]
739    fn mutate_address_prefers_targeted_senders() {
740        use super::select_random_address;
741        use crate::invariant::SenderFilters;
742        use alloy_primitives::Address;
743
744        let mut state = EvmFuzzState::test();
745
746        // Add addresses to dictionary (these should NOT be selected when targeted is set).
747        let dict_addr = Address::repeat_byte(0xdd);
748        state.collect_values([dict_addr.into_word()]);
749
750        // Set up targeted senders.
751        let targeted1 = Address::repeat_byte(0x11);
752        let targeted2 = Address::repeat_byte(0x22);
753        let senders = SenderFilters::new(vec![targeted1, targeted2], vec![]);
754
755        let cfg = proptest::test_runner::Config { failure_persistence: None, ..Default::default() };
756        let mut runner = proptest::test_runner::TestRunner::new(cfg);
757
758        // Call select_random_address directly to verify it uses targeted senders.
759        let original = Address::repeat_byte(0xff);
760        let mut got_targeted1 = false;
761        let mut got_targeted2 = false;
762        let mut got_dict = false;
763
764        for _ in 0..100 {
765            if let Some(addr) = select_random_address(original, &mut runner, &state, Some(&senders))
766            {
767                if addr == targeted1 {
768                    got_targeted1 = true;
769                }
770                if addr == targeted2 {
771                    got_targeted2 = true;
772                }
773                if addr == dict_addr {
774                    got_dict = true;
775                }
776            }
777        }
778
779        // Should see targeted addresses, never dictionary address.
780        assert!(
781            got_targeted1 || got_targeted2,
782            "select_random_address should select from targeted senders"
783        );
784        assert!(
785            !got_dict,
786            "select_random_address should not select from dictionary when targeted senders are set"
787        );
788    }
789
790    #[test]
791    fn mutate_address_respects_excluded_senders() {
792        use super::select_random_address;
793        use crate::invariant::SenderFilters;
794        use alloy_primitives::Address;
795
796        let mut state = EvmFuzzState::test();
797
798        // Add addresses to dictionary.
799        let addr1 = Address::repeat_byte(0x11);
800        let addr2 = Address::repeat_byte(0x22);
801        let excluded_addr = Address::repeat_byte(0xee);
802        state.collect_values([addr1.into_word(), addr2.into_word(), excluded_addr.into_word()]);
803
804        // Exclude one address.
805        let senders = SenderFilters::new(vec![], vec![excluded_addr]);
806
807        let cfg = proptest::test_runner::Config { failure_persistence: None, ..Default::default() };
808        let mut runner = proptest::test_runner::TestRunner::new(cfg);
809
810        // Call select_random_address directly to verify it respects excluded senders.
811        let original = Address::repeat_byte(0xff);
812        let mut got_excluded = false;
813        let mut got_valid = false;
814
815        for _ in 0..100 {
816            if let Some(addr) = select_random_address(original, &mut runner, &state, Some(&senders))
817            {
818                if addr == excluded_addr {
819                    got_excluded = true;
820                    break;
821                }
822                if addr == addr1 || addr == addr2 {
823                    got_valid = true;
824                }
825            }
826        }
827
828        assert!(!got_excluded, "select_random_address should not select excluded addresses");
829        assert!(got_valid, "select_random_address should select valid (non-excluded) addresses");
830    }
831}