Skip to main content

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