Skip to main content

foundry_config/
fuzz.rs

1//! Configuration for fuzz testing.
2
3use alloy_primitives::U256;
4use foundry_compilers::utils::canonicalized;
5use serde::{Deserialize, Deserializer, Serialize, de::Error};
6use std::path::PathBuf;
7
8/// Contains for fuzz testing
9#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
10pub struct FuzzConfig {
11    /// The number of test cases that must execute for each property test
12    #[serde(deserialize_with = "deserialize_fuzz_runs")]
13    pub runs: u32,
14    /// Optional 1-based fuzz run to execute.
15    pub run: Option<u32>,
16    /// Optional fuzz worker ID to pair with `run`.
17    pub worker: Option<u32>,
18    /// Fails the fuzzed test if a revert occurs.
19    pub fail_on_revert: bool,
20    /// The maximum number of test case rejections allowed,
21    /// encountered during usage of `vm.assume` cheatcode.
22    pub max_test_rejects: u32,
23    /// Optional seed for the fuzzing RNG algorithm
24    pub seed: Option<U256>,
25    /// The fuzz dictionary configuration
26    #[serde(flatten)]
27    pub dictionary: FuzzDictionaryConfig,
28    /// Number of runs to execute and include in the gas report.
29    pub gas_report_samples: u32,
30    /// The fuzz corpus configuration.
31    #[serde(flatten)]
32    pub corpus: FuzzCorpusConfig,
33    /// Path where fuzz failures are recorded and replayed.
34    pub failure_persist_dir: Option<PathBuf>,
35    /// show `console.log` in fuzz test, defaults to `false`
36    pub show_logs: bool,
37    /// Optional timeout (in seconds) for each property test
38    pub timeout: Option<u32>,
39}
40
41impl Default for FuzzConfig {
42    fn default() -> Self {
43        Self {
44            runs: 256,
45            run: None,
46            worker: None,
47            fail_on_revert: true,
48            max_test_rejects: 65536,
49            seed: None,
50            dictionary: FuzzDictionaryConfig::default(),
51            gas_report_samples: 256,
52            corpus: FuzzCorpusConfig { payable_value_weight: 0, ..Default::default() },
53            failure_persist_dir: None,
54            show_logs: false,
55            timeout: None,
56        }
57    }
58}
59
60impl FuzzConfig {
61    /// Creates fuzz configuration to write failures in `{PROJECT_ROOT}/cache/fuzz` dir.
62    pub fn new(cache_dir: PathBuf) -> Self {
63        Self { failure_persist_dir: Some(cache_dir), ..Default::default() }
64    }
65}
66
67/// Contains for fuzz testing
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
69pub struct FuzzDictionaryConfig {
70    /// The weight of the dictionary
71    #[serde(deserialize_with = "crate::deserialize_stringified_percent")]
72    pub dictionary_weight: u32,
73    /// The flag indicating whether to include values from storage
74    pub include_storage: bool,
75    /// The flag indicating whether to include push bytes values
76    pub include_push_bytes: bool,
77    /// The flag indicating whether invariant runs call targeted contracts' view functions (with
78    /// no inputs or only address inputs, bound to the sender) after each successful call that
79    /// accessed them, and add the results, whole structs included, to the dictionary. At most 32
80    /// views are called per call; when more are eligible, the selection rotates across calls.
81    pub include_view_values: bool,
82    /// How many addresses to record at most.
83    /// Once the fuzzer exceeds this limit, it will start evicting random entries
84    ///
85    /// This limit is put in place to prevent memory blowup.
86    #[serde(
87        deserialize_with = "crate::deserialize_usize_or_max",
88        serialize_with = "crate::serialize_usize_or_max"
89    )]
90    pub max_fuzz_dictionary_addresses: usize,
91    /// How many values to record at most.
92    /// Once the fuzzer exceeds this limit, it will start evicting random entries
93    /// The dictionary always retains a zero seed, so the effective minimum is one.
94    #[serde(
95        deserialize_with = "crate::deserialize_usize_or_max",
96        serialize_with = "crate::serialize_usize_or_max"
97    )]
98    pub max_fuzz_dictionary_values: usize,
99    /// How many literal values to seed from the AST, at most.
100    ///
101    /// This value is independent from the max amount of addresses and values.
102    #[serde(
103        deserialize_with = "crate::deserialize_usize_or_max",
104        serialize_with = "crate::serialize_usize_or_max"
105    )]
106    pub max_fuzz_dictionary_literals: usize,
107}
108
109impl Default for FuzzDictionaryConfig {
110    fn default() -> Self {
111        const MB: usize = 1024 * 1024;
112
113        Self {
114            dictionary_weight: 40,
115            include_storage: true,
116            include_push_bytes: true,
117            include_view_values: false,
118            max_fuzz_dictionary_addresses: 300 * MB / 20,
119            max_fuzz_dictionary_values: 300 * MB / 32,
120            max_fuzz_dictionary_literals: 200 * MB / 32,
121        }
122    }
123}
124
125#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
126pub struct FuzzCorpusConfig {
127    // Path to corpus directory, enabled coverage guided fuzzing mode.
128    // If not set then sequences producing new coverage are not persisted and mutated.
129    pub corpus_dir: Option<PathBuf>,
130    // Path to fuzz branch frontier artifacts for symbolic follow-up.
131    pub frontier_dir: Option<PathBuf>,
132    // Maximum number of branch frontier records to write for one fuzz test.
133    pub frontier_limit: usize,
134    // Whether corpus to use gzip file compression and decompression.
135    pub corpus_gzip: bool,
136    // Number of mutations until entry marked as eligible to be flushed from in-memory corpus.
137    // Mutations will be performed at least `corpus_min_mutations` times.
138    pub corpus_min_mutations: usize,
139    // Number of corpus that won't be evicted from memory.
140    pub corpus_min_size: usize,
141    /// Whether to collect and display edge coverage metrics.
142    pub show_edge_coverage: bool,
143    /// Whether EVM edge coverage should use collision-free dense IDs.
144    pub evm_edge_coverage_collision_free: bool,
145    /// Whether EVM edge coverage IDs should include call-frame depth.
146    pub evm_edge_coverage_include_call_depth: bool,
147    /// Whether to collect edge coverage from native Rust crates compiled with
148    /// SanitizerCoverage instrumentation (e.g. precompile implementations).
149    /// Requires building forge with a `RUSTC_WRAPPER` that injects sancov flags.
150    pub sancov_edges: bool,
151    /// Whether to capture comparison operands from sancov-instrumented crates
152    /// and inject them into the fuzz dictionary. Independent of `sancov_edges`.
153    pub sancov_trace_cmp: bool,
154    /// Whether EVM edge coverage comes from compiler instrumentation instead of the
155    /// `JUMP`/`JUMPI` edge inspector.
156    ///
157    /// Coverage builds of a compiler emit `PUSHn <id>; EDGECOV` (opcode `0xC0`) on every
158    /// control-flow edge, with dense IDs starting at 1. When enabled, the EVM executes that
159    /// opcode, which records a hit for the edge and costs no gas (it also refunds its `PUSH`),
160    /// and these hits replace the inspector's EVM edges as the corpus guidance signal.
161    /// Comparison operands then come from the compiler's `CMPLOG` (`0xC1`) probes instead of the
162    /// cmp-log inspector. Instrumented artifacts only run with this on: on any other EVM `0xC0`
163    /// and `0xC1` are undefined opcodes.
164    ///
165    /// Hits are keyed by ID alone, so IDs must be unique across all instrumented code: build it
166    /// in one compiler invocation.
167    pub instrumented_edges: bool,
168    /// Percent chance of generating fresh transaction input instead of continuing from corpus
169    /// input during coverage-guided campaigns.
170    #[serde(deserialize_with = "crate::deserialize_stringified_percent")]
171    pub corpus_random_sequence_weight: u32,
172    /// Percent chance that generated payable calls carry non-zero `msg.value`.
173    #[serde(deserialize_with = "crate::deserialize_stringified_percent")]
174    pub payable_value_weight: u32,
175    /// Weights for coverage-guided corpus mutation strategies.
176    #[serde(flatten)]
177    pub mutation_weights: FuzzCorpusMutationWeights,
178}
179
180impl FuzzCorpusConfig {
181    pub const DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT: u32 = 10;
182    pub const ENSEMBLE_CORPUS_RANDOM_SEQUENCE_WEIGHT: u32 = 50;
183    pub const DEFAULT_FRONTIER_LIMIT: usize = 256;
184
185    pub fn with_test(&mut self, contract: &str, test: &str) {
186        if let Some(corpus_dir) = &self.corpus_dir {
187            self.corpus_dir = Some(canonicalized(corpus_dir.join(contract).join(test)));
188        }
189        if let Some(frontier_dir) = &self.frontier_dir {
190            self.frontier_dir = Some(canonicalized(frontier_dir.join(contract).join(test)));
191        }
192    }
193
194    /// Whether any edge coverage (EVM, instrumented or sancov) should be collected.
195    pub const fn collect_edge_coverage(&self) -> bool {
196        self.corpus_dir.is_some()
197            || self.show_edge_coverage
198            || self.sancov_edges
199            || self.instrumented_edges
200    }
201
202    /// Whether the EVM `EdgeCovInspector` should be enabled.
203    ///
204    /// Disabled when sancov edge coverage is active — sancov provides the
205    /// coverage signal and EVM hits from the Solidity handler would dilute it.
206    /// Also disabled when instrumented edges are on, since compiler instrumentation then
207    /// provides the EVM edges.
208    /// Trace-cmp-only mode keeps EVM edges enabled since trace-cmp only
209    /// contributes dictionary entries, not edge coverage.
210    pub const fn collect_evm_edge_coverage(&self) -> bool {
211        !self.sancov_edges
212            && !self.instrumented_edges
213            && (self.corpus_dir.is_some() || self.show_edge_coverage)
214    }
215
216    /// Whether EVM edge coverage comes from the compiler-instrumented `EDGECOV` opcode.
217    pub const fn collect_instrumented_edges(&self) -> bool {
218        self.instrumented_edges
219    }
220
221    /// Whether EVM comparison operand capture is enabled.
222    ///
223    /// EVM comparison operands for corpus mutation are only useful for coverage-guided fuzzing, so
224    /// they are derived from corpus mode and disabled when sancov edge coverage is active.
225    /// Frontier capture still records EVM comparison sites because those artifacts target
226    /// Solidity bytecode branches, not the active coverage guidance source.
227    pub fn collect_evm_cmp_log(&self) -> bool {
228        self.capture_branch_frontiers()
229            || (!self.sancov_edges
230                && self.corpus_dir.is_some()
231                && self.mutation_weights.effective().mutation_weight_cmp > 0)
232    }
233
234    /// Whether fuzz branch frontier artifacts should be captured.
235    pub const fn capture_branch_frontiers(&self) -> bool {
236        self.frontier_dir.is_some() && self.frontier_limit > 0
237    }
238
239    /// Whether EVM edge coverage should use collision-free dense IDs.
240    pub const fn evm_edge_coverage_collision_free(&self) -> bool {
241        self.evm_edge_coverage_collision_free
242    }
243
244    /// Whether EVM edge coverage IDs should include call-frame depth.
245    pub const fn evm_edge_coverage_include_call_depth(&self) -> bool {
246        self.evm_edge_coverage_include_call_depth
247    }
248
249    /// Whether sancov edge coverage collection is enabled.
250    pub const fn collect_sancov_edges(&self) -> bool {
251        self.sancov_edges
252    }
253
254    /// Whether sancov trace-cmp capture is enabled.
255    pub const fn collect_sancov_trace_cmp(&self) -> bool {
256        self.sancov_trace_cmp
257    }
258
259    /// Whether either sancov coverage mode is active.
260    pub const fn sancov_active(&self) -> bool {
261        self.sancov_edges || self.sancov_trace_cmp
262    }
263
264    /// Whether coverage guided fuzzing is enabled.
265    pub const fn is_coverage_guided(&self) -> bool {
266        self.corpus_dir.is_some()
267    }
268}
269
270impl Default for FuzzCorpusConfig {
271    fn default() -> Self {
272        Self {
273            corpus_dir: None,
274            frontier_dir: None,
275            frontier_limit: Self::DEFAULT_FRONTIER_LIMIT,
276            corpus_gzip: true,
277            corpus_min_mutations: 5,
278            corpus_min_size: 0,
279            show_edge_coverage: false,
280            evm_edge_coverage_collision_free: true,
281            evm_edge_coverage_include_call_depth: false,
282            sancov_edges: false,
283            sancov_trace_cmp: false,
284            instrumented_edges: false,
285            corpus_random_sequence_weight: Self::DEFAULT_CORPUS_RANDOM_SEQUENCE_WEIGHT,
286            payable_value_weight: 15,
287            mutation_weights: FuzzCorpusMutationWeights::default(),
288        }
289    }
290}
291
292#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
293pub struct FuzzCorpusMutationWeights {
294    /// Weight for splicing two corpus sequences.
295    pub mutation_weight_splice: u32,
296    /// Weight for repeating part of a corpus sequence.
297    pub mutation_weight_repeat: u32,
298    /// Weight for interleaving two corpus sequences.
299    pub mutation_weight_interleave: u32,
300    /// Weight for replacing a corpus sequence prefix with generated calls.
301    pub mutation_weight_prefix: u32,
302    /// Weight for replacing a corpus sequence suffix with generated calls.
303    pub mutation_weight_suffix: u32,
304    /// Weight for ABI-aware argument mutation.
305    pub mutation_weight_abi: u32,
306    /// Weight for comparison-operand guided argument mutation.
307    pub mutation_weight_cmp: u32,
308}
309
310impl FuzzCorpusMutationWeights {
311    pub const fn total(&self) -> u64 {
312        self.mutation_weight_splice as u64
313            + self.mutation_weight_repeat as u64
314            + self.mutation_weight_interleave as u64
315            + self.mutation_weight_prefix as u64
316            + self.mutation_weight_suffix as u64
317            + self.mutation_weight_abi as u64
318            + self.mutation_weight_cmp as u64
319    }
320
321    /// Returns defaults if every configured weight is zero.
322    pub fn effective(self) -> Self {
323        if self.total() == 0 { Self::default() } else { self }
324    }
325}
326
327impl Default for FuzzCorpusMutationWeights {
328    fn default() -> Self {
329        Self {
330            mutation_weight_splice: 1,
331            mutation_weight_repeat: 1,
332            mutation_weight_interleave: 1,
333            mutation_weight_prefix: 1,
334            mutation_weight_suffix: 1,
335            mutation_weight_abi: 1,
336            mutation_weight_cmp: 1,
337        }
338    }
339}
340
341fn deserialize_fuzz_runs<'de, D>(deserializer: D) -> Result<u32, D::Error>
342where
343    D: Deserializer<'de>,
344{
345    let runs = u32::deserialize(deserializer)?;
346    if runs == 0 {
347        return Err(D::Error::custom("`fuzz.runs` must be greater than 0"));
348    }
349    Ok(runs)
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    #[test]
357    fn instrumented_edges_replace_evm_edge_coverage() {
358        let corpus = FuzzCorpusConfig {
359            corpus_dir: Some("corpus".into()),
360            instrumented_edges: true,
361            ..Default::default()
362        };
363        assert!(corpus.collect_edge_coverage());
364        assert!(corpus.collect_instrumented_edges());
365        assert!(!corpus.collect_evm_edge_coverage());
366        // Cmp-log is configured independently of the edge source.
367        assert!(corpus.collect_evm_cmp_log());
368
369        let default = FuzzCorpusConfig { corpus_dir: Some("corpus".into()), ..Default::default() };
370        assert!(!default.collect_instrumented_edges());
371        assert!(default.collect_evm_edge_coverage());
372    }
373}