Skip to main content

foundry_evm_fuzz/invariant/
mod.rs

1use alloy_dyn_abi::{JsonAbiExt, abi::AbiDecoderConfig};
2use alloy_json_abi::{Event, Function, JsonAbi, StateMutability};
3use alloy_primitives::{Address, B256, Bytes, Selector, map::HashMap};
4use foundry_compilers::artifacts::StorageLayout;
5use itertools::Either;
6use serde::{Deserialize, Serialize};
7use std::{
8    cell::{Cell, Ref, RefCell},
9    collections::BTreeMap,
10    fmt,
11    rc::Rc,
12    sync::Arc,
13};
14
15mod call_override;
16pub use call_override::RandomCallGenerator;
17
18mod filters;
19use crate::BasicTxDetails;
20use evm2::evm::AccountChanges;
21pub use filters::{ArtifactFilters, SenderFilters};
22use foundry_common::{ContractsByAddress, ContractsByArtifact};
23
24type DynamicTargetArtifactMatchCache =
25    Rc<RefCell<HashMap<(Address, B256), Option<CachedTargetContract>>>>;
26type FuzzedFunction = (Address, Function);
27type FunctionLookup = HashMap<Selector, Function>;
28
29/// Contracts identified as targets during a fuzz run.
30///
31/// During execution, any newly created contract is added as target and used through the rest of
32/// the fuzz run if the collection is updatable (no `targetContract` specified in `setUp`).
33#[derive(Clone, Debug)]
34pub struct FuzzRunIdentifiedContracts {
35    /// Contracts identified as targets during a fuzz run.
36    targets: Rc<RefCell<TargetedContracts>>,
37    /// Flat cache of all currently fuzzable target functions.
38    fuzzed_functions: Rc<RefCell<Vec<FuzzedFunction>>>,
39    /// Generation counter for cached fuzzed functions.
40    fuzzed_functions_generation: Rc<Cell<u64>>,
41    /// Whether target contracts are updatable or not.
42    pub is_updatable: bool,
43    artifact_matches: DynamicTargetArtifactMatchCache,
44}
45
46impl FuzzRunIdentifiedContracts {
47    /// Creates a new `FuzzRunIdentifiedContracts` instance.
48    pub fn new(targets: TargetedContracts, is_updatable: bool) -> Self {
49        let fuzzed_functions = Self::flatten_fuzzed_functions(&targets);
50        Self {
51            targets: Rc::new(RefCell::new(targets)),
52            fuzzed_functions: Rc::new(RefCell::new(fuzzed_functions)),
53            fuzzed_functions_generation: Rc::new(Cell::new(0)),
54            is_updatable,
55            artifact_matches: Rc::new(RefCell::new(HashMap::default())),
56        }
57    }
58
59    /// Borrows the current targeted contracts.
60    pub fn targets(&self) -> Ref<'_, TargetedContracts> {
61        self.targets.borrow()
62    }
63
64    /// Borrows the current flat list of fuzzed target functions.
65    pub fn fuzzed_functions(&self) -> Ref<'_, [FuzzedFunction]> {
66        Ref::map(self.fuzzed_functions.borrow(), Vec::as_slice)
67    }
68
69    /// Returns the current fuzzed-functions generation.
70    pub fn fuzzed_functions_generation(&self) -> u64 {
71        self.fuzzed_functions_generation.get()
72    }
73
74    fn refresh_fuzzed_functions(&self) {
75        let fuzzed_functions = {
76            let targets = self.targets.borrow();
77            Self::flatten_fuzzed_functions(&targets)
78        };
79        *self.fuzzed_functions.borrow_mut() = fuzzed_functions;
80        self.fuzzed_functions_generation.set(self.fuzzed_functions_generation.get() + 1);
81    }
82
83    fn flatten_fuzzed_functions(targets: &TargetedContracts) -> Vec<FuzzedFunction> {
84        targets.fuzzed_functions().map(|(address, function)| (*address, function.clone())).collect()
85    }
86
87    /// If targets are updatable, collect all contracts created during an invariant run (which
88    /// haven't been discovered yet).
89    ///
90    /// `state_changes` are the call's [`AccountChanges`], as returned by
91    /// `ExecutedTx::account_changes` or `PendingState::account_changes`.
92    pub fn collect_created_contracts<'a>(
93        &self,
94        state_changes: impl IntoIterator<Item = AccountChanges<'a>>,
95        project_contracts: &ContractsByArtifact,
96        setup_contracts: &ContractsByAddress,
97        artifact_filters: &ArtifactFilters,
98        created_contracts: &mut Vec<Address>,
99    ) -> eyre::Result<()> {
100        if !self.is_updatable {
101            return Ok(());
102        }
103
104        let mut targets_changed = false;
105        for changes in state_changes {
106            let address = changes.address;
107            // An account a call touched without changing it counts.
108            if setup_contracts.contains_key(&address) || !(changes.is_changed() || changes.touched)
109            {
110                continue;
111            }
112            let Some((code_hash, code)) = changes.code.or_else(|| {
113                changes.current.and_then(|info| Some((info.code_hash, info.code.as_ref()?)))
114            }) else {
115                continue;
116            };
117            if code.is_empty() {
118                continue;
119            }
120            let Some(contract) = self.target_contract_for_code(
121                address,
122                code_hash,
123                code.original_byte_slice(),
124                project_contracts,
125                artifact_filters,
126            )?
127            else {
128                continue;
129            };
130            created_contracts.push(address);
131            self.targets.borrow_mut().insert(address, contract.into_targeted_contract());
132            targets_changed = true;
133        }
134        if targets_changed {
135            self.refresh_fuzzed_functions();
136        }
137        Ok(())
138    }
139
140    fn target_contract_for_code(
141        &self,
142        address: Address,
143        code_hash: B256,
144        code: &[u8],
145        project_contracts: &ContractsByArtifact,
146        artifact_filters: &ArtifactFilters,
147    ) -> eyre::Result<Option<CachedTargetContract>> {
148        let cache_key = (address, code_hash);
149        if let Some(cached_match) = self.artifact_matches.borrow().get(&cache_key) {
150            return Ok(cached_match.clone());
151        }
152
153        let cached_match = if let Some((artifact, contract_data)) =
154            project_contracts.find_by_deployed_code(code)
155        {
156            artifact_filters.get_targeted_functions(artifact, &contract_data.abi)?.map(
157                |targeted_functions| CachedTargetContract {
158                    identifier: artifact.name.clone(),
159                    abi: contract_data.abi.clone(),
160                    targeted_functions,
161                    storage_layout: contract_data.storage_layout.as_ref().map(Arc::clone),
162                    event_lookup: Arc::new(TargetedContractEvents::new(&contract_data.abi)),
163                },
164            )
165        } else {
166            None
167        };
168        self.artifact_matches.borrow_mut().insert(cache_key, cached_match.clone());
169        Ok(cached_match)
170    }
171
172    /// Clears targeted contracts created during an invariant run.
173    pub fn clear_created_contracts(&self, created_contracts: Vec<Address>) {
174        let mut targets_changed = false;
175        if !created_contracts.is_empty() {
176            let mut targets = self.targets.borrow_mut();
177            for addr in &created_contracts {
178                targets_changed |= targets.remove(addr).is_some();
179            }
180        }
181        if targets_changed {
182            self.refresh_fuzzed_functions();
183        }
184    }
185}
186
187#[derive(Clone, Debug)]
188struct CachedTargetContract {
189    identifier: String,
190    abi: JsonAbi,
191    targeted_functions: Vec<Function>,
192    storage_layout: Option<Arc<StorageLayout>>,
193    event_lookup: Arc<TargetedContractEvents>,
194}
195
196impl CachedTargetContract {
197    fn into_targeted_contract(self) -> TargetedContract {
198        TargetedContract::from_parts(
199            self.identifier,
200            self.abi,
201            self.targeted_functions,
202            Vec::new(),
203            self.storage_layout,
204            self.event_lookup,
205        )
206    }
207}
208
209/// A collection of contracts identified as targets for invariant testing.
210#[derive(Clone, Debug, Default)]
211pub struct TargetedContracts {
212    /// The inner map of targeted contracts.
213    pub inner: BTreeMap<Address, TargetedContract>,
214}
215
216impl TargetedContracts {
217    /// Returns a new `TargetedContracts` instance.
218    pub fn new() -> Self {
219        Self::default()
220    }
221
222    /// Returns fuzzed contract and fuzzed function from address and provided calldata.
223    ///
224    /// Used to decode return values and logs in order to add values into fuzz dictionary.
225    pub fn fuzzed_artifacts(
226        &self,
227        tx: &BasicTxDetails,
228    ) -> (Option<&TargetedContract>, Option<&Function>) {
229        match self.inner.get(&tx.call_details.target) {
230            Some(c) => {
231                let function = tx
232                    .call_details
233                    .calldata
234                    .get(..4)
235                    .map(Selector::from_slice)
236                    .and_then(|selector| c.function_by_selector(selector));
237                (Some(c), function)
238            }
239            None => (None, None),
240        }
241    }
242
243    /// Returns flatten target contract address and functions to be fuzzed.
244    /// Includes contract targeted functions if specified, else all mutable contract functions.
245    pub fn fuzzed_functions(&self) -> impl Iterator<Item = (&Address, &Function)> {
246        self.inner
247            .iter()
248            .filter(|(_, c)| !c.abi.functions.is_empty())
249            .flat_map(|(contract, c)| c.abi_fuzzed_functions().map(move |f| (contract, f)))
250    }
251
252    /// Returns whether the given transaction can be replayed or not with known contracts.
253    ///
254    /// The call must target a fuzzed function, carry arguments that ABI-decode with canonical
255    /// words, and send value only to a payable function. This checks ABI admission, not exact
256    /// fuzzer output: trailing calldata and non-strict dynamic layouts are allowed, and enum
257    /// variant bounds are not checked.
258    pub fn can_replay(&self, tx: &BasicTxDetails) -> bool {
259        let calldata = &tx.call_details.calldata;
260        self.inner.get(&tx.call_details.target).is_some_and(|c| {
261            calldata
262                .get(..4)
263                .map(Selector::from_slice)
264                .and_then(|selector| c.fuzzed_function_by_selector(selector))
265                .is_some_and(|function| {
266                    (function.state_mutability == StateMutability::Payable
267                        || tx.call_details.value.is_none_or(|value| value.is_zero()))
268                        // Decoding depth follows the function's type nesting, which the fuzzer
269                        // does not limit, so the default recursion limit would reject valid calls.
270                        && function
271                            .abi_decode_input_with_config(
272                                &calldata[4..],
273                                AbiDecoderConfig::new()
274                                    .validate_words(true)
275                                    .recursion_limit(usize::MAX),
276                            )
277                            .is_ok()
278                })
279        })
280    }
281
282    /// Identifies fuzzed contract and function based on given tx details and returns unique metric
283    /// key composed from contract identifier and function name.
284    pub fn fuzzed_metric_key(&self, tx: &BasicTxDetails) -> Option<String> {
285        tx.call_details.calldata.get(..4).map(Selector::from_slice).and_then(|selector| {
286            self.fuzzed_metric_key_for_selector(tx.call_details.target, selector)
287        })
288    }
289
290    /// Identifies fuzzed contract and function from target and selector and returns unique metric
291    /// key composed from contract identifier and function name.
292    pub fn fuzzed_metric_key_for_selector(
293        &self,
294        target: Address,
295        selector: Selector,
296    ) -> Option<String> {
297        self.inner.get(&target).and_then(|contract| {
298            contract
299                .function_by_selector(selector)
300                .map(|function| format!("{}.{}", contract.identifier.as_str(), function.name))
301        })
302    }
303}
304
305impl std::ops::Deref for TargetedContracts {
306    type Target = BTreeMap<Address, TargetedContract>;
307
308    fn deref(&self) -> &Self::Target {
309        &self.inner
310    }
311}
312
313impl std::ops::DerefMut for TargetedContracts {
314    fn deref_mut(&mut self) -> &mut Self::Target {
315        &mut self.inner
316    }
317}
318
319/// A contract identified as target for invariant testing.
320#[derive(Clone, Debug)]
321pub struct TargetedContract {
322    /// The contract identifier. This is only used in error messages.
323    pub identifier: String,
324    /// The contract's ABI.
325    pub abi: JsonAbi,
326    /// The targeted functions of the contract.
327    pub targeted_functions: Vec<Function>,
328    /// The excluded functions of the contract.
329    pub excluded_functions: Vec<Function>,
330    /// The contract's storage layout, if available.
331    pub storage_layout: Option<Arc<StorageLayout>>,
332    /// Contract events indexed by topic0 and indexed-topic count for log dictionary decoding.
333    pub event_lookup: Arc<TargetedContractEvents>,
334    functions_by_selector: FunctionLookup,
335    fuzzed_functions_by_selector: FunctionLookup,
336}
337
338impl TargetedContract {
339    /// Returns a new `TargetedContract` instance.
340    pub fn new(identifier: String, abi: JsonAbi) -> Self {
341        let event_lookup = Arc::new(TargetedContractEvents::new(&abi));
342        Self::from_parts(identifier, abi, Vec::new(), Vec::new(), None, event_lookup)
343    }
344
345    fn from_parts(
346        identifier: String,
347        abi: JsonAbi,
348        targeted_functions: Vec<Function>,
349        excluded_functions: Vec<Function>,
350        storage_layout: Option<Arc<StorageLayout>>,
351        event_lookup: Arc<TargetedContractEvents>,
352    ) -> Self {
353        let mut contract = Self {
354            identifier,
355            abi,
356            targeted_functions,
357            excluded_functions,
358            storage_layout,
359            event_lookup,
360            functions_by_selector: FunctionLookup::default(),
361            fuzzed_functions_by_selector: FunctionLookup::default(),
362        };
363        contract.rebuild_function_lookups();
364        contract
365    }
366
367    /// Determines contract storage layout from project contracts. Needs `storageLayout` to be
368    /// enabled as extra output in project configuration.
369    pub fn with_project_contracts(mut self, project_contracts: &ContractsByArtifact) -> Self {
370        if let Some((src, name)) = self.identifier.split_once(':')
371            && let Some((_, contract_data)) = project_contracts.iter().find(|(artifact, _)| {
372                artifact.name == name && artifact.source.as_path().ends_with(src)
373            })
374        {
375            self.storage_layout = contract_data.storage_layout.as_ref().map(Arc::clone);
376        }
377        self
378    }
379
380    /// Helper to retrieve functions to fuzz for specified abi.
381    /// Returns specified targeted functions if any, else mutable abi functions, always skipping
382    /// functions marked as excluded.
383    pub fn abi_fuzzed_functions(&self) -> impl Iterator<Item = &Function> {
384        if self.targeted_functions.is_empty() {
385            Either::Right(self.abi.functions().filter(|&func| {
386                !matches!(
387                    func.state_mutability,
388                    alloy_json_abi::StateMutability::Pure | alloy_json_abi::StateMutability::View
389                ) && !self.excluded_functions.contains(func)
390            }))
391        } else {
392            Either::Left(
393                self.targeted_functions
394                    .iter()
395                    .filter(|func| !self.excluded_functions.contains(func)),
396            )
397        }
398    }
399
400    pub fn rebuild_function_lookups(&mut self) {
401        let functions_by_selector =
402            self.abi.functions().fold(FunctionLookup::default(), |mut functions, function| {
403                functions.entry(function.selector()).or_insert_with(|| function.clone());
404                functions
405            });
406        let fuzzed_functions_by_selector = self.abi_fuzzed_functions().fold(
407            FunctionLookup::default(),
408            |mut functions, function| {
409                functions.entry(function.selector()).or_insert_with(|| function.clone());
410                functions
411            },
412        );
413        self.functions_by_selector = functions_by_selector;
414        self.fuzzed_functions_by_selector = fuzzed_functions_by_selector;
415    }
416
417    /// Returns any ABI function for the given selector.
418    pub fn function_by_selector(&self, selector: Selector) -> Option<&Function> {
419        self.functions_by_selector.get(&selector)
420    }
421
422    /// Returns a fuzzable function for the given selector.
423    pub fn fuzzed_function_by_selector(&self, selector: Selector) -> Option<&Function> {
424        self.fuzzed_functions_by_selector.get(&selector)
425    }
426
427    /// Returns the function for the given selector.
428    pub fn get_function(&self, selector: Selector) -> eyre::Result<&Function> {
429        self.function_by_selector(selector)
430            .ok_or_else(|| eyre::eyre!("{} does not have the selector {selector}", self.identifier))
431    }
432
433    /// Adds the specified selectors to the targeted functions.
434    pub fn add_selectors(
435        &mut self,
436        selectors: impl IntoIterator<Item = Selector>,
437        should_exclude: bool,
438    ) -> eyre::Result<()> {
439        for selector in selectors {
440            if should_exclude {
441                self.excluded_functions.push(self.get_function(selector)?.clone());
442            } else {
443                self.targeted_functions.push(self.get_function(selector)?.clone());
444            }
445        }
446        self.rebuild_function_lookups();
447        Ok(())
448    }
449}
450
451/// Events for a targeted contract, pre-indexed for log dictionary decoding.
452#[derive(Clone, Debug, Default)]
453pub struct TargetedContractEvents {
454    by_topic: HashMap<(B256, usize), Vec<TargetedContractEvent>>,
455    anonymous: Vec<TargetedContractEvent>,
456}
457
458impl TargetedContractEvents {
459    fn new(abi: &JsonAbi) -> Self {
460        let mut events = Self::default();
461        for (order, event) in abi.events().enumerate() {
462            let event = TargetedContractEvent { order, event: event.clone() };
463            if event.event.anonymous {
464                events.anonymous.push(event);
465            } else {
466                let indexed_count = event.event.inputs.iter().filter(|input| input.indexed).count();
467                events
468                    .by_topic
469                    .entry((event.event.selector(), indexed_count))
470                    .or_default()
471                    .push(event);
472            }
473        }
474        events
475    }
476
477    pub fn by_topic(
478        &self,
479        selector: &B256,
480        indexed_count: usize,
481    ) -> Option<&[TargetedContractEvent]> {
482        self.by_topic.get(&(*selector, indexed_count)).map(Vec::as_slice)
483    }
484
485    pub fn anonymous(&self) -> &[TargetedContractEvent] {
486        &self.anonymous
487    }
488}
489
490/// Event with its flattened ABI order for preserving log decode priority.
491#[derive(Clone, Debug)]
492pub struct TargetedContractEvent {
493    event: Event,
494    order: usize,
495}
496
497impl TargetedContractEvent {
498    pub const fn order(&self) -> usize {
499        self.order
500    }
501
502    pub const fn event(&self) -> &Event {
503        &self.event
504    }
505}
506
507/// Test contract which is testing its invariants.
508#[derive(Clone, Debug)]
509pub struct InvariantContract<'a> {
510    /// Address of the test contract.
511    pub address: Address,
512    /// Name of the test contract.
513    pub name: &'a str,
514    /// Invariant functions to assert against, paired with their `fail_on_revert` config.
515    /// Stored in **source declaration order** so failure-event attribution and report
516    /// rendering match user expectations.
517    pub invariant_fns: Vec<(&'a Function, bool)>,
518    /// Index into [`Self::invariant_fns`] of the stable campaign anchor. Boolean invariant
519    /// suites use a deterministic contract-local anchor so test filters do not affect
520    /// corpus/failure namespaces.
521    pub anchor_idx: usize,
522    /// If true, `afterInvariant` function is called after each invariant run.
523    pub call_after_invariant: bool,
524    /// ABI of the test contract.
525    pub abi: &'a JsonAbi,
526    /// ABI calldata for each invariant function.
527    pub invariant_calldata: Vec<Bytes>,
528}
529
530impl<'a> InvariantContract<'a> {
531    /// Creates a new invariant contract.
532    ///
533    /// Caller must ensure `invariant_fns` is non-empty and `anchor_idx < invariant_fns.len()`.
534    pub fn new(
535        address: Address,
536        name: &'a str,
537        invariant_fns: Vec<(&'a Function, bool)>,
538        anchor_idx: usize,
539        call_after_invariant: bool,
540        abi: &'a JsonAbi,
541    ) -> Self {
542        let invariant_calldata =
543            invariant_fns.iter().map(|(func, _)| func.selector().into()).collect();
544        Self {
545            address,
546            name,
547            invariant_fns,
548            anchor_idx,
549            call_after_invariant,
550            abi,
551            invariant_calldata,
552        }
553    }
554
555    /// Returns the stable campaign anchor.
556    pub fn anchor(&self) -> &'a Function {
557        self.invariant_fns[self.anchor_idx].0
558    }
559
560    /// Returns cached calldata for the invariant at `idx`.
561    pub fn invariant_calldata(&self, idx: usize) -> Bytes {
562        self.invariant_calldata[idx].clone()
563    }
564
565    /// Returns cached calldata for the stable campaign anchor.
566    pub fn anchor_calldata(&self) -> Bytes {
567        self.invariant_calldata(self.anchor_idx)
568    }
569
570    /// Returns true if this is an optimization mode invariant (returns int256).
571    pub fn is_optimization(&self) -> bool {
572        is_optimization_invariant(self.anchor())
573    }
574}
575
576/// Settings that determine the validity of a persisted invariant counterexample.
577///
578/// When a counterexample is replayed, it's only valid if the same contracts, selectors,
579/// senders, and fail_on_revert settings are used. Changes to unrelated code (e.g., adding
580/// a log statement) should not invalidate the counterexample.
581#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
582pub struct InvariantSettings {
583    /// Target contracts with their addresses and identifiers.
584    pub target_contracts: BTreeMap<Address, String>,
585    /// Target selectors per contract address.
586    pub target_selectors: BTreeMap<Address, Vec<Selector>>,
587    /// Target senders for the invariant test.
588    pub target_senders: Vec<Address>,
589    /// Excluded senders for the invariant test.
590    pub excluded_senders: Vec<Address>,
591    /// Whether the test should fail on any revert.
592    pub fail_on_revert: bool,
593}
594
595impl InvariantSettings {
596    /// Creates new invariant settings from the given components.
597    pub fn new(
598        targeted_contracts: &TargetedContracts,
599        sender_filters: &SenderFilters,
600        fail_on_revert: bool,
601    ) -> Self {
602        let mut target_contracts = BTreeMap::new();
603        let mut target_selectors = BTreeMap::new();
604        for (addr, contract) in &targeted_contracts.inner {
605            target_contracts.insert(*addr, contract.identifier.clone());
606            target_selectors
607                .insert(*addr, contract.abi_fuzzed_functions().map(|f| f.selector()).collect());
608        }
609
610        let mut target_senders = sender_filters.targeted.clone();
611        target_senders.sort_unstable();
612
613        let mut excluded_senders = sender_filters.excluded.clone();
614        excluded_senders.sort_unstable();
615
616        Self {
617            target_contracts,
618            target_selectors,
619            target_senders,
620            excluded_senders,
621            fail_on_revert,
622        }
623    }
624
625    /// Compares these settings with another and returns a description of what changed.
626    /// Returns `None` if the settings are equivalent.
627    pub fn diff(&self, other: &Self) -> Option<String> {
628        let mut changes = Vec::new();
629
630        if self.target_contracts != other.target_contracts {
631            let added: Vec<_> = other
632                .target_contracts
633                .iter()
634                .filter(|(addr, _)| !self.target_contracts.contains_key(*addr))
635                .map(|(_, name)| name.as_str())
636                .collect();
637            let removed: Vec<_> = self
638                .target_contracts
639                .iter()
640                .filter(|(addr, _)| !other.target_contracts.contains_key(*addr))
641                .map(|(_, name)| name.as_str())
642                .collect();
643
644            if !added.is_empty() {
645                changes.push(format!("added target contracts: {}", added.join(", ")));
646            }
647            if !removed.is_empty() {
648                changes.push(format!("removed target contracts: {}", removed.join(", ")));
649            }
650        }
651
652        if self.target_selectors != other.target_selectors {
653            changes.push("target selectors changed".to_string());
654        }
655
656        if self.target_senders != other.target_senders {
657            changes.push("target senders changed".to_string());
658        }
659
660        if self.excluded_senders != other.excluded_senders {
661            changes.push("excluded senders changed".to_string());
662        }
663
664        if self.fail_on_revert != other.fail_on_revert {
665            changes.push(format!(
666                "fail_on_revert changed from {} to {}",
667                self.fail_on_revert, other.fail_on_revert
668            ));
669        }
670
671        if changes.is_empty() { None } else { Some(changes.join(", ")) }
672    }
673}
674
675impl fmt::Display for InvariantSettings {
676    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
677        write!(
678            f,
679            "targets: {}, selectors: {}, senders: {}, excluded: {}, fail_on_revert: {}",
680            self.target_contracts.len(),
681            self.target_selectors.values().map(|v| v.len()).sum::<usize>(),
682            self.target_senders.len(),
683            self.excluded_senders.len(),
684            self.fail_on_revert,
685        )
686    }
687}
688
689/// Returns true if the function returns `int256`, indicating optimization mode.
690/// In optimization mode, the fuzzer maximizes the return value instead of checking invariants.
691pub fn is_optimization_invariant(func: &Function) -> bool {
692    func.outputs.len() == 1 && func.outputs[0].ty == "int256"
693}
694
695#[cfg(test)]
696mod tests {
697    use super::*;
698    use crate::CallDetails;
699    use alloy_primitives::U256;
700    use evm2::{
701        bytecode::Bytecode,
702        evm::{AccountInfo, PendingState, StorageOverlay},
703    };
704    use foundry_compilers::{
705        ArtifactId,
706        artifacts::{
707            BytecodeObject, CompactBytecode, CompactContractBytecode, CompactDeployedBytecode,
708        },
709    };
710
711    fn abi_with_functions(functions: &[&str]) -> JsonAbi {
712        let mut abi = JsonAbi::new();
713        for function in functions {
714            let function = Function::parse(function).unwrap();
715            abi.functions.entry(function.name.clone()).or_default().push(function);
716        }
717        abi
718    }
719
720    fn targeted_contracts_with_functions(target: Address, functions: &[&str]) -> TargetedContracts {
721        let mut targets = TargetedContracts::new();
722        targets.inner.insert(
723            target,
724            TargetedContract::new("Target".to_string(), abi_with_functions(functions)),
725        );
726        targets
727    }
728
729    fn targeted_contracts_with_function(target: Address, function: Function) -> TargetedContracts {
730        let mut abi = JsonAbi::new();
731        abi.functions.entry(function.name.clone()).or_default().push(function);
732        let mut targets = TargetedContracts::new();
733        targets.inner.insert(target, TargetedContract::new("Target".to_string(), abi));
734        targets
735    }
736
737    fn tx(target: Address, calldata: impl Into<Bytes>) -> BasicTxDetails {
738        BasicTxDetails {
739            warp: None,
740            roll: None,
741            sender: Address::ZERO,
742            call_details: CallDetails { target, calldata: calldata.into(), value: None },
743        }
744    }
745
746    fn artifact_id(name: &str) -> ArtifactId {
747        ArtifactId {
748            path: format!("{name}.json").into(),
749            name: name.to_string(),
750            source: format!("{name}.sol").into(),
751            version: "0.8.30".parse().unwrap(),
752            build_id: "test".to_string(),
753            profile: "test".to_string(),
754        }
755    }
756
757    fn project_contracts_with_runtime_code_and_abi(
758        name: &str,
759        code: Bytes,
760        abi: JsonAbi,
761    ) -> ContractsByArtifact {
762        let deployed_bytecode = CompactDeployedBytecode {
763            bytecode: Some(CompactBytecode {
764                object: BytecodeObject::Bytecode(code),
765                source_map: None,
766                link_references: Default::default(),
767            }),
768            immutable_references: Default::default(),
769        };
770        let artifact = CompactContractBytecode {
771            abi: Some(abi),
772            bytecode: None,
773            deployed_bytecode: Some(deployed_bytecode),
774        };
775        ContractsByArtifact::new([(artifact_id(name), artifact)])
776    }
777
778    /// Records an account created with `code` by the transaction.
779    fn insert_created_account(state: &mut PendingState, address: Address, code: Bytes) {
780        let info = AccountInfo::default().with_code(Bytecode::new_raw(code));
781        state.insert_account(address, None, Some(info));
782    }
783
784    #[test]
785    fn targeted_contracts_short_calldata_is_not_replayable_or_decodable() {
786        let target = Address::repeat_byte(0x42);
787        let targets = targeted_contracts_with_function(target, Function::parse("foo()").unwrap());
788        let tx = tx(target, vec![0xde, 0xad, 0xbe]);
789
790        assert!(!targets.can_replay(&tx));
791        assert!(targets.fuzzed_artifacts(&tx).1.is_none());
792        assert!(targets.fuzzed_metric_key(&tx).is_none());
793    }
794
795    #[test]
796    fn targeted_contracts_replay_only_generatable_calls() {
797        let target = Address::repeat_byte(0x42);
798        let deep_signature = format!("deep(uint256{})", "[1]".repeat(17));
799        let targets = targeted_contracts_with_functions(
800            target,
801            &["set(uint8)", "deposit() payable", &deep_signature],
802        );
803        let set = Function::parse("set(uint8)").unwrap().selector();
804        let deposit = Function::parse("deposit()").unwrap().selector();
805        let deep = Function::parse(&deep_signature).unwrap().selector();
806        let set_calldata = |word: u64| {
807            let mut calldata = set.to_vec();
808            calldata.extend_from_slice(&U256::from(word).to_be_bytes::<32>());
809            calldata
810        };
811        let with_value = |value: u64, mut tx: BasicTxDetails| {
812            tx.call_details.value = Some(U256::from(value));
813            tx
814        };
815        let mut trailing = set_calldata(1);
816        trailing.extend_from_slice(&[0xaa; 20]);
817
818        assert!(targets.can_replay(&tx(target, set_calldata(0xff))));
819        assert!(!targets.can_replay(&tx(target, set.to_vec())));
820        assert!(!targets.can_replay(&tx(target, set_calldata(0x1ff))));
821        assert!(targets.can_replay(&tx(target, trailing)));
822        assert!(targets.can_replay(&with_value(0, tx(target, set_calldata(1)))));
823        assert!(!targets.can_replay(&with_value(1, tx(target, set_calldata(1)))));
824        assert!(targets.can_replay(&with_value(1, tx(target, deposit.to_vec()))));
825        assert!(targets.can_replay(&tx(target, [deep.as_slice(), &[0; 32]].concat())));
826    }
827
828    #[test]
829    fn abi_fuzzed_functions_filters_excluded_targeted_functions() {
830        let allowed = Function::parse("allowed()").unwrap();
831        let excluded = Function::parse("excluded()").unwrap();
832        let mut contract = TargetedContract::new("Target".to_string(), JsonAbi::new());
833        contract.targeted_functions = vec![allowed.clone(), excluded.clone()];
834        contract.excluded_functions = vec![excluded];
835
836        let selectors = contract.abi_fuzzed_functions().map(Function::selector).collect::<Vec<_>>();
837
838        assert_eq!(selectors, vec![allowed.selector()]);
839    }
840
841    #[test]
842    fn targeted_contracts_refresh_selector_lookup_after_filters() {
843        let target = Address::repeat_byte(0x42);
844        let foo = Function::parse("foo()").unwrap();
845        let bar = Function::parse("bar()").unwrap();
846
847        let mut excluded = targeted_contracts_with_functions(target, &["foo()", "bar()"]);
848        excluded.inner.get_mut(&target).unwrap().add_selectors([foo.selector()], true).unwrap();
849        assert!(!excluded.can_replay(&tx(target, foo.selector().to_vec())));
850        assert!(excluded.can_replay(&tx(target, bar.selector().to_vec())));
851        assert_eq!(
852            excluded.fuzzed_artifacts(&tx(target, foo.selector().to_vec())).1.unwrap().name,
853            "foo"
854        );
855
856        let mut targeted = targeted_contracts_with_functions(target, &["foo()", "bar()"]);
857        targeted.inner.get_mut(&target).unwrap().add_selectors([foo.selector()], false).unwrap();
858        assert!(targeted.can_replay(&tx(target, foo.selector().to_vec())));
859        assert!(!targeted.can_replay(&tx(target, bar.selector().to_vec())));
860        assert_eq!(
861            targeted.fuzzed_metric_key_for_selector(target, bar.selector()).unwrap(),
862            "Target.bar"
863        );
864    }
865
866    #[test]
867    fn fuzz_run_identified_contracts_cache_fuzzed_functions_in_target_order() {
868        let first = Address::repeat_byte(0x01);
869        let second = Address::repeat_byte(0x02);
870        let mut targets = targeted_contracts_with_functions(second, &["bar()", "baz(uint256)"]);
871        targets.inner.insert(
872            first,
873            TargetedContract::new(
874                "First".to_string(),
875                abi_with_functions(&["foo()", "qux(address)"]),
876            ),
877        );
878        let expected = targets
879            .fuzzed_functions()
880            .map(|(address, function)| (*address, function.selector()))
881            .collect::<Vec<_>>();
882
883        let identified = FuzzRunIdentifiedContracts::new(targets, true);
884        let actual = identified
885            .fuzzed_functions()
886            .iter()
887            .map(|(address, function)| (*address, function.selector()))
888            .collect::<Vec<_>>();
889
890        assert_eq!(actual, expected);
891    }
892
893    #[test]
894    fn collect_created_contracts_caches_deployed_code_matches() {
895        let existing = Address::repeat_byte(0x42);
896        let created = Address::repeat_byte(0x43);
897        let setup = Address::repeat_byte(0x44);
898        let untouched = Address::repeat_byte(0x45);
899        let touched = Address::repeat_byte(0x46);
900        let runtime_code = Bytes::from_static(&[0x60, 0x00, 0x56]);
901        let project_contracts = project_contracts_with_runtime_code_and_abi(
902            "DynamicTarget",
903            runtime_code.clone(),
904            JsonAbi::new(),
905        );
906        let mut targets = TargetedContracts::new();
907        for address in [existing, setup, untouched, touched] {
908            targets.inner.insert(
909                address,
910                TargetedContract::new("AlreadyTargeted".to_string(), JsonAbi::new()),
911            );
912        }
913        let identified = FuzzRunIdentifiedContracts::new(targets, true);
914
915        let mut state = PendingState::default();
916        insert_created_account(&mut state, existing, runtime_code.clone());
917        insert_created_account(&mut state, setup, runtime_code.clone());
918        let loaded = AccountInfo::default().with_code(Bytecode::new_raw(runtime_code.clone()));
919        state.insert_account(untouched, Some(loaded.clone()), Some(loaded.clone()));
920        insert_created_account(&mut state, created, runtime_code);
921        let storage = StorageOverlay::default();
922        let touched_only = AccountChanges {
923            address: touched,
924            original: Some(&loaded),
925            current: Some(&loaded),
926            created: false,
927            selfdestructed: false,
928            touched: true,
929            code: None,
930            storage: &storage,
931        };
932        let mut created_contracts = Vec::new();
933        let setup_contracts =
934            ContractsByAddress::from([(setup, ("Setup".to_string(), JsonAbi::new()))]);
935
936        identified
937            .collect_created_contracts(
938                state.account_changes().chain([touched_only]),
939                &project_contracts,
940                &setup_contracts,
941                &ArtifactFilters::default(),
942                &mut created_contracts,
943            )
944            .unwrap();
945
946        created_contracts.sort_unstable();
947        assert_eq!(created_contracts, vec![existing, created, touched]);
948        let targets = identified.targets();
949        assert_eq!(targets[&existing].identifier, "DynamicTarget");
950        assert_eq!(targets[&created].identifier, "DynamicTarget");
951        assert_eq!(targets[&touched].identifier, "DynamicTarget");
952        assert_eq!(targets[&setup].identifier, "AlreadyTargeted");
953        assert_eq!(targets[&untouched].identifier, "AlreadyTargeted");
954        drop(targets);
955
956        identified
957            .collect_created_contracts(
958                state.account_changes(),
959                &Default::default(),
960                &setup_contracts,
961                &ArtifactFilters::default(),
962                &mut created_contracts,
963            )
964            .unwrap();
965
966        created_contracts.sort_unstable();
967        assert_eq!(created_contracts, vec![existing, existing, created, created, touched]);
968    }
969
970    #[test]
971    fn collect_and_clear_created_contracts_refresh_fuzzed_function_cache() {
972        let existing = Address::repeat_byte(0x42);
973        let created = Address::repeat_byte(0x43);
974        let runtime_code = Bytes::from_static(&[0x60, 0x00, 0x56]);
975        let project_contracts = project_contracts_with_runtime_code_and_abi(
976            "DynamicTarget",
977            runtime_code.clone(),
978            abi_with_functions(&["dynamic(uint256)"]),
979        );
980        let identified = FuzzRunIdentifiedContracts::new(
981            targeted_contracts_with_functions(existing, &["existing()"]),
982            true,
983        );
984
985        let initial = identified
986            .fuzzed_functions()
987            .iter()
988            .map(|(address, function)| (*address, function.selector()))
989            .collect::<Vec<_>>();
990        assert_eq!(initial, vec![(existing, Function::parse("existing()").unwrap().selector())]);
991        assert_eq!(identified.fuzzed_functions_generation(), 0);
992
993        let mut state = PendingState::default();
994        insert_created_account(&mut state, created, runtime_code);
995        let mut created_contracts = Vec::new();
996
997        identified
998            .collect_created_contracts(
999                state.account_changes(),
1000                &project_contracts,
1001                &ContractsByAddress::default(),
1002                &ArtifactFilters::default(),
1003                &mut created_contracts,
1004            )
1005            .unwrap();
1006
1007        let with_created = identified
1008            .fuzzed_functions()
1009            .iter()
1010            .map(|(address, function)| (*address, function.selector()))
1011            .collect::<Vec<_>>();
1012        assert_eq!(identified.fuzzed_functions_generation(), 1);
1013        assert_eq!(
1014            with_created,
1015            vec![
1016                (existing, Function::parse("existing()").unwrap().selector()),
1017                (created, Function::parse("dynamic(uint256)").unwrap().selector()),
1018            ]
1019        );
1020
1021        identified.clear_created_contracts(created_contracts);
1022        let cleared = identified
1023            .fuzzed_functions()
1024            .iter()
1025            .map(|(address, function)| (*address, function.selector()))
1026            .collect::<Vec<_>>();
1027        assert_eq!(cleared, initial);
1028        assert_eq!(identified.fuzzed_functions_generation(), 2);
1029    }
1030}