Skip to main content

foundry_evm_fuzz/
sequence.rs

1//! Pure transaction-sequence generation and mutation primitives.
2
3use crate::{
4    BasicTxDetails, FuzzFixtures,
5    invariant::FuzzRunIdentifiedContracts,
6    strategies::{
7        FuzzState, TxGenerator, constrain_enum_value, generate_msg_value, mutate_param_value,
8    },
9};
10use alloy_dyn_abi::JsonAbiExt;
11use alloy_json_abi::Function;
12use alloy_primitives::{U256, map::HashSet};
13use eyre::{Result, eyre};
14use foundry_config::{FuzzCorpusConfig, FuzzCorpusMutationWeights};
15use proptest::test_runner::TestRunner;
16use rand::{
17    Rng,
18    distr::{Distribution, weighted::WeightedIndex},
19};
20
21/// A neutral borrowed view of one corpus entry.
22#[derive(Clone, Copy)]
23pub struct CorpusEntryView<'a> {
24    transactions: &'a [BasicTxDetails],
25    comparisons: &'a [Vec<ComparisonHint>],
26}
27
28impl<'a> CorpusEntryView<'a> {
29    pub fn new(
30        transactions: &'a [BasicTxDetails],
31        comparisons: &'a [Vec<ComparisonHint>],
32    ) -> Result<Self> {
33        if transactions.is_empty() {
34            return Err(eyre!("corpus entry has no transactions"));
35        }
36        if comparisons.len() > transactions.len() {
37            return Err(eyre!("corpus entry has more comparison sets than transactions"));
38        }
39        Ok(Self { transactions, comparisons })
40    }
41}
42
43#[derive(Clone)]
44enum SequenceMode {
45    Stateless(Function),
46    Invariant(FuzzRunIdentifiedContracts),
47}
48
49/// Generates initial sequences and their lazy continuations.
50#[derive(Clone)]
51pub struct SequenceGenerator {
52    tx: TxGenerator,
53    state: FuzzState,
54    fixtures: FuzzFixtures,
55    mode: SequenceMode,
56    weights: FuzzCorpusMutationWeights,
57    mutations: WeightedIndex<u32>,
58    arg_mutations: Option<WeightedIndex<u32>>,
59    fresh_weight: u32,
60    payable_weight: u32,
61    has_corpus_dir: bool,
62}
63
64/// An initial sequence and the generator used to lazily continue it.
65pub struct SequencePlan {
66    initial: InitialSequence,
67    tx: TxGenerator,
68    fresh_weight: u32,
69    has_corpus_dir: bool,
70    stateless: bool,
71    source: Option<usize>,
72}
73
74enum InitialSequence {
75    Single(BasicTxDetails),
76    Multiple(Vec<BasicTxDetails>),
77}
78
79impl InitialSequence {
80    pub fn into_first(self) -> BasicTxDetails {
81        match self {
82            Self::Single(tx) => tx,
83            Self::Multiple(mut txs) => txs.remove(0),
84        }
85    }
86
87    pub fn as_slice(&self) -> &[BasicTxDetails] {
88        match self {
89            Self::Single(tx) => std::slice::from_ref(tx),
90            Self::Multiple(txs) => txs,
91        }
92    }
93}
94
95impl SequencePlan {
96    pub fn initial(&self) -> &[BasicTxDetails] {
97        self.initial.as_slice()
98    }
99    pub fn into_first(self) -> BasicTxDetails {
100        self.initial.into_first()
101    }
102    pub const fn source(&self) -> Option<usize> {
103        self.source
104    }
105    pub fn next(
106        &self,
107        runner: &mut TestRunner,
108        discarded: bool,
109        depth: usize,
110    ) -> Result<BasicTxDetails> {
111        if self.stateless {
112            return Err(eyre!("stateless sequence is limited to one transaction"));
113        }
114        if !self.has_corpus_dir || discarded {
115            return self.tx.next_tx(runner);
116        }
117        let fresh = self.fresh_weight > 0 && runner.rng().random_ratio(self.fresh_weight, 100);
118        if depth >= self.initial.as_slice().len() || fresh {
119            self.tx.next_tx(runner)
120        } else {
121            Ok(self.initial.as_slice()[depth].clone())
122        }
123    }
124}
125
126#[derive(Clone, Copy)]
127enum MutationType {
128    Splice,
129    Repeat,
130    Interleave,
131    Prefix,
132    Suffix,
133    Abi,
134    Cmp,
135}
136
137impl SequenceGenerator {
138    pub fn stateless(
139        tx: TxGenerator,
140        state: FuzzState,
141        function: Function,
142        config: &FuzzCorpusConfig,
143    ) -> Result<Self> {
144        Self::stateless_with_fixtures(tx, state, FuzzFixtures::default(), function, config)
145    }
146    pub fn stateless_with_fixtures(
147        tx: TxGenerator,
148        state: FuzzState,
149        fixtures: FuzzFixtures,
150        function: Function,
151        config: &FuzzCorpusConfig,
152    ) -> Result<Self> {
153        Self::new(tx, state, fixtures, SequenceMode::Stateless(function), config)
154    }
155    pub fn invariant(
156        tx: TxGenerator,
157        state: FuzzState,
158        targets: FuzzRunIdentifiedContracts,
159        config: &FuzzCorpusConfig,
160    ) -> Result<Self> {
161        Self::invariant_with_fixtures(tx, state, FuzzFixtures::default(), targets, config)
162    }
163    pub fn invariant_with_fixtures(
164        tx: TxGenerator,
165        state: FuzzState,
166        fixtures: FuzzFixtures,
167        targets: FuzzRunIdentifiedContracts,
168        config: &FuzzCorpusConfig,
169    ) -> Result<Self> {
170        Self::new(tx, state, fixtures, SequenceMode::Invariant(targets), config)
171    }
172    fn new(
173        tx: TxGenerator,
174        state: FuzzState,
175        fixtures: FuzzFixtures,
176        mode: SequenceMode,
177        config: &FuzzCorpusConfig,
178    ) -> Result<Self> {
179        let weights = config.mutation_weights.effective();
180        if weights.total() > u64::from(u32::MAX) {
181            return Err(eyre!(
182                "effective mutation weights sum to {}, which exceeds the maximum supported total {}",
183                weights.total(),
184                u32::MAX
185            ));
186        }
187        let all = [
188            weights.mutation_weight_splice,
189            weights.mutation_weight_repeat,
190            weights.mutation_weight_interleave,
191            weights.mutation_weight_prefix,
192            weights.mutation_weight_suffix,
193            weights.mutation_weight_abi,
194            weights.mutation_weight_cmp,
195        ];
196        let mutations =
197            WeightedIndex::new(all).map_err(|e| eyre!("invalid corpus mutation weights: {e}"))?;
198        let arg_mutations = if weights.mutation_weight_abi == 0 && weights.mutation_weight_cmp == 0
199        {
200            None
201        } else {
202            Some(
203                WeightedIndex::new([weights.mutation_weight_abi, weights.mutation_weight_cmp])
204                    .map_err(|e| eyre!("invalid argument mutation weights: {e}"))?,
205            )
206        };
207        Ok(Self {
208            tx,
209            state,
210            fixtures,
211            mode,
212            weights,
213            mutations,
214            arg_mutations,
215            fresh_weight: config.corpus_random_sequence_weight.min(100),
216            payable_weight: config.payable_value_weight,
217            has_corpus_dir: config.corpus_dir.is_some(),
218        })
219    }
220
221    pub fn start<'a, F>(
222        &self,
223        runner: &mut TestRunner,
224        corpus_len: usize,
225        mut entry_at: F,
226        coverage: bool,
227    ) -> Result<SequencePlan>
228    where
229        F: FnMut(usize) -> Result<CorpusEntryView<'a>>,
230    {
231        let (initial, source) = match &self.mode {
232            SequenceMode::Stateless(function) => {
233                self.start_stateless(runner, corpus_len, &mut entry_at, coverage, function)?
234            }
235            SequenceMode::Invariant(targets) => {
236                self.start_invariant(runner, corpus_len, &mut entry_at, coverage, targets)?
237            }
238        };
239        Ok(SequencePlan {
240            initial,
241            tx: self.tx.clone(),
242            fresh_weight: self.fresh_weight,
243            has_corpus_dir: self.has_corpus_dir,
244            stateless: matches!(self.mode, SequenceMode::Stateless(_)),
245            source,
246        })
247    }
248
249    fn start_stateless<'a>(
250        &self,
251        runner: &mut TestRunner,
252        corpus_len: usize,
253        entry_at: &mut impl FnMut(usize) -> Result<CorpusEntryView<'a>>,
254        coverage: bool,
255        function: &Function,
256    ) -> Result<(InitialSequence, Option<usize>)> {
257        if !coverage
258            || corpus_len == 0
259            || (self.fresh_weight > 0 && runner.rng().random_ratio(self.fresh_weight, 100))
260        {
261            return Ok((InitialSequence::Single(self.tx.next_tx(runner)?), None));
262        }
263        let index = runner.rng().random_range(0..corpus_len);
264        let entry = entry_at(index)?;
265        let mut tx = entry.transactions[0].clone();
266        let hints = entry.comparisons.first().map_or(&[][..], Vec::as_slice);
267        match self.arg_mutations.as_ref().map(|d| d.sample(runner.rng()) == 1) {
268            Some(true)
269                if !SequenceMutator::cmp_mutate(
270                    &mut tx,
271                    function,
272                    hints,
273                    runner,
274                    &self.fixtures,
275                )? && self.weights.mutation_weight_abi > 0
276                    && !function.inputs.is_empty() =>
277            {
278                SequenceMutator::abi_mutate(
279                    &mut tx,
280                    function,
281                    runner,
282                    &self.state,
283                    &self.fixtures,
284                    self.payable_weight,
285                )?
286            }
287            Some(true) => {}
288            Some(false) if self.weights.mutation_weight_abi > 0 && !function.inputs.is_empty() => {
289                SequenceMutator::abi_mutate(
290                    &mut tx,
291                    function,
292                    runner,
293                    &self.state,
294                    &self.fixtures,
295                    self.payable_weight,
296                )?
297            }
298            Some(false) if self.weights.mutation_weight_cmp > 0 => {
299                let _ =
300                    SequenceMutator::cmp_mutate(&mut tx, function, hints, runner, &self.fixtures)?;
301            }
302            None => return Ok((InitialSequence::Single(self.tx.next_tx(runner)?), None)),
303            _ => {}
304        }
305        Ok((InitialSequence::Single(tx), Some(index)))
306    }
307
308    fn start_invariant<'a>(
309        &self,
310        runner: &mut TestRunner,
311        corpus_len: usize,
312        entry_at: &mut impl FnMut(usize) -> Result<CorpusEntryView<'a>>,
313        coverage: bool,
314        targets: &FuzzRunIdentifiedContracts,
315    ) -> Result<(InitialSequence, Option<usize>)> {
316        if !coverage || corpus_len == 0 {
317            return Ok((InitialSequence::Multiple(vec![self.tx.next_tx(runner)?]), None));
318        }
319        let kind = match self.mutations.sample(runner.rng()) {
320            0 => MutationType::Splice,
321            1 => MutationType::Repeat,
322            2 => MutationType::Interleave,
323            3 => MutationType::Prefix,
324            4 => MutationType::Suffix,
325            5 => MutationType::Abi,
326            _ => MutationType::Cmp,
327        };
328        let a = runner.rng().random_range(0..corpus_len);
329        let b = runner.rng().random_range(0..corpus_len);
330        let primary = entry_at(a)?;
331        let secondary = entry_at(b)?;
332        let (mut seq, source) = match kind {
333            MutationType::Splice => {
334                (SequenceMutator::splice(primary.transactions, secondary.transactions, runner), a)
335            }
336            MutationType::Interleave => (
337                SequenceMutator::interleave(primary.transactions, secondary.transactions, runner),
338                a,
339            ),
340            MutationType::Repeat => {
341                let i = if runner.rng().random() { a } else { b };
342                let entry = if i == a { primary } else { secondary };
343                (SequenceMutator::repeat(entry.transactions, runner), i)
344            }
345            MutationType::Prefix | MutationType::Suffix => {
346                let i = if runner.rng().random() { a } else { b };
347                let base = if i == a { primary.transactions } else { secondary.transactions };
348                let len = if matches!(kind, MutationType::Prefix) {
349                    runner.rng().random_range(0..=base.len())
350                } else {
351                    runner.rng().random_range(0..base.len())
352                };
353                let mut r = Vec::with_capacity(len);
354                for _ in 0..len {
355                    r.push(self.tx.next_tx(runner)?)
356                }
357                (
358                    if matches!(kind, MutationType::Prefix) {
359                        SequenceMutator::prefix(base, r)
360                    } else {
361                        SequenceMutator::suffix(base, r)
362                    },
363                    i,
364                )
365            }
366            MutationType::Abi | MutationType::Cmp => {
367                let i = if runner.rng().random() { a } else { b };
368                let entry = if i == a { primary } else { secondary };
369                let mut seq = entry.transactions.to_vec();
370                let fallback = runner.rng().random_range(0..seq.len());
371                if matches!(kind, MutationType::Abi) {
372                    let tx = &mut seq[fallback];
373                    if let (_, Some(f)) = targets.targets().fuzzed_artifacts(tx)
374                        && !f.inputs.is_empty()
375                    {
376                        SequenceMutator::abi_mutate(
377                            tx,
378                            f,
379                            runner,
380                            &self.state,
381                            &self.fixtures,
382                            self.payable_weight,
383                        )?;
384                    }
385                } else {
386                    let candidates =
387                        entry.comparisons.iter().enumerate().filter(|(_, h)| !h.is_empty());
388                    let count = candidates.clone().count();
389                    let mut mutated = false;
390                    if count > 0 {
391                        let start = runner.rng().random_range(0..count);
392                        for (idx, h) in candidates.cycle().skip(start).take(count) {
393                            let tx = &mut seq[idx];
394                            if let (_, Some(f)) = targets.targets().fuzzed_artifacts(tx) {
395                                mutated =
396                                    SequenceMutator::cmp_mutate(tx, f, h, runner, &self.fixtures)?;
397                                if mutated {
398                                    break;
399                                }
400                            }
401                        }
402                    }
403                    if !mutated && self.weights.mutation_weight_abi > 0 {
404                        let tx = &mut seq[fallback];
405                        if let (_, Some(f)) = targets.targets().fuzzed_artifacts(tx)
406                            && !f.inputs.is_empty()
407                        {
408                            SequenceMutator::abi_mutate(
409                                tx,
410                                f,
411                                runner,
412                                &self.state,
413                                &self.fixtures,
414                                self.payable_weight,
415                            )?
416                        }
417                    }
418                }
419                (seq, i)
420            }
421        };
422        if seq.is_empty() {
423            seq.push(self.tx.next_tx(runner)?)
424        }
425        Ok((InitialSequence::Multiple(seq), Some(source)))
426    }
427}
428
429/// An EVM comparison observed while executing an input.
430#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
431pub struct ComparisonHint {
432    pub lhs: U256,
433    pub rhs: U256,
434}
435
436impl ComparisonHint {
437    /// Collects the distinct `hints` that a cmp mutation can apply to `calldata`, in first-seen
438    /// order.
439    ///
440    /// Cmp mutations only rewrite the calldata stored with the hints, so other hints can never
441    /// produce a mutation.
442    pub fn applicable(calldata: &[u8], hints: impl IntoIterator<Item = Self>) -> Vec<Self> {
443        let mut seen = HashSet::<Self>::default();
444        hints.into_iter().filter(|hint| seen.insert(*hint) && hint.applies_to(calldata)).collect()
445    }
446
447    /// Returns whether a cmp mutation can replace one of this comparison's operands in
448    /// `calldata`.
449    pub fn applies_to(&self, calldata: &[u8]) -> bool {
450        let lhs = self.lhs.to_be_bytes::<32>();
451        let rhs = self.rhs.to_be_bytes::<32>();
452        CMP_WIDTHS.iter().any(|&width| {
453            let lhs = &lhs[32 - width..];
454            let rhs = &rhs[32 - width..];
455            lhs != rhs && (contains_operand(calldata, lhs) || contains_operand(calldata, rhs))
456        })
457    }
458}
459
460/// Pure mutations shared by stateless and invariant sequence producers.
461struct SequenceMutator;
462
463impl SequenceMutator {
464    fn splice(
465        first: &[BasicTxDetails],
466        second: &[BasicTxDetails],
467        runner: &mut TestRunner,
468    ) -> Vec<BasicTxDetails> {
469        let rng = runner.rng();
470        let start1 = rng.random_range(0..first.len());
471        let end1 = rng.random_range(start1..first.len());
472        let start2 = rng.random_range(0..second.len());
473        let end2 = rng.random_range(start2..second.len());
474        first[start1..=end1].iter().chain(&second[start2..=end2]).cloned().collect()
475    }
476
477    fn repeat(sequence: &[BasicTxDetails], runner: &mut TestRunner) -> Vec<BasicTxDetails> {
478        let rng = runner.rng();
479        let start = rng.random_range(0..sequence.len());
480        let end = rng.random_range(start..=sequence.len());
481        let repeated = sequence[rng.random_range(0..sequence.len())].clone();
482        let mut result = Vec::with_capacity(sequence.len());
483        result.extend_from_slice(&sequence[..start]);
484        result.extend((start..end).map(|_| repeated.clone()));
485        result.extend_from_slice(&sequence[end..]);
486        result
487    }
488
489    fn interleave(
490        first: &[BasicTxDetails],
491        second: &[BasicTxDetails],
492        runner: &mut TestRunner,
493    ) -> Vec<BasicTxDetails> {
494        first
495            .iter()
496            .zip(second)
497            .map(
498                |(first, second)| {
499                    if runner.rng().random() { first.clone() } else { second.clone() }
500                },
501            )
502            .collect()
503    }
504
505    fn prefix(
506        sequence: &[BasicTxDetails],
507        mut replacements: Vec<BasicTxDetails>,
508    ) -> Vec<BasicTxDetails> {
509        replacements.truncate(sequence.len());
510        let mut result = sequence.to_vec();
511        result[..replacements.len()].clone_from_slice(&replacements);
512        result
513    }
514
515    fn suffix(
516        sequence: &[BasicTxDetails],
517        mut replacements: Vec<BasicTxDetails>,
518    ) -> Vec<BasicTxDetails> {
519        replacements.truncate(sequence.len());
520        let mut result = sequence.to_vec();
521        let retained = result.len() - replacements.len();
522        result[retained..].clone_from_slice(&replacements);
523        result
524    }
525
526    /// Mutates ABI arguments while retaining transaction metadata and optionally changing value.
527    fn abi_mutate(
528        tx: &mut BasicTxDetails,
529        function: &Function,
530        runner: &mut TestRunner,
531        state: &FuzzState,
532        fixtures: &FuzzFixtures,
533        payable_value_weight: u32,
534    ) -> Result<()> {
535        if function.inputs.is_empty() || tx.call_details.calldata.len() < 4 {
536            return Ok(());
537        }
538        if function.state_mutability == alloy_json_abi::StateMutability::Payable
539            && runner.rng().random_ratio(payable_value_weight.min(100), 100)
540        {
541            tx.call_details.value = Some(generate_msg_value(runner));
542        }
543        let mut rounds = runner.rng().random_range(0..=function.inputs.len()).max(1);
544        let indices = if function.inputs.len() <= 1 {
545            vec![0]
546        } else {
547            (0..rounds).map(|_| runner.rng().random_range(0..function.inputs.len())).collect()
548        };
549        let mut inputs = function
550            .abi_decode_input(&tx.call_details.calldata[4..])
551            .map_err(|err| eyre!("failed to load previous inputs: {err}"))?;
552        while rounds > 0 {
553            let index = indices[rounds - 1];
554            inputs[index] = mutate_param_value(
555                &function.inputs[index].selector_type().parse()?,
556                inputs[index].clone(),
557                runner,
558                state,
559            );
560            rounds -= 1;
561        }
562        let inputs = inputs
563            .into_iter()
564            .zip(&function.inputs)
565            .map(|(value, input)| constrain_enum_value(value, input, fixtures))
566            .collect::<Vec<_>>();
567        tx.call_details.calldata =
568            function.abi_encode_input(&inputs).map_err(|err| eyre!(err.to_string()))?.into();
569        Ok(())
570    }
571
572    fn cmp_mutate(
573        tx: &mut BasicTxDetails,
574        function: &Function,
575        hints: &[ComparisonHint],
576        runner: &mut TestRunner,
577        fixtures: &FuzzFixtures,
578    ) -> Result<bool> {
579        if hints.is_empty() || tx.call_details.calldata.len() <= 4 {
580            return Ok(false);
581        }
582        let start = runner.rng().random_range(0..hints.len());
583        for offset in 0..hints.len() {
584            if let Some(calldata) = cmp_mutated_calldata(
585                tx.call_details.calldata.as_ref(),
586                hints[(start + offset) % hints.len()],
587                runner,
588            ) && let Ok(inputs) = function.abi_decode_input(&calldata[4..])
589                && inputs
590                    .iter()
591                    .cloned()
592                    .zip(&function.inputs)
593                    .map(|(value, input)| constrain_enum_value(value, input, fixtures))
594                    .zip(&inputs)
595                    .all(|(constrained, input)| constrained == *input)
596            {
597                tx.call_details.calldata = calldata.into();
598                return Ok(true);
599            }
600        }
601        Ok(false)
602    }
603}
604
605/// Operand widths, in bytes, that cmp mutations try to replace.
606const CMP_WIDTHS: [usize; 6] = [32, 16, 8, 4, 2, 1];
607
608fn cmp_mutated_calldata(
609    calldata: &[u8],
610    hint: ComparisonHint,
611    runner: &mut TestRunner,
612) -> Option<Vec<u8>> {
613    let lhs = hint.lhs.to_be_bytes::<32>();
614    let rhs = hint.rhs.to_be_bytes::<32>();
615    let start = runner.rng().random_range(0..CMP_WIDTHS.len());
616    for offset in 0..CMP_WIDTHS.len() {
617        let width = CMP_WIDTHS[(start + offset) % CMP_WIDTHS.len()];
618        let lhs = &lhs[32 - width..];
619        let rhs = &rhs[32 - width..];
620        if lhs == rhs {
621            continue;
622        }
623        let pairs =
624            if runner.rng().random() { [(lhs, rhs), (rhs, lhs)] } else { [(rhs, lhs), (lhs, rhs)] };
625        for (pattern, replacement) in pairs {
626            if let Some(mutated) = replace_operand(calldata, pattern, replacement, runner) {
627                return Some(mutated);
628            }
629        }
630    }
631    None
632}
633
634/// Length of the function selector that cmp mutations never rewrite.
635const SELECTOR_LEN: usize = 4;
636
637/// Returns whether `pattern` can be searched for in `calldata` arguments.
638fn is_replaceable_operand(calldata: &[u8], pattern: &[u8]) -> bool {
639    !pattern.is_empty()
640        && calldata.len() >= SELECTOR_LEN + pattern.len()
641        && (pattern.len() == 32 || pattern.iter().any(|byte| *byte != 0))
642}
643
644/// Returns whether `pattern` occurs in `calldata` arguments.
645fn contains_operand(calldata: &[u8], pattern: &[u8]) -> bool {
646    is_replaceable_operand(calldata, pattern)
647        && calldata[SELECTOR_LEN..].windows(pattern.len()).any(|window| window == pattern)
648}
649
650fn replace_operand(
651    calldata: &[u8],
652    pattern: &[u8],
653    replacement: &[u8],
654    runner: &mut TestRunner,
655) -> Option<Vec<u8>> {
656    if pattern.len() != replacement.len() || !is_replaceable_operand(calldata, pattern) {
657        return None;
658    }
659    let search_len = calldata.len() - SELECTOR_LEN - pattern.len() + 1;
660    let start = runner.rng().random_range(0..search_len);
661    for offset in 0..search_len {
662        let index = SELECTOR_LEN + ((start + offset) % search_len);
663        if &calldata[index..index + pattern.len()] == pattern {
664            let mut mutated = calldata.to_vec();
665            mutated[index..index + replacement.len()].copy_from_slice(replacement);
666            return Some(mutated);
667        }
668    }
669    None
670}
671
672#[cfg(test)]
673mod tests {
674    use super::*;
675    use crate::{
676        CallDetails,
677        invariant::{TargetedContract, TargetedContracts},
678        strategies::EvmFuzzState,
679    };
680    use alloy_dyn_abi::DynSolValue;
681    use alloy_json_abi::JsonAbi;
682    use alloy_primitives::{Address, Bytes};
683    use foundry_config::FuzzDictionaryConfig;
684    use proptest::{prelude::Just, strategy::Strategy};
685    use revm::database::InMemoryDB;
686    use std::path::PathBuf;
687
688    fn sentinel(runner: &mut TestRunner) -> u64 {
689        runner.rng().random()
690    }
691
692    fn forced_weights(kind: usize) -> FuzzCorpusMutationWeights {
693        let mut weights = FuzzCorpusMutationWeights {
694            mutation_weight_splice: 0,
695            mutation_weight_repeat: 0,
696            mutation_weight_interleave: 0,
697            mutation_weight_prefix: 0,
698            mutation_weight_suffix: 0,
699            mutation_weight_abi: 0,
700            mutation_weight_cmp: 0,
701        };
702        match kind {
703            0 => weights.mutation_weight_splice = 1,
704            1 => weights.mutation_weight_repeat = 1,
705            2 => weights.mutation_weight_interleave = 1,
706            3 => weights.mutation_weight_prefix = 1,
707            4 => weights.mutation_weight_suffix = 1,
708            5 => weights.mutation_weight_abi = 1,
709            _ => weights.mutation_weight_cmp = 1,
710        }
711        weights
712    }
713
714    fn tx(sender: u8) -> BasicTxDetails {
715        BasicTxDetails {
716            warp: Some(U256::from(sender)),
717            roll: Some(U256::from(sender + 1)),
718            sender: Address::with_last_byte(sender),
719            call_details: CallDetails {
720                target: Address::with_last_byte(10),
721                calldata: Bytes::from(vec![sender]),
722                value: Some(U256::from(sender)),
723            },
724        }
725    }
726
727    fn state() -> FuzzState {
728        EvmFuzzState::new(&[], &InMemoryDB::default(), FuzzDictionaryConfig::default(), None)
729            .stateless_worker()
730    }
731
732    fn generator_tx(sender: u8) -> TxGenerator {
733        TxGenerator::from_strategy(Just(tx(sender)).boxed())
734    }
735
736    fn config() -> FuzzCorpusConfig {
737        FuzzCorpusConfig { corpus_dir: Some(PathBuf::from("corpus")), ..Default::default() }
738    }
739
740    #[test]
741    fn prefix_and_suffix_handle_sequence_edges() {
742        let sequence = vec![tx(1), tx(2), tx(3)];
743        assert_eq!(SequenceMutator::prefix(&sequence, Vec::new())[0].sender, sequence[0].sender);
744        assert_eq!(SequenceMutator::suffix(&sequence, Vec::new())[2].sender, sequence[2].sender);
745        assert_eq!(
746            SequenceMutator::prefix(&sequence, vec![tx(9), tx(8), tx(7)])[2].sender,
747            tx(7).sender
748        );
749        assert_eq!(SequenceMutator::suffix(&sequence, vec![tx(9)])[0].warp, sequence[0].warp);
750    }
751
752    #[test]
753    fn splice_retains_singleton_entries() {
754        let mut runner = TestRunner::deterministic();
755        let result = SequenceMutator::splice(&[tx(1)], &[tx(2)], &mut runner);
756
757        assert_eq!(
758            result.iter().map(|tx| tx.sender).collect::<Vec<_>>(),
759            [tx(1).sender, tx(2).sender]
760        );
761    }
762
763    #[test]
764    fn splice_can_select_final_transactions() {
765        let first = [tx(1), tx(2)];
766        let second = [tx(3), tx(4)];
767        let mut runner = TestRunner::deterministic();
768        let mut selected_first_final = false;
769        let mut selected_second_final = false;
770
771        for _ in 0..1000 {
772            let result = SequenceMutator::splice(&first, &second, &mut runner);
773            selected_first_final |= result.iter().any(|tx| tx.sender == first[1].sender);
774            selected_second_final |= result.iter().any(|tx| tx.sender == second[1].sender);
775        }
776
777        assert!(selected_first_final, "splice never selected the first entry's final transaction");
778        assert!(
779            selected_second_final,
780            "splice never selected the second entry's final transaction"
781        );
782    }
783
784    #[test]
785    fn repeat_can_replace_final_transaction() {
786        let sequence = [tx(1), tx(2)];
787        let mut runner = TestRunner::deterministic();
788        let mut replaced_final = false;
789
790        for _ in 0..1000 {
791            let result = SequenceMutator::repeat(&sequence, &mut runner);
792            replaced_final |= result[1].sender != sequence[1].sender;
793        }
794
795        assert!(replaced_final, "repeat never replaced the final transaction");
796    }
797
798    #[test]
799    fn cmp_mutation_replaces_operand_and_retains_metadata() {
800        let function = Function::parse("testCmp(uint256)").unwrap();
801        let mut input = tx(7);
802        input.call_details.calldata =
803            function.abi_encode_input(&[DynSolValue::Uint(U256::from(7), 256)]).unwrap().into();
804        let metadata = (input.warp, input.roll, input.sender, input.call_details.value);
805        let mut runner = TestRunner::default();
806
807        assert!(
808            SequenceMutator::cmp_mutate(
809                &mut input,
810                &function,
811                &[ComparisonHint { lhs: U256::from(7), rhs: U256::from(42) }],
812                &mut runner,
813                &FuzzFixtures::default(),
814            )
815            .unwrap()
816        );
817        let decoded = function.abi_decode_input(&input.call_details.calldata[4..]).unwrap();
818        assert_eq!(decoded[0].as_uint().unwrap().0, U256::from(42));
819        assert_eq!((input.warp, input.roll, input.sender, input.call_details.value), metadata);
820    }
821
822    #[test]
823    fn stateless_fresh_and_disabled_mutators_generate_one_transaction() {
824        let function = Function::parse("test(uint256)").unwrap();
825        let corpus_tx = tx(1);
826        let corpus = [CorpusEntryView::new(std::slice::from_ref(&corpus_tx), &[]).unwrap()];
827        for disable_mutators in [false, true] {
828            let mut config = config();
829            config.corpus_random_sequence_weight = if disable_mutators { 0 } else { 100 };
830            if disable_mutators {
831                config.mutation_weights.mutation_weight_abi = 0;
832                config.mutation_weights.mutation_weight_cmp = 0;
833            }
834            let generator =
835                SequenceGenerator::stateless(generator_tx(9), state(), function.clone(), &config)
836                    .unwrap();
837            let plan = generator
838                .start(&mut TestRunner::default(), corpus.len(), |i| Ok(corpus[i]), true)
839                .unwrap();
840            assert_eq!(plan.initial().len(), 1);
841            assert_eq!(plan.initial()[0].sender, tx(9).sender);
842            assert_eq!(plan.initial()[0].call_details.value, tx(9).call_details.value);
843            assert_eq!(plan.source(), None);
844        }
845    }
846
847    #[test]
848    fn sequence_plan_continues_corpus_or_generates_when_unavailable() {
849        let mut config = config();
850        config.corpus_random_sequence_weight = 0;
851        config.mutation_weights.mutation_weight_splice = 1;
852        config.mutation_weights.mutation_weight_repeat = 0;
853        config.mutation_weights.mutation_weight_interleave = 0;
854        config.mutation_weights.mutation_weight_prefix = 0;
855        config.mutation_weights.mutation_weight_suffix = 0;
856        config.mutation_weights.mutation_weight_abi = 0;
857        config.mutation_weights.mutation_weight_cmp = 0;
858        let targets = FuzzRunIdentifiedContracts::new(TargetedContracts::new(), false);
859        let generator =
860            SequenceGenerator::invariant(generator_tx(9), state(), targets, &config).unwrap();
861        let mut runner = TestRunner::default();
862        let plan = SequencePlan {
863            initial: InitialSequence::Multiple(vec![tx(1), tx(2)]),
864            tx: generator.tx,
865            fresh_weight: generator.fresh_weight,
866            has_corpus_dir: generator.has_corpus_dir,
867            stateless: false,
868            source: Some(0),
869        };
870
871        assert_eq!(plan.next(&mut runner, false, 1).unwrap().sender, tx(2).sender);
872        assert_eq!(plan.next(&mut runner, true, 1).unwrap().sender, tx(9).sender);
873        assert_eq!(plan.next(&mut runner, false, 2).unwrap().sender, tx(9).sender);
874    }
875
876    #[test]
877    fn continuation_preserves_gate_draw_order() {
878        for (fresh_weight, discarded, depth, expected_sender, draws_gate) in [
879            (0, false, 1, 2, false),
880            (100, false, 1, 9, true),
881            (50, false, 2, 9, true),
882            (50, true, 1, 9, false),
883        ] {
884            let plan = SequencePlan {
885                initial: InitialSequence::Multiple(vec![tx(1), tx(2)]),
886                tx: generator_tx(9),
887                fresh_weight,
888                has_corpus_dir: true,
889                stateless: false,
890                source: Some(0),
891            };
892            let mut actual = TestRunner::deterministic();
893            let mut reference = TestRunner::deterministic();
894            if draws_gate {
895                let _ = reference.rng().random_ratio(fresh_weight, 100);
896            }
897            assert_eq!(
898                plan.next(&mut actual, discarded, depth).unwrap().sender,
899                tx(expected_sender).sender
900            );
901            assert_eq!(sentinel(&mut actual), sentinel(&mut reference));
902        }
903    }
904
905    #[test]
906    fn forced_invariant_mutations_preserve_old_selection_draws() {
907        let sequences = [vec![tx(1), tx(2), tx(3)], vec![tx(4), tx(5), tx(6)]];
908        let entries = sequences
909            .iter()
910            .map(|sequence| CorpusEntryView::new(sequence, &[]).unwrap())
911            .collect::<Vec<_>>();
912        for kind in 0..7 {
913            let mut config = config();
914            config.mutation_weights = forced_weights(kind);
915            let generator = SequenceGenerator::invariant(
916                generator_tx(9),
917                state(),
918                FuzzRunIdentifiedContracts::new(TargetedContracts::new(), false),
919                &config,
920            )
921            .unwrap();
922            let mut actual = TestRunner::deterministic();
923            let mut reference = TestRunner::deterministic();
924
925            // The legacy producer selected the mutation, both corpus entries, and then the source
926            // before making operation-specific draws. Keep these draws explicit: this test is
927            // intended to catch seemingly harmless reordering during further extraction work.
928            let distribution = WeightedIndex::new(
929                [kind == 0, kind == 1, kind == 2, kind == 3, kind == 4, kind == 5, kind == 6]
930                    .map(u32::from),
931            )
932            .unwrap();
933            assert_eq!(distribution.sample(reference.rng()), kind);
934            let a = reference.rng().random_range(0..entries.len());
935            let b = reference.rng().random_range(0..entries.len());
936            let source = match kind {
937                0 | 2 => a,
938                _ => {
939                    if reference.rng().random() {
940                        a
941                    } else {
942                        b
943                    }
944                }
945            };
946            // ABI/CMP always selected a fallback transaction after choosing the source.
947            if kind >= 5 {
948                let _ = reference.rng().random_range(0..entries[source].transactions.len());
949            }
950
951            let plan =
952                generator.start(&mut actual, entries.len(), |i| Ok(entries[i]), true).unwrap();
953            assert_eq!(plan.source(), Some(source), "mutation family {kind}");
954            // For argument mutation there are no matching artifacts, so the fallback index is the
955            // final draw. Structural mutations make additional operation-specific draws and are
956            // covered independently by the mutator unit tests.
957            if kind >= 5 {
958                assert_eq!(
959                    sentinel(&mut actual),
960                    sentinel(&mut reference),
961                    "mutation family {kind}"
962                );
963            }
964        }
965    }
966
967    #[test]
968    fn stateless_plan_never_exposes_continuation() {
969        let generator = SequenceGenerator::stateless(
970            generator_tx(9),
971            state(),
972            Function::parse("test()").unwrap(),
973            &config(),
974        )
975        .unwrap();
976        let plan = generator
977            .start(&mut TestRunner::deterministic(), 0, |_| unreachable!(), false)
978            .unwrap();
979        assert!(plan.next(&mut TestRunner::deterministic(), false, 0).is_err());
980    }
981
982    #[test]
983    fn overflowing_effective_mutation_weight_is_rejected() {
984        let mut config = config();
985        config.mutation_weights.mutation_weight_splice = u32::MAX;
986        config.mutation_weights.mutation_weight_repeat = 1;
987        assert!(
988            SequenceGenerator::stateless(
989                generator_tx(1),
990                state(),
991                Function::parse("test()").unwrap(),
992                &config,
993            )
994            .is_err()
995        );
996    }
997
998    #[test]
999    fn invariant_cmp_only_does_not_fallback_to_abi() {
1000        let target = Address::with_last_byte(42);
1001        let function = Function::parse("test(uint256)").unwrap();
1002        let mut abi = JsonAbi::new();
1003        abi.functions.entry(function.name.clone()).or_default().push(function.clone());
1004        let mut contracts = TargetedContracts::new();
1005        contracts.insert(target, TargetedContract::new("Target".into(), abi));
1006        let mut original = tx(1);
1007        original.call_details.target = target;
1008        original.call_details.calldata =
1009            function.abi_encode_input(&[DynSolValue::Uint(U256::from(7), 256)]).unwrap().into();
1010        let sequence = [original.clone()];
1011        let corpus = [CorpusEntryView::new(&sequence, &[]).unwrap()];
1012        let mut config = config();
1013        config.mutation_weights = FuzzCorpusMutationWeights {
1014            mutation_weight_splice: 0,
1015            mutation_weight_repeat: 0,
1016            mutation_weight_interleave: 0,
1017            mutation_weight_prefix: 0,
1018            mutation_weight_suffix: 0,
1019            mutation_weight_abi: 0,
1020            mutation_weight_cmp: 1,
1021        };
1022        let generator = SequenceGenerator::invariant(
1023            generator_tx(9),
1024            state(),
1025            FuzzRunIdentifiedContracts::new(contracts, false),
1026            &config,
1027        )
1028        .unwrap();
1029        let plan = generator
1030            .start(&mut TestRunner::default(), corpus.len(), |i| Ok(corpus[i]), true)
1031            .unwrap();
1032        assert_eq!(plan.initial()[0].call_details.calldata, original.call_details.calldata);
1033    }
1034
1035    #[test]
1036    fn malformed_corpus_views_are_rejected_without_panicking() {
1037        assert!(CorpusEntryView::new(&[], &[]).is_err());
1038        let sequence = [tx(1)];
1039        let comparisons = [Vec::new(), Vec::new()];
1040        assert!(CorpusEntryView::new(&sequence, &comparisons).is_err());
1041
1042        let generator = SequenceGenerator::stateless(
1043            generator_tx(9),
1044            state(),
1045            Function::parse("test(uint256)").unwrap(),
1046            &config(),
1047        )
1048        .unwrap();
1049        let result = generator.start(
1050            &mut TestRunner::deterministic(),
1051            1,
1052            |_| CorpusEntryView::new(&[], &[]),
1053            true,
1054        );
1055        assert!(result.is_err());
1056    }
1057
1058    #[test]
1059    fn start_accesses_at_most_two_corpus_entries() {
1060        let mut config = config();
1061        config.mutation_weights.mutation_weight_splice = 1;
1062        config.mutation_weights.mutation_weight_repeat = 0;
1063        config.mutation_weights.mutation_weight_interleave = 0;
1064        config.mutation_weights.mutation_weight_prefix = 0;
1065        config.mutation_weights.mutation_weight_suffix = 0;
1066        config.mutation_weights.mutation_weight_abi = 0;
1067        config.mutation_weights.mutation_weight_cmp = 0;
1068        let generator = SequenceGenerator::invariant(
1069            generator_tx(9),
1070            state(),
1071            FuzzRunIdentifiedContracts::new(TargetedContracts::new(), false),
1072            &config,
1073        )
1074        .unwrap();
1075        let sequence = [tx(1)];
1076        let mut accesses = 0;
1077        generator
1078            .start(
1079                &mut TestRunner::deterministic(),
1080                10_000,
1081                |_| {
1082                    accesses += 1;
1083                    CorpusEntryView::new(&sequence, &[])
1084                },
1085                true,
1086            )
1087            .unwrap();
1088        assert_eq!(accesses, 2);
1089    }
1090
1091    #[test]
1092    fn applicable_hints_dedup_and_drop_operands_missing_from_calldata() {
1093        let function = Function::parse("testCmp(uint256)").unwrap();
1094        let calldata = function.abi_encode_input(&[DynSolValue::Uint(U256::from(7), 256)]).unwrap();
1095        let hint =
1096            |lhs: u64, rhs: u64| ComparisonHint { lhs: U256::from(lhs), rhs: U256::from(rhs) };
1097
1098        let hints = [hint(7, 42), hint(1000, 2000), hint(7, 42), hint(5, 5), hint(42, 7)];
1099        let applicable = ComparisonHint::applicable(&calldata, hints);
1100        assert_eq!(applicable, [hint(7, 42), hint(42, 7)]);
1101        for hint in hints {
1102            let mut input = tx(7);
1103            input.call_details.calldata = calldata.clone().into();
1104            let mutated = SequenceMutator::cmp_mutate(
1105                &mut input,
1106                &function,
1107                &[hint],
1108                &mut TestRunner::default(),
1109                &FuzzFixtures::default(),
1110            )
1111            .unwrap();
1112            assert_eq!(mutated, applicable.contains(&hint));
1113        }
1114    }
1115}