Skip to main content

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