Skip to main content

foundry_evm/inspectors/
chisel_state.rs

1use alloy_primitives::U256;
2use evm2::{
3    EvmTypesHost, Inspector,
4    interpreter::{Host, Interpreter},
5};
6
7/// An inspector for Chisel.
8#[derive(Clone, Debug, Default)]
9pub struct ChiselState {
10    /// The PC mapped to the final source statement, if available.
11    pub final_pc: Option<usize>,
12    /// The state after the final source statement, or at the end of the REPL call if it was not
13    /// reached.
14    pub state: Option<(Vec<U256>, Vec<u8>)>,
15    /// Whether the current instruction matches the final source statement.
16    at_final_pc: bool,
17}
18
19impl ChiselState {
20    /// Create a new Chisel state inspector.
21    #[inline]
22    pub const fn new(final_pc: Option<usize>) -> Self {
23        Self { final_pc, state: None, at_final_pc: false }
24    }
25}
26
27/// Returns whether `interp` runs the root frame of the transaction.
28fn is_root_frame<T: EvmTypesHost>(interp: &mut Interpreter<'_, '_, T>) -> bool {
29    interp.message().depth == interp.host().initial_call_depth()
30}
31
32impl<T: EvmTypesHost> Inspector<T> for ChiselState {
33    fn initialize_interp(&mut self, interp: &mut Interpreter<'_, '_, T>) {
34        if is_root_frame(interp) {
35            self.state = None;
36            self.at_final_pc = false;
37        }
38    }
39
40    #[cold]
41    fn step(&mut self, interp: &mut Interpreter<'_, '_, T>) {
42        if is_root_frame(interp) {
43            // Read the PC before execution: PUSH and JUMP do not advance it by one byte, and evm2
44            // leaves it on an instruction that halts.
45            self.at_final_pc = self.final_pc == Some(interp.pc());
46        }
47    }
48
49    #[cold]
50    fn step_end(&mut self, interp: &mut Interpreter<'_, '_, T>) {
51        // Reaching the byte after the final instruction, such as a loop's exit, also completes the
52        // statement. A source span may be absent or map to an instruction that never executes. In
53        // that case, capture the completed root frame instead. The result is only an error after
54        // the instruction that halts the frame.
55        if is_root_frame(interp)
56            && (self.at_final_pc
57                || self.final_pc.is_some_and(|pc| interp.pc() == pc + 1)
58                || (self.state.is_none() && interp.result().is_err()))
59        {
60            self.state =
61                Some((interp.stack().as_slice().to_vec(), interp.memory().as_slice().to_vec()));
62        }
63    }
64}
65
66#[cfg(test)]
67mod tests {
68    use super::*;
69    use alloy_network::TransactionBuilder;
70    use alloy_primitives::{Address, hex};
71    use evm2::{
72        bytecode::Bytecode,
73        evm::{AccountInfo, InMemoryDB},
74    };
75    use foundry_evm_core::evm::{
76        EthEvmNetwork, EvmEnv, EvmFactoryFor, FoundryEvmFactory, FoundryTxConversion, SpecFor,
77        TransactionRequestFor, TypesFor,
78    };
79
80    fn execute(inspector: ChiselState, code: &str) -> ChiselState {
81        let target = Address::with_last_byte(0x40);
82        let child = Address::with_last_byte(0x20);
83        let mut db = InMemoryDB::default();
84        for (address, code) in [(target, code), (child, "61cafe5f52600700")] {
85            db.insert_account_info(
86                &address,
87                AccountInfo::default()
88                    .with_code(Bytecode::new_legacy(hex::decode(code).unwrap().into())),
89            );
90        }
91        let factory = EvmFactoryFor::<EthEvmNetwork>::default();
92        let spec = SpecFor::<EthEvmNetwork>::default();
93        let mut evm =
94            factory.create_evm(db, EvmEnv::new(spec, factory.version(spec, 1), Default::default()));
95        evm.set_inspector(inspector);
96        let request = TransactionRequestFor::<EthEvmNetwork>::default()
97            .with_from(Address::with_last_byte(0x30))
98            .with_to(target)
99            .with_nonce(0)
100            .with_chain_id(1)
101            .with_gas_limit(1_000_000)
102            .with_max_fee_per_gas(0)
103            .with_max_priority_fee_per_gas(0);
104        let tx = TypesFor::<EthEvmNetwork>::tx_from_request(request).unwrap();
105        let result = evm.transact(&tx).unwrap().commit();
106        assert!(result.status);
107        *evm.clear_inspector_as::<ChiselState>().unwrap()
108    }
109
110    #[test]
111    fn captures_final_state_without_an_executed_source_match() {
112        for final_pc in [None, Some(100)] {
113            // MSTORE(0, 0x1337), PUSH1 42, STOP.
114            let inspector = execute(ChiselState::new(final_pc), "6113375f52602a00");
115            assert_eq!(
116                inspector.state,
117                Some((vec![U256::from(42)], U256::from(0x1337).to_be_bytes::<32>().to_vec()))
118            );
119        }
120    }
121
122    #[test]
123    fn preserves_source_snapshot_after_push_and_jump() {
124        for (code, final_pc, expected_stack) in [
125            // A valid source match at PC zero must still work, including PUSH immediates.
126            ("6113375f52602a00", 0, vec![U256::from(0x1337)]),
127            // PUSH1 42, PUSH1 6, JUMP, INVALID, JUMPDEST, POP, STOP.
128            ("602a600656fe5b5000", 4, vec![U256::from(42)]),
129        ] {
130            let inspector = execute(ChiselState::new(Some(final_pc)), code);
131            assert_eq!(inspector.state, Some((expected_stack, vec![])));
132        }
133    }
134
135    #[test]
136    fn nested_calls_do_not_replace_root_state() {
137        for (final_pc, expected_stack) in [(None, vec![U256::from(42)]), (Some(4), vec![])] {
138            // MSTORE(0, 0x1337), CALL child, POP success, PUSH1 42, STOP. The child also executes
139            // MSTORE at PC 4, but writes 0xcafe and leaves 7 on its stack.
140            let inspector =
141                execute(ChiselState::new(final_pc), "6113375f525f5f5f5f5f60205af150602a00");
142            assert_eq!(
143                inspector.state,
144                Some((expected_stack, U256::from(0x1337).to_be_bytes::<32>().to_vec()))
145            );
146        }
147    }
148
149    #[test]
150    fn resets_snapshot_between_executions() {
151        let inspector = execute(ChiselState::new(Some(4)), "6113375f52602a00");
152        // The second execution never reaches PC 4 and must use its own terminal snapshot.
153        let inspector = execute(inspector, "602b00");
154        assert_eq!(inspector.state, Some((vec![U256::from(43)], vec![])));
155    }
156}