1use 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
12pub enum InvariantWorkers {
13 #[default]
15 Auto,
16 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(rename_all = "snake_case")]
98pub enum InvariantDepthMode {
99 #[default]
101 Fixed,
102 #[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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
123pub struct InvariantConfig {
124 pub runs: u32,
126 pub depth: u32,
128 pub min_depth: u32,
130 pub depth_mode: InvariantDepthMode,
132 pub workers: InvariantWorkers,
137 pub fail_on_revert: bool,
139 pub call_override: bool,
142 #[serde(flatten)]
144 pub dictionary: FuzzDictionaryConfig,
145 pub shrink_run_limit: u32,
148 pub max_assume_rejects: u32,
151 pub gas_report_samples: u32,
153 #[serde(flatten)]
155 pub corpus: FuzzCorpusConfig,
156 #[serde(default, skip_serializing)]
158 #[doc(hidden)]
159 pub corpus_random_sequence_weight_configured: bool,
160 #[serde(default, skip_serializing)]
162 #[doc(hidden)]
163 pub workers_configured: bool,
164 pub failure_persist_dir: Option<PathBuf>,
166 pub show_metrics: bool,
168 pub timeout: Option<u32>,
171 pub show_solidity: bool,
173 pub max_time_delay: Option<u32>,
175 pub max_block_delay: Option<u32>,
177 pub check_interval: u32,
185 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 pub fn new(cache_dir: PathBuf) -> Self {
227 Self { failure_persist_dir: Some(cache_dir), ..Default::default() }
228 }
229
230 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}