Skip to main content

sentri_dynamic_evm/
lib.rs

1#![deny(unsafe_code)]
2#![allow(missing_docs)]
3
4//! revm-backed dynamic invariant fuzzing for EVM/Solidity contracts.
5//!
6//! Ties three things together: `sentri_utils::SolcManager` (compiles
7//! source, already existed), `solc_bridge` (turns its ABI/bytecode output
8//! into the chain-agnostic shapes `sentri-dynamic-core` understands), and
9//! `backend::RevmBackend` (executes calls against real EVM bytecode via
10//! `revm`, gated behind the `revm-backend` feature — see that module's doc
11//! comment for why it's split out and what's unverified about it).
12
13#[cfg(feature = "revm-backend")]
14pub mod backend;
15#[cfg(feature = "revm-backend")]
16pub mod reentrancy_inspector;
17pub mod rpc;
18pub mod solc_bridge;
19pub mod types;
20pub mod well_known_selectors;
21
22pub use types::CompiledContract;
23
24#[cfg(feature = "revm-backend")]
25use sentri_dynamic_core::{fuzz, FuzzConfig, Violation};
26use sentri_dynamic_core::{FunctionSpec, Invariant};
27
28/// Auto-detects standard invariants from a contract's function surface:
29/// currently, ERC20-shaped conservation (`totalSupply()` + `balanceOf(address)`
30/// both present) and monotonicity for any no-argument view function whose
31/// name suggests an accumulator (`totalSupply`, `totalAssets`,
32/// `exchangeRate`, `sharePrice`, cumulative/checkpoint-style getters).
33/// Returns an empty list if nothing recognizable is present — dynamic
34/// fuzzing without an oracle can't find anything, so callers should treat
35/// an empty result as "nothing to check yet", not "contract is safe".
36///
37/// Pure data in, data out — doesn't touch `revm`, so unlike the rest of
38/// this crate it's built and tested unconditionally (see the tests module
39/// below), not gated behind the `revm-backend` feature.
40pub fn auto_detect_invariants(
41    functions: &[FunctionSpec],
42    actors: &[[u8; 20]],
43) -> Vec<Box<dyn Invariant>> {
44    use sentri_dynamic_core::{
45        AccessControlInvariant, ConservationInvariant, MonotonicInvariant, ParamKind,
46    };
47
48    let mut invariants: Vec<Box<dyn Invariant>> = Vec::new();
49
50    let total_supply = functions
51        .iter()
52        .find(|f| f.name == "totalSupply" && f.inputs.is_empty());
53    let balance_of = functions
54        .iter()
55        .find(|f| f.name == "balanceOf" && f.inputs.len() == 1);
56    if let (Some(ts), Some(bo)) = (total_supply, balance_of) {
57        invariants.push(Box::new(ConservationInvariant::new(
58            "ERC20 conservation: sum(balanceOf) == totalSupply()",
59            ts.clone(),
60            bo.clone(),
61            actors.to_vec(),
62        )));
63    }
64
65    // OpenZeppelin-Ownable-shaped: owner() view + a single-address mutating
66    // setter conventionally named transferOwnership. Every real-world
67    // Ownable clone uses that exact selector, so matching on the name
68    // (rather than trying to infer "this is the privileged setter" from
69    // shape alone, which would be far too broad) keeps false positives
70    // near zero while still catching the single most common real
71    // access-control bug: a transferOwnership that forgot onlyOwner.
72    let owner_fn = functions
73        .iter()
74        .find(|f| f.name == "owner" && f.inputs.is_empty());
75    let transfer_ownership_fn = functions
76        .iter()
77        .find(|f| f.name == "transferOwnership" && f.inputs == vec![ParamKind::Address]);
78    if let (Some(owner_fn), Some(transfer_fn)) = (owner_fn, transfer_ownership_fn) {
79        invariants.push(Box::new(AccessControlInvariant::new(
80            "transferOwnership authorization",
81            owner_fn.clone(),
82            transfer_fn.clone(),
83        )));
84    }
85
86    const MONOTONIC_NAME_HINTS: &[&str] = &[
87        "totalSupply",
88        "totalAssets",
89        "exchangeRate",
90        "sharePrice",
91        "totalDeposits",
92        "checkpoint",
93        "cumulative",
94    ];
95    for f in functions {
96        if f.mutates_state || !f.inputs.is_empty() {
97            continue;
98        }
99        let lower = f.name.to_lowercase();
100        if MONOTONIC_NAME_HINTS
101            .iter()
102            .any(|hint| lower.contains(hint.to_lowercase().as_str()))
103        {
104            invariants.push(Box::new(MonotonicInvariant::new(
105                format!("{} monotonicity", f.name),
106                f.clone(),
107            )));
108        }
109    }
110
111    invariants
112}
113
114/// Compiles `source` with `solc`, auto-detects invariants from its ABI, and
115/// runs the dynamic fuzzer against it. Returns `Ok(None)` if no violation
116/// was found within the configured search budget, `Ok(Some(violation))`
117/// with a minimal reproduction if one was, and `Err` for compilation
118/// failures.
119#[cfg(feature = "revm-backend")]
120pub fn fuzz_solidity_source(source: &str, config: FuzzConfig) -> anyhow::Result<Option<Violation>> {
121    let solc = sentri_utils::SolcManager::new()?;
122    let output = solc.get_ast_for_source(source, "fuzz_target.sol")?;
123
124    let Some((_, contract_json)) = output.contracts.iter().find(|(_, v)| {
125        v.get("bin")
126            .and_then(|b| b.as_str())
127            .map(|b| !b.trim_start_matches("0x").is_empty())
128            .unwrap_or(false)
129    }) else {
130        anyhow::bail!("no deployable contract found in source (no non-empty bytecode — is this an interface/abstract contract?)");
131    };
132
133    let contract = solc_bridge::compiled_contract_from_solc_entry(contract_json)?;
134    if contract.functions.is_empty() {
135        anyhow::bail!("compiled successfully but no callable functions with supported argument types were found");
136    }
137
138    let invariants = auto_detect_invariants(&contract.functions, &config.actors);
139    if invariants.is_empty() {
140        anyhow::bail!(
141            "no auto-detectable invariant on this ABI (looked for ERC20-shaped totalSupply/balanceOf, or monotonic accumulator getters) — nothing to check"
142        );
143    }
144
145    // `backend_factory` borrows `actors` for as long as the returned
146    // closure lives; `config` is about to be moved into `fuzz` below, so
147    // the factory needs its own copy rather than borrowing config.actors
148    // directly (a borrow of config.actors can't outlive config itself
149    // being consumed in the very same call).
150    let actors = config.actors.clone();
151    let factory = backend::backend_factory(&contract, &actors);
152    Ok(fuzz(factory, &contract.functions, invariants, config))
153}
154
155/// Probes already-deployed runtime bytecode (no ABI available — the common
156/// case for an unverified contract, a realistic real-world bug-bounty
157/// target) against a fixed list of well-known ERC20/Ownable selectors,
158/// keeping only the ones that don't revert. The same "read as proxy"
159/// technique block explorers use for unverified contracts. Not a complete
160/// function-discovery mechanism — it only knows about the selectors it's
161/// told to try — but enough to drive [`auto_detect_invariants`] against a
162/// contract with zero source available.
163#[cfg(feature = "revm-backend")]
164pub fn probe_deployed_contract(bytecode: Vec<u8>, contract_address: [u8; 20]) -> Vec<FunctionSpec> {
165    use sentri_dynamic_core::EncodedCall;
166    use well_known_selectors::{
167        erc20_mutator_functions, erc20_probe_functions, ownable_mutator_functions,
168        ownable_probe_functions,
169    };
170
171    fn all_probes_succeed(
172        backend: &mut dyn sentri_dynamic_core::ExecutionBackend,
173        caller: [u8; 20],
174        fns: &[FunctionSpec],
175    ) -> bool {
176        fns.iter().all(|f| {
177            let mut calldata = f.selector.to_vec();
178            // Zero-fill one 32-byte word per argument (probing with default
179            // args; we only care whether the selector exists, i.e. doesn't
180            // revert on an unknown-function dispatch).
181            calldata.resize(4 + 32 * f.inputs.len(), 0u8);
182            let outcome = backend.call(&EncodedCall {
183                function: f.clone(),
184                calldata,
185                caller,
186                value: 0,
187            });
188            !outcome.reverted
189        })
190    }
191
192    let mut backend = backend::RevmBackend::from_runtime_bytecode(bytecode, contract_address);
193    let probe_caller = [0xEEu8; 20];
194    let mut confirmed = Vec::new();
195
196    let erc20_read = erc20_probe_functions();
197    if all_probes_succeed(&mut backend, probe_caller, &erc20_read) {
198        confirmed.extend(erc20_read);
199        confirmed.extend(erc20_mutator_functions());
200    }
201
202    let ownable_read = ownable_probe_functions();
203    if all_probes_succeed(&mut backend, probe_caller, &ownable_read) {
204        confirmed.extend(ownable_read);
205        confirmed.extend(ownable_mutator_functions());
206    }
207
208    confirmed
209}
210
211/// Fetches deployed bytecode from `rpc_url` for `contract_address`, probes
212/// it against known selectors (see [`probe_deployed_contract`]),
213/// auto-detects invariants from whatever's confirmed present, and runs the
214/// dynamic fuzzer against it — the no-source-available counterpart to
215/// [`fuzz_solidity_source`].
216///
217/// This does **not** fork the contract's real on-chain storage — only its
218/// code is fetched and deployed into an otherwise-empty account. That's
219/// enough to exercise bugs in the contract's own accounting logic (exactly
220/// what `ConservationInvariant`/`AccessControlInvariant` check), but any
221/// behavior depending on pre-existing on-chain storage (existing balances,
222/// addresses of other contracts read from storage, etc.) won't be
223/// reproduced faithfully. Full state forking is a larger feature this
224/// intentionally doesn't attempt yet.
225#[cfg(feature = "revm-backend")]
226pub fn fuzz_deployed_contract(
227    rpc_url: &str,
228    contract_address: [u8; 20],
229    config: FuzzConfig,
230) -> anyhow::Result<Option<Violation>> {
231    let bytecode = crate::rpc::fetch_bytecode(rpc_url, contract_address)?;
232    if bytecode.is_empty() {
233        anyhow::bail!("no code deployed at this address (per eth_getCode) — nothing to fuzz");
234    }
235
236    let functions = probe_deployed_contract(bytecode.clone(), contract_address);
237    if functions.is_empty() {
238        anyhow::bail!(
239            "deployed bytecode didn't respond successfully to any known ERC20/Ownable probe selectors — no auto-detectable surface to fuzz"
240        );
241    }
242
243    let invariants = auto_detect_invariants(&functions, &config.actors);
244    if invariants.is_empty() {
245        anyhow::bail!("probed functions present, but no auto-detectable invariant on this surface");
246    }
247
248    let actors = config.actors.clone();
249    let fresh_backend = move || -> Box<dyn sentri_dynamic_core::ExecutionBackend> {
250        let mut backend =
251            backend::RevmBackend::from_runtime_bytecode(bytecode.clone(), contract_address);
252        backend.fund_actors(&actors);
253        Box::new(backend)
254    };
255
256    Ok(fuzz(fresh_backend, &functions, invariants, config))
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262    use sentri_dynamic_core::ParamKind;
263
264    fn view_fn(name: &str, inputs: Vec<ParamKind>) -> FunctionSpec {
265        FunctionSpec::new(name, [0u8; 4], inputs, false)
266    }
267
268    #[test]
269    fn detects_erc20_conservation_when_both_functions_present() {
270        let functions = vec![
271            view_fn("totalSupply", vec![]),
272            view_fn("balanceOf", vec![ParamKind::Address]),
273        ];
274        let invariants = auto_detect_invariants(&functions, &[[1u8; 20]]);
275        assert!(invariants.iter().any(|i| i.name().contains("conservation")));
276    }
277
278    #[test]
279    fn skips_conservation_when_only_one_of_the_pair_is_present() {
280        let functions = vec![view_fn("totalSupply", vec![])];
281        let invariants = auto_detect_invariants(&functions, &[[1u8; 20]]);
282        assert!(!invariants.iter().any(|i| i.name().contains("conservation")));
283    }
284
285    #[test]
286    fn detects_monotonic_hints_case_insensitively() {
287        let functions = vec![view_fn("TotalAssets", vec![])];
288        let invariants = auto_detect_invariants(&functions, &[]);
289        assert!(invariants.iter().any(|i| i.name().contains("monotonicity")));
290    }
291
292    #[test]
293    fn ignores_mutating_functions_and_functions_with_arguments_for_monotonic_hints() {
294        let functions = vec![
295            FunctionSpec::new("totalAssets", [0u8; 4], vec![], true), // mutates -> not a getter
296            view_fn("checkpointFor", vec![ParamKind::Address]), // takes args -> not a plain accumulator getter
297        ];
298        let invariants = auto_detect_invariants(&functions, &[]);
299        assert!(invariants.is_empty());
300    }
301
302    #[test]
303    fn returns_empty_on_unrecognized_abi() {
304        let functions = vec![view_fn("frobnicate", vec![])];
305        assert!(auto_detect_invariants(&functions, &[]).is_empty());
306    }
307
308    #[test]
309    fn detects_ownable_access_control_when_both_functions_present() {
310        let functions = vec![
311            view_fn("owner", vec![]),
312            FunctionSpec::new(
313                "transferOwnership",
314                [0u8; 4],
315                vec![ParamKind::Address],
316                true,
317            ),
318        ];
319        let invariants = auto_detect_invariants(&functions, &[]);
320        assert!(invariants
321            .iter()
322            .any(|i| i.name().contains("transferOwnership authorization")));
323    }
324
325    #[test]
326    fn skips_access_control_when_transfer_ownership_takes_the_wrong_args() {
327        // A same-named function with a different signature (e.g. a
328        // two-step transferOwnership(address,bool) variant) shouldn't be
329        // matched — the invariant's caller-comparison logic specifically
330        // assumes a single address argument.
331        let functions = vec![
332            view_fn("owner", vec![]),
333            FunctionSpec::new(
334                "transferOwnership",
335                [0u8; 4],
336                vec![ParamKind::Address, ParamKind::Bool],
337                true,
338            ),
339        ];
340        assert!(auto_detect_invariants(&functions, &[]).is_empty());
341    }
342
343    #[test]
344    fn skips_access_control_when_only_owner_is_present() {
345        let functions = vec![view_fn("owner", vec![])];
346        assert!(auto_detect_invariants(&functions, &[]).is_empty());
347    }
348}
349
350/// The one thing none of the offline tests elsewhere in this workspace can
351/// prove: that the *real* revm/solc pipeline — actual compiled bytecode,
352/// actual EVM execution — catches a real bug, not just that it type-checks
353/// (see this module's doc comment history for why that was previously the
354/// open question). Needs solc, auto-downloaded by `SolcManager` if not
355/// already present, and therefore network; skips rather than fails if
356/// that's unavailable, matching `sentri-analyzer-evm`'s existing
357/// solc-unavailable fallback convention rather than introducing a new one.
358#[cfg(all(test, feature = "revm-backend"))]
359mod revm_integration_tests {
360    use super::*;
361
362    /// Deliberately vulnerable: `airdrop` credits a recipient's balance
363    /// without minting the corresponding supply, breaking
364    /// `sum(balanceOf) == totalSupply()` — the same "value created out of
365    /// thin air" bug shape as `sentri_dynamic_core`'s MockBackend proof,
366    /// but here as real Solidity compiled to real bytecode.
367    const VULNERABLE_TOKEN_SOURCE: &str = r#"
368// SPDX-License-Identifier: MIT
369pragma solidity ^0.8.0;
370
371contract VulnerableToken {
372    mapping(address => uint256) public balanceOf;
373    uint256 public totalSupply;
374
375    function mint(address to, uint256 amount) public {
376        balanceOf[to] += amount;
377        totalSupply += amount;
378    }
379
380    function airdrop(address to, uint256 amount) public {
381        balanceOf[to] += amount;
382    }
383}
384"#;
385
386    #[test]
387    fn revm_backend_catches_a_real_conservation_bug_end_to_end() {
388        if sentri_utils::SolcManager::new().is_err() {
389            eprintln!("skipping revm_backend_catches_a_real_conservation_bug_end_to_end: solc unavailable in this environment");
390            return;
391        }
392
393        let config = FuzzConfig {
394            seed: 1,
395            max_runs: 300,
396            sequence_depth: 10,
397            actors: vec![[1u8; 20], [2u8; 20], [3u8; 20]],
398        };
399
400        let violation = match fuzz_solidity_source(VULNERABLE_TOKEN_SOURCE, config) {
401            Ok(Some(v)) => v,
402            Ok(None) => panic!(
403                "fuzzer ran to completion without finding VulnerableToken's known conservation bug"
404            ),
405            Err(e) => panic!("fuzz_solidity_source failed unexpectedly: {e:#}"),
406        };
407
408        assert_eq!(
409            violation.invariant_name,
410            "ERC20 conservation: sum(balanceOf) == totalSupply()"
411        );
412        assert!(!violation.sequence.is_empty());
413    }
414
415    /// Deliberately vulnerable: `transferOwnership` is missing its
416    /// `onlyOwner` check — the single most common real-world access-control
417    /// bug shape, and the exact thing a forgotten modifier looks like in
418    /// production code.
419    const VULNERABLE_OWNABLE_SOURCE: &str = r#"
420// SPDX-License-Identifier: MIT
421pragma solidity ^0.8.0;
422
423contract VulnerableOwnable {
424    address public owner;
425
426    constructor() {
427        owner = msg.sender;
428    }
429
430    function transferOwnership(address newOwner) public {
431        owner = newOwner;
432    }
433}
434"#;
435
436    #[test]
437    fn revm_backend_catches_a_real_missing_only_owner_bug_end_to_end() {
438        if sentri_utils::SolcManager::new().is_err() {
439            eprintln!("skipping revm_backend_catches_a_real_missing_only_owner_bug_end_to_end: solc unavailable in this environment");
440            return;
441        }
442
443        let config = FuzzConfig {
444            seed: 2,
445            max_runs: 200,
446            sequence_depth: 4,
447            actors: vec![[1u8; 20], [2u8; 20], [3u8; 20]],
448        };
449
450        let violation = match fuzz_solidity_source(VULNERABLE_OWNABLE_SOURCE, config) {
451            Ok(Some(v)) => v,
452            Ok(None) => panic!(
453                "fuzzer ran to completion without finding VulnerableOwnable's known missing-onlyOwner bug"
454            ),
455            Err(e) => panic!("fuzz_solidity_source failed unexpectedly: {e:#}"),
456        };
457
458        assert_eq!(violation.invariant_name, "transferOwnership authorization");
459        assert!(!violation.sequence.is_empty());
460    }
461
462    /// A classic reentrancy pair: `VulnerableBank.withdraw` sends ETH to the
463    /// caller *before* zeroing their balance (a checks-effects-interactions
464    /// violation), and `Attacker.receive` re-enters `withdraw` to drain more
465    /// than it deposited. Real Solidity, compiled and executed — this is the
466    /// proof that the `ReentrancyInspector` produces correct traces from
467    /// live EVM execution and that `detect_reentrancy` flags them.
468    const REENTRANCY_SOURCE: &str = r#"
469// SPDX-License-Identifier: MIT
470pragma solidity ^0.8.0;
471
472contract VulnerableBank {
473    mapping(address => uint256) public balanceOf;
474
475    function deposit() external payable {
476        balanceOf[msg.sender] += msg.value;
477    }
478
479    function withdraw() external {
480        uint256 amount = balanceOf[msg.sender];
481        require(amount > 0, "no balance");
482        (bool ok, ) = msg.sender.call{value: amount}("");
483        require(ok, "send failed");
484        balanceOf[msg.sender] = 0; // effect after interaction: the bug
485    }
486}
487
488contract Attacker {
489    VulnerableBank public bank;
490    uint256 public reenters;
491
492    constructor(address payable b) {
493        bank = VulnerableBank(b);
494    }
495
496    function attack() external payable {
497        bank.deposit{value: msg.value}();
498        bank.withdraw();
499    }
500
501    receive() external payable {
502        if (reenters < 1) {
503            reenters++;
504            bank.withdraw();
505        }
506    }
507}
508"#;
509
510    /// Pulls one named contract's creation bytecode out of solc's
511    /// combined-json output (which keys entries as `"path.sol:Name"`).
512    fn init_code_for(output: &sentri_utils::SolcOutput, name: &str) -> Vec<u8> {
513        let suffix = format!(":{name}");
514        let entry = output
515            .contracts
516            .iter()
517            .find(|(k, _)| k.ends_with(&suffix))
518            .unwrap_or_else(|| panic!("contract {name} not found in solc output"))
519            .1;
520        solc_bridge::compiled_contract_from_solc_entry(entry)
521            .expect("named contract should have parseable bytecode")
522            .init_code
523    }
524
525    #[test]
526    fn revm_backend_catches_real_reentrancy_end_to_end() {
527        use crate::backend::RevmBackend;
528        // ExecutionBackend brings the `last_call_trace` trait method into scope.
529        use sentri_dynamic_core::{detect_reentrancy, ExecutionBackend};
530
531        let Ok(solc) = sentri_utils::SolcManager::new() else {
532            eprintln!("skipping revm_backend_catches_real_reentrancy_end_to_end: solc unavailable in this environment");
533            return;
534        };
535        let output = solc
536            .get_ast_for_source(REENTRANCY_SOURCE, "reentrancy.sol")
537            .expect("reentrancy source should compile");
538
539        let bank_init = init_code_for(&output, "VulnerableBank");
540        let attacker_init = init_code_for(&output, "Attacker");
541
542        // Deploy the bank as the primary contract.
543        let deployer = [0xAAu8; 20];
544        let mut backend =
545            RevmBackend::deploy(bank_init, deployer).expect("bank deployment should succeed");
546        let bank_addr = backend.contract_address();
547
548        // Deploy the attacker into the same state, passing the bank address
549        // as its constructor argument (ABI-encoded: left-padded to 32 bytes).
550        let mut attacker_init_with_arg = attacker_init;
551        let mut arg_word = [0u8; 32];
552        arg_word[12..32].copy_from_slice(&bank_addr);
553        attacker_init_with_arg.extend_from_slice(&arg_word);
554        let attacker_addr = backend
555            .deploy_secondary(attacker_init_with_arg, deployer)
556            .expect("attacker deployment should succeed");
557
558        // Fund an EOA to originate the attack transaction.
559        let eoa = [0x11u8; 20];
560        backend.fund_actors(&[eoa]);
561
562        // attack() is payable: the value funds the initial deposit that the
563        // attacker then re-entrantly over-withdraws.
564        let attack_selector = solc_bridge::selector_for("attack", &[]);
565        let outcome =
566            backend.call_address(attacker_addr, attack_selector.to_vec(), eoa, 1_000_000u128);
567        assert!(
568            !outcome.reverted,
569            "the attack transaction itself should succeed (that's what makes it an exploit)"
570        );
571
572        let report = detect_reentrancy(backend.last_call_trace())
573            .expect("the inspector trace of a real reentrancy attack must be flagged");
574        assert_eq!(
575            report.address, bank_addr,
576            "the re-entered contract should be identified as the bank"
577        );
578    }
579}