Skip to main content

sentri_dynamic_core/
lib.rs

1#![deny(unsafe_code)]
2#![allow(missing_docs)]
3
4//! Chain-agnostic dynamic/coverage-guided invariant fuzzing engine.
5//!
6//! This crate contains no VM: it only knows how to generate call
7//! sequences, drive an [`ExecutionBackend`], check [`Invariant`]s after
8//! every call, and shrink a failing sequence to a minimal reproduction.
9//! Chain-specific crates (starting with `sentri-dynamic-evm`, backed by
10//! `revm`) provide the [`ExecutionBackend`] implementation; this crate's
11//! own test suite proves the engine logic correct against an in-memory
12//! mock so it never depends on a real VM being available to be verified.
13
14pub mod abi_encode;
15pub mod backend;
16pub mod invariant;
17pub mod poc;
18pub mod sequence;
19pub mod shrink;
20pub mod trace;
21pub mod u256;
22
23#[cfg(test)]
24mod testing;
25
26pub use backend::{CallOutcome, EncodedCall, ExecutionBackend, FunctionSpec, ParamKind};
27pub use invariant::{
28    AccessControlInvariant, CheckContext, ConservationInvariant, Invariant, MonotonicInvariant,
29    ReentrancyInvariant,
30};
31pub use poc::format_poc;
32pub use sequence::{generate_random_sequence, run_sequence, CallSequence, Violation};
33pub use shrink::shrink;
34pub use trace::{detect_reentrancy, ReentrancyReport, TraceEvent};
35
36use rand::rngs::SmallRng;
37use rand::SeedableRng;
38
39/// Search parameters for a fuzzing run. `seed` makes runs reproducible —
40/// the same seed against the same contract always generates the same
41/// sequences, so a violation found once can be found again for debugging.
42#[derive(Debug, Clone)]
43pub struct FuzzConfig {
44    pub seed: u64,
45    pub max_runs: usize,
46    pub sequence_depth: usize,
47    pub actors: Vec<[u8; 20]>,
48}
49
50impl Default for FuzzConfig {
51    fn default() -> Self {
52        Self {
53            seed: 0,
54            max_runs: 500,
55            sequence_depth: 12,
56            actors: Vec::new(),
57        }
58    }
59}
60
61/// Run the search loop: generate random call sequences, execute each
62/// against a fresh backend instance, check invariants after every call,
63/// and on the first violation, shrink it to a minimal reproduction before
64/// returning.
65///
66/// `fresh_backend` is called once per attempt (and many more times during
67/// shrinking) — it must return a backend already in its genesis/deployed
68/// state, ready to receive calls. How "fresh" is produced (redeploy vs. a
69/// cheap in-memory state clone) is entirely the backend's concern.
70pub fn fuzz(
71    fresh_backend: impl Fn() -> Box<dyn ExecutionBackend>,
72    functions: &[FunctionSpec],
73    invariants: Vec<Box<dyn Invariant>>,
74    config: FuzzConfig,
75) -> Option<Violation> {
76    let mut rng = SmallRng::seed_from_u64(config.seed);
77
78    for _ in 0..config.max_runs {
79        let seq =
80            generate_random_sequence(&mut rng, functions, &config.actors, config.sequence_depth);
81        if seq.is_empty() {
82            continue;
83        }
84
85        let mut backend = fresh_backend();
86        let Some(violation) = run_sequence(backend.as_mut(), &seq, &invariants) else {
87            continue;
88        };
89
90        let shrunk = shrink(&fresh_backend, &violation.sequence, &invariants);
91        let mut replay_backend = fresh_backend();
92        // Re-run the shrunk sequence to get a Violation object whose
93        // `sequence` field matches what shrink actually produced — `shrink`
94        // itself only returns the CallSequence, not a fresh Violation.
95        return Some(
96            run_sequence(replay_backend.as_mut(), &shrunk, &invariants).unwrap_or(violation),
97        );
98    }
99    None
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use crate::testing::{self, MockBackend};
106
107    #[test]
108    fn catches_monotonic_violation_and_shrinks_it() {
109        let functions = testing::counter_functions();
110        let value_fn = functions
111            .iter()
112            .find(|f| f.selector == testing::VALUE)
113            .unwrap()
114            .clone();
115        let invariants: Vec<Box<dyn Invariant>> =
116            vec![Box::new(MonotonicInvariant::new("counter value", value_fn))];
117
118        let config = FuzzConfig {
119            seed: 7,
120            max_runs: 200,
121            sequence_depth: 8,
122            actors: vec![[1u8; 20]],
123        };
124
125        let violation = fuzz(
126            || Box::new(MockBackend::default()),
127            &functions,
128            invariants,
129            config,
130        )
131        .expect("MockBackend's decrement() is a real bug — the fuzzer must find it");
132
133        assert_eq!(violation.invariant_name, "counter value");
134        assert!(
135            violation.sequence.len() <= 3,
136            "expected shrinking to collapse this down to a handful of calls, got {}",
137            violation.sequence.len()
138        );
139        // The shrunk reproduction must still actually reproduce when replayed.
140        let mut replay = MockBackend::default();
141        let invariants: Vec<Box<dyn Invariant>> = vec![Box::new(MonotonicInvariant::new(
142            "counter value",
143            testing::counter_functions()
144                .into_iter()
145                .find(|f| f.selector == testing::VALUE)
146                .unwrap(),
147        ))];
148        assert!(run_sequence(&mut replay, &violation.sequence, &invariants).is_some());
149    }
150
151    #[test]
152    fn catches_conservation_violation() {
153        let functions = testing::token_functions();
154        let total_supply_fn = functions
155            .iter()
156            .find(|f| f.selector == testing::TOTAL_SUPPLY)
157            .unwrap()
158            .clone();
159        let balance_of_fn = functions
160            .iter()
161            .find(|f| f.selector == testing::BALANCE_OF)
162            .unwrap()
163            .clone();
164        let actors = vec![[1u8; 20], [2u8; 20], [3u8; 20]];
165        let invariants: Vec<Box<dyn Invariant>> = vec![Box::new(ConservationInvariant::new(
166            "token conservation",
167            total_supply_fn,
168            balance_of_fn,
169            actors.clone(),
170        ))];
171
172        let config = FuzzConfig {
173            seed: 99,
174            max_runs: 300,
175            sequence_depth: 8,
176            actors,
177        };
178
179        let violation = fuzz(
180            || Box::new(MockBackend::default()),
181            &functions,
182            invariants,
183            config,
184        )
185        .expect("MockBackend's buggyCredit() breaks conservation — the fuzzer must find it");
186
187        assert_eq!(violation.invariant_name, "token conservation");
188        assert!(violation.message.contains("sum(balanceOf)"));
189    }
190
191    #[test]
192    fn no_violation_when_only_the_safe_function_is_available() {
193        // Sanity check against false positives: a run that can only call
194        // the correct `mint` (never the buggy credit path) must never
195        // report a conservation violation.
196        let mint_only = vec![testing::token_functions()
197            .into_iter()
198            .find(|f| f.selector == testing::MINT)
199            .unwrap()];
200        let mut all = mint_only;
201        all.push(
202            testing::token_functions()
203                .into_iter()
204                .find(|f| f.selector == testing::TOTAL_SUPPLY)
205                .unwrap(),
206        );
207        all.push(
208            testing::token_functions()
209                .into_iter()
210                .find(|f| f.selector == testing::BALANCE_OF)
211                .unwrap(),
212        );
213
214        let total_supply_fn = all
215            .iter()
216            .find(|f| f.selector == testing::TOTAL_SUPPLY)
217            .unwrap()
218            .clone();
219        let balance_of_fn = all
220            .iter()
221            .find(|f| f.selector == testing::BALANCE_OF)
222            .unwrap()
223            .clone();
224        let actors = vec![[1u8; 20], [2u8; 20]];
225        let invariants: Vec<Box<dyn Invariant>> = vec![Box::new(ConservationInvariant::new(
226            "token conservation",
227            total_supply_fn,
228            balance_of_fn,
229            actors.clone(),
230        ))];
231
232        let config = FuzzConfig {
233            seed: 5,
234            max_runs: 150,
235            sequence_depth: 8,
236            actors,
237        };
238
239        let result = fuzz(
240            || Box::new(MockBackend::default()),
241            &all,
242            invariants,
243            config,
244        );
245        assert!(
246            result.is_none(),
247            "mint-only sequences must never violate conservation"
248        );
249    }
250
251    #[test]
252    fn catches_access_control_violation() {
253        let functions = testing::ownable_functions();
254        let owner_fn = functions
255            .iter()
256            .find(|f| f.selector == testing::OWNER)
257            .unwrap()
258            .clone();
259        let transfer_fn = functions
260            .iter()
261            .find(|f| f.selector == testing::TRANSFER_OWNERSHIP)
262            .unwrap()
263            .clone();
264
265        let invariants: Vec<Box<dyn Invariant>> = vec![Box::new(AccessControlInvariant::new(
266            "ownership transfer authorization",
267            owner_fn,
268            transfer_fn,
269        ))];
270
271        // Actor pool deliberately excludes testing::GENESIS_OWNER, so any
272        // successful transferOwnership in this run is necessarily from a
273        // non-owner — MockBackend's TRANSFER_OWNERSHIP has no caller check
274        // at all, so this must always find a violation.
275        let config = FuzzConfig {
276            seed: 3,
277            max_runs: 50,
278            sequence_depth: 4,
279            actors: vec![[1u8; 20], [2u8; 20]],
280        };
281
282        let violation = fuzz(
283            || Box::new(MockBackend::default()),
284            &functions,
285            invariants,
286            config,
287        )
288        .expect("MockBackend's transferOwnership has no caller check — the fuzzer must find it");
289
290        assert_eq!(violation.invariant_name, "ownership transfer authorization");
291        assert!(violation.message.contains("non-owner"));
292    }
293
294    #[test]
295    fn no_false_positive_when_ownership_transfer_is_actually_guarded() {
296        let functions = testing::ownable_functions_safe();
297        let owner_fn = functions
298            .iter()
299            .find(|f| f.selector == testing::OWNER)
300            .unwrap()
301            .clone();
302        let transfer_fn = functions
303            .iter()
304            .find(|f| f.selector == testing::SAFE_TRANSFER_OWNERSHIP)
305            .unwrap()
306            .clone();
307
308        let invariants: Vec<Box<dyn Invariant>> = vec![Box::new(AccessControlInvariant::new(
309            "ownership transfer authorization",
310            owner_fn,
311            transfer_fn,
312        ))];
313
314        let config = FuzzConfig {
315            seed: 11,
316            max_runs: 150,
317            sequence_depth: 6,
318            actors: vec![[1u8; 20], [2u8; 20]],
319        };
320
321        let result = fuzz(
322            || Box::new(MockBackend::default()),
323            &functions,
324            invariants,
325            config,
326        );
327        assert!(
328            result.is_none(),
329            "a correctly owner-gated transferOwnership must never be flagged"
330        );
331    }
332
333    #[test]
334    fn catches_reentrancy_from_the_call_trace() {
335        let functions = testing::vault_functions_vulnerable();
336        let invariants: Vec<Box<dyn Invariant>> =
337            vec![Box::new(ReentrancyInvariant::new("reentrancy"))];
338
339        let config = FuzzConfig {
340            seed: 1,
341            max_runs: 20,
342            sequence_depth: 3,
343            actors: vec![[1u8; 20], [2u8; 20]],
344        };
345
346        let violation = fuzz(
347            || Box::new(MockBackend::default()),
348            &functions,
349            invariants,
350            config,
351        )
352        .expect("the vulnerable withdraw's trace shows exploitable reentrancy — must be caught");
353
354        assert_eq!(violation.invariant_name, "reentrancy");
355        assert!(violation.message.contains("re-entered"));
356    }
357
358    #[test]
359    fn no_reentrancy_false_positive_on_guarded_or_cei_vaults() {
360        let functions = testing::vault_functions_safe();
361        let invariants: Vec<Box<dyn Invariant>> =
362            vec![Box::new(ReentrancyInvariant::new("reentrancy"))];
363
364        let config = FuzzConfig {
365            seed: 4,
366            max_runs: 200,
367            sequence_depth: 6,
368            actors: vec![[1u8; 20], [2u8; 20]],
369        };
370
371        let result = fuzz(
372            || Box::new(MockBackend::default()),
373            &functions,
374            invariants,
375            config,
376        );
377        assert!(
378            result.is_none(),
379            "guarded and CEI-correct withdraws must never be flagged as reentrancy"
380        );
381    }
382}