Skip to main content

foundry_config/
invariant.rs

1//! Configuration for invariant testing
2
3use crate::fuzz::{FuzzCorpusConfig, FuzzDictionaryConfig};
4use serde::{
5    Deserialize, Deserializer, Serialize, Serializer,
6    de::{Error, Visitor},
7};
8use std::{fmt, num::NonZeroUsize, path::PathBuf, str::FromStr};
9
10/// Worker selection mode for invariant campaign sharding.
11#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12pub enum InvariantWorkers {
13    /// Automatically derive invariant workers from the active `--jobs` / rayon thread pool.
14    #[default]
15    Auto,
16    /// Explicit user override for invariant campaign sharding.
17    Fixed(NonZeroUsize),
18}
19
20impl Serialize for InvariantWorkers {
21    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
22    where
23        S: Serializer,
24    {
25        match self {
26            Self::Auto => serializer.serialize_str("auto"),
27            Self::Fixed(workers) => workers.get().serialize(serializer),
28        }
29    }
30}
31
32impl<'de> Deserialize<'de> for InvariantWorkers {
33    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
34    where
35        D: Deserializer<'de>,
36    {
37        deserializer.deserialize_any(InvariantWorkersVisitor)
38    }
39}
40
41impl FromStr for InvariantWorkers {
42    type Err = String;
43
44    fn from_str(value: &str) -> Result<Self, Self::Err> {
45        let value = value.trim();
46        if value.eq_ignore_ascii_case("auto") {
47            return Ok(Self::Auto);
48        }
49
50        let workers = value.parse::<usize>().map_err(|err| err.to_string())?;
51        fixed_workers(workers)
52    }
53}
54
55struct InvariantWorkersVisitor;
56
57impl Visitor<'_> for InvariantWorkersVisitor {
58    type Value = InvariantWorkers;
59
60    fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
61        formatter.write_str("`auto` or a positive integer worker count")
62    }
63
64    fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
65    where
66        E: Error,
67    {
68        value.parse().map_err(E::custom)
69    }
70
71    fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
72    where
73        E: Error,
74    {
75        let workers = usize::try_from(value).map_err(E::custom)?;
76        fixed_workers(workers).map_err(E::custom)
77    }
78
79    fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
80    where
81        E: Error,
82    {
83        let workers =
84            usize::try_from(value).map_err(|_| E::custom("invariant workers must be positive"))?;
85        fixed_workers(workers).map_err(E::custom)
86    }
87}
88
89fn fixed_workers(workers: usize) -> Result<InvariantWorkers, String> {
90    NonZeroUsize::new(workers)
91        .map(InvariantWorkers::Fixed)
92        .ok_or_else(|| "invariant workers must be greater than 0".to_string())
93}
94
95/// Per-run invariant depth selection mode.
96#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(rename_all = "snake_case")]
98pub enum InvariantDepthMode {
99    /// Execute every invariant run up to the configured `depth`.
100    #[default]
101    Fixed,
102    /// Sample every invariant run depth uniformly between `min_depth` and `depth`.
103    #[serde(alias = "uniform")]
104    Random,
105}
106
107impl FromStr for InvariantDepthMode {
108    type Err = String;
109
110    fn from_str(value: &str) -> Result<Self, Self::Err> {
111        match value.trim().to_ascii_lowercase().as_str() {
112            "fixed" => Ok(Self::Fixed),
113            "random" | "uniform" => Ok(Self::Random),
114            value => {
115                Err(format!("unknown invariant depth mode `{value}`, expected `fixed` or `random`"))
116            }
117        }
118    }
119}
120
121/// Contains for invariant testing
122#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
123pub struct InvariantConfig {
124    /// The number of runs that must execute for each invariant test group.
125    pub runs: u32,
126    /// The number of calls executed to attempt to break invariants in one run.
127    pub depth: u32,
128    /// Minimum sampled run depth when `depth_mode = "random"`.
129    pub min_depth: u32,
130    /// How to choose the effective depth for each invariant run.
131    pub depth_mode: InvariantDepthMode,
132    /// Worker selection mode used to shard invariant runs.
133    ///
134    /// Defaults to `auto`, which derives the worker count from `--jobs`. Use a positive integer
135    /// for an explicit worker count.
136    pub workers: InvariantWorkers,
137    /// Fails the invariant fuzzing if a revert occurs
138    pub fail_on_revert: bool,
139    /// Allows overriding an unsafe external call when running invariant tests. eg. reentrancy
140    /// checks
141    pub call_override: bool,
142    /// The fuzz dictionary configuration
143    #[serde(flatten)]
144    pub dictionary: FuzzDictionaryConfig,
145    /// The maximum number of attempts to shrink the sequence, also used to minimize the argument
146    /// values of stateless fuzz counterexamples.
147    pub shrink_run_limit: u32,
148    /// The maximum number of rejects via `vm.assume` which can be encountered during a single
149    /// invariant run.
150    pub max_assume_rejects: u32,
151    /// Number of runs to execute and include in the gas report.
152    pub gas_report_samples: u32,
153    /// The fuzz corpus configuration.
154    #[serde(flatten)]
155    pub corpus: FuzzCorpusConfig,
156    /// Whether `corpus_random_sequence_weight` was supplied by a config provider.
157    #[serde(default, skip_serializing)]
158    #[doc(hidden)]
159    pub corpus_random_sequence_weight_configured: bool,
160    /// Whether `workers` was supplied by a config provider.
161    #[serde(default, skip_serializing)]
162    #[doc(hidden)]
163    pub workers_configured: bool,
164    /// Path where invariant failures are recorded and replayed.
165    pub failure_persist_dir: Option<PathBuf>,
166    /// Whether to collect and display fuzzed selectors metrics.
167    pub show_metrics: bool,
168    /// Optional campaign-global timeout (in seconds) for each invariant test. Shrinking the
169    /// failures of a timed test stops at most `timeout` seconds after the campaign deadline.
170    pub timeout: Option<u32>,
171    /// Display counterexample as solidity calls.
172    pub show_solidity: bool,
173    /// Maximum time (in seconds) between generated txs.
174    pub max_time_delay: Option<u32>,
175    /// Maximum number of blocks elapsed between generated txs.
176    pub max_block_delay: Option<u32>,
177    /// Number of calls to execute between invariant assertions.
178    ///
179    /// - `0`: Only assert on the last call of each run (fastest, but may miss exact breaking call)
180    /// - `1` (default): Assert after every call (current behavior, most precise)
181    /// - `N`: Assert every N calls AND always on the last call
182    ///
183    /// Example: `check_interval = 10` means assert after calls 10, 20, 30, ... and the last call.
184    pub check_interval: u32,
185    /// Gas limit for every campaign call after `setUp` and target selection: handler calls,
186    /// invariant checks, `afterInvariant`, and their replays and shrinks.
187    ///
188    /// Unset keeps the project `gas_limit`; a larger value has no effect. A handler call whose
189    /// minimum gas is above the limit runs with that minimum instead. At the intrinsic charge,
190    /// network charges included, it has no gas left and reverts. At an EIP-7623 calldata floor
191    /// above the intrinsic charge, it keeps the difference and can still run.
192    pub call_gas_limit: Option<u64>,
193}
194
195impl Default for InvariantConfig {
196    fn default() -> Self {
197        Self {
198            runs: 256,
199            depth: 500,
200            min_depth: 1,
201            depth_mode: InvariantDepthMode::default(),
202            workers: InvariantWorkers::default(),
203            fail_on_revert: false,
204            call_override: false,
205            dictionary: FuzzDictionaryConfig { dictionary_weight: 80, ..Default::default() },
206            shrink_run_limit: 5000,
207            max_assume_rejects: 65536,
208            gas_report_samples: 256,
209            corpus: FuzzCorpusConfig::default(),
210            corpus_random_sequence_weight_configured: false,
211            workers_configured: false,
212            failure_persist_dir: None,
213            show_metrics: true,
214            timeout: None,
215            show_solidity: false,
216            max_time_delay: None,
217            max_block_delay: None,
218            check_interval: 1,
219            call_gas_limit: None,
220        }
221    }
222}
223
224impl InvariantConfig {
225    /// Creates invariant configuration to write failures in `{PROJECT_ROOT}/cache/fuzz` dir.
226    pub fn new(cache_dir: PathBuf) -> Self {
227        Self { failure_persist_dir: Some(cache_dir), ..Default::default() }
228    }
229
230    /// Returns true if generated invariant calls may advance block time or height.
231    pub const fn has_delay(&self) -> bool {
232        matches!(self.max_block_delay, Some(delay) if delay > 0)
233            || matches!(self.max_time_delay, Some(delay) if delay > 0)
234    }
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    #[test]
242    fn invariant_workers_accept_auto_and_fixed_counts() {
243        assert_eq!("AUTO".parse::<InvariantWorkers>().unwrap(), InvariantWorkers::Auto);
244        assert_eq!(
245            serde_json::from_str::<InvariantWorkers>(r#""auto""#).unwrap(),
246            InvariantWorkers::Auto
247        );
248        assert_eq!(
249            serde_json::from_str::<InvariantWorkers>(r#"4"#).unwrap(),
250            InvariantWorkers::Fixed(NonZeroUsize::new(4).unwrap())
251        );
252        assert_eq!(
253            serde_json::from_str::<InvariantWorkers>(r#""4""#).unwrap(),
254            InvariantWorkers::Fixed(NonZeroUsize::new(4).unwrap())
255        );
256    }
257
258    #[test]
259    fn invariant_workers_default_to_auto() {
260        assert_eq!(InvariantWorkers::default(), InvariantWorkers::Auto);
261        assert_eq!(InvariantConfig::default().workers, InvariantWorkers::Auto);
262    }
263
264    #[test]
265    fn invariant_workers_reject_zero() {
266        let err = serde_json::from_str::<InvariantWorkers>(r#"0"#).unwrap_err();
267        assert!(err.to_string().contains("greater than 0"));
268    }
269
270    #[test]
271    fn invariant_config_zero_delays_are_disabled() {
272        let mut config = InvariantConfig { max_block_delay: Some(0), ..Default::default() };
273        assert!(!config.has_delay());
274
275        config.max_block_delay = None;
276        config.max_time_delay = Some(0);
277        assert!(!config.has_delay());
278
279        config.max_time_delay = Some(1);
280        assert!(config.has_delay());
281    }
282
283    #[test]
284    fn invariant_config_equality_includes_corpus_random_sequence_provenance() {
285        let explicit = InvariantConfig {
286            corpus_random_sequence_weight_configured: true,
287            ..InvariantConfig::default()
288        };
289
290        assert_ne!(InvariantConfig::default(), explicit);
291    }
292
293    #[test]
294    fn invariant_depth_mode_accepts_fixed_and_random() {
295        assert_eq!("fixed".parse::<InvariantDepthMode>().unwrap(), InvariantDepthMode::Fixed);
296        assert_eq!("uniform".parse::<InvariantDepthMode>().unwrap(), InvariantDepthMode::Random);
297        assert_eq!(
298            serde_json::from_str::<InvariantDepthMode>(r#""random""#).unwrap(),
299            InvariantDepthMode::Random
300        );
301        assert_eq!(
302            serde_json::from_str::<InvariantDepthMode>(r#""uniform""#).unwrap(),
303            InvariantDepthMode::Random
304        );
305    }
306}