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