Skip to main content

foundry_evm/inspectors/
revert_diagnostic.rs

1use alloy_primitives::{Address, map::HashMap};
2use evm2::{
3    EvmTypes, Inspector, InspectorConfig, OpcodeSet,
4    interpreter::{Interpreter, Message, MessageKind, MessageResult, op},
5};
6use foundry_evm_core::constants::{CHEATCODE_ADDRESS, HARDHAT_CONSOLE_ADDRESS};
7use foundry_evm_traces::RevertDiagnostic as DetailedRevertReason;
8
9const IGNORE: [Address; 2] = [HARDHAT_CONSOLE_ADDRESS, CHEATCODE_ADDRESS];
10
11/// An `EXTCODESIZE` probe of an address without executable code.
12///
13/// The probe is cached optimistically when the opcode starts, and validated against the opcode's
14/// output when it ends.
15#[derive(Clone, Copy, Debug)]
16enum SizeCheck {
17    /// `EXTCODESIZE` is executing; its output is validated in `step_end`.
18    Pending { addr: Address, depth: u16 },
19    /// `EXTCODESIZE` did not report any code for the address.
20    NonContract { addr: Address, depth: u16 },
21}
22
23impl SizeCheck {
24    const fn target(self) -> (Address, u16) {
25        match self {
26            Self::Pending { addr, depth } | Self::NonContract { addr, depth } => (addr, depth),
27        }
28    }
29}
30
31/// An inspector that tracks call context to enhances revert diagnostics.
32/// Useful for understanding reverts that are not linked to custom errors or revert strings.
33///
34/// Supported diagnostics:
35///  1. **Non-void call to non-contract address:** the soldity compiler adds some validation to the
36///     return data of the call, so despite the call succeeds, as doesn't return data, the
37///     validation causes a revert.
38///
39///     Identified when: a call with non-empty calldata is made to an address without bytecode,
40///     followed by an empty revert at the same depth.
41///
42///  2. **Void call to non-contract address:** in this case the solidity compiler adds some checks
43///     before doing the call, so it never takes place.
44///
45///     Identified when: extcodesize for the target address returns 0 + empty revert at the same
46///     depth.
47#[derive(Clone, Debug, Default)]
48pub struct RevertDiagnostic {
49    /// Tracks calls with calldata that target an address without executable code.
50    non_contract_call: Option<(Address, MessageKind, u16)>,
51    /// Tracks EXTCODESIZE checks that target an address without executable code.
52    non_contract_size_check: Option<SizeCheck>,
53    /// Diagnostic detected for the currently executing frame.
54    pending: Option<DetailedRevertReason>,
55    /// Trace nodes for active frames. `None` means the tracer did not create a node.
56    active_trace_nodes: Vec<Option<usize>>,
57    /// Presentation-only revert diagnostics keyed by trace node.
58    diagnostics: HashMap<usize, DetailedRevertReason>,
59}
60
61impl RevertDiagnostic {
62    /// Derives the revert reason based on the cached data. Should only be called after a revert.
63    const fn reason(&self) -> Option<DetailedRevertReason> {
64        if let Some((addr, scheme, _)) = self.non_contract_call {
65            let reason = if is_delegatecall(scheme) {
66                DetailedRevertReason::DelegateCallToNonContract(addr)
67            } else {
68                DetailedRevertReason::CallToNonContract(addr)
69            };
70
71            return Some(reason);
72        }
73
74        if let Some(check) = self.non_contract_size_check {
75            let (addr, _) = check.target();
76            // unknown schema as the call never took place --> output most generic reason
77            return Some(DetailedRevertReason::CallToNonContract(addr));
78        }
79
80        None
81    }
82
83    /// Starts tracking a frame before its inspectors can short-circuit execution.
84    pub fn frame_start(&mut self) {
85        self.active_trace_nodes.push(None);
86    }
87
88    /// Associates the active frame with the node created by the tracer.
89    pub fn set_trace_node(&mut self, trace_node: usize) {
90        let frame = self.active_trace_nodes.last_mut();
91        debug_assert!(frame.is_some(), "missing active revert diagnostic frame");
92        if let Some(frame) = frame {
93            *frame = Some(trace_node);
94        }
95    }
96
97    /// Finishes tracking a frame and associates any pending diagnostic with its trace node.
98    pub fn frame_end(&mut self) {
99        let frame = self.active_trace_nodes.pop();
100        debug_assert!(frame.is_some(), "revert diagnostic frame stack underflow");
101        let diagnostic = self.pending.take();
102        if let Some(node_idx) = frame.flatten()
103            && let Some(diagnostic) = diagnostic
104        {
105            self.diagnostics.insert(node_idx, diagnostic);
106        }
107    }
108
109    /// Consumes the inspector and returns its presentation-only diagnostics.
110    pub fn into_diagnostics(self) -> HashMap<usize, DetailedRevertReason> {
111        debug_assert!(self.active_trace_nodes.is_empty(), "unclosed revert diagnostic frames");
112        self.diagnostics
113    }
114
115    /// When a `REVERT` opcode with zero data size occurs, records a diagnostic if a matching
116    /// non-contract call or size check was observed at the current depth. Stale observations from
117    /// other depths are cleared.
118    #[cold]
119    fn handle_revert<T: EvmTypes>(&mut self, interp: &Interpreter<'_, '_, T>) {
120        let depth = interp.message().depth;
121        // REVERT (offset, size)
122        if let Some(size) = interp.stack().peek(1)
123            && size.is_zero()
124        {
125            // Check empty revert with same depth as a non-contract call
126            if let Some((_, _, call_depth)) = self.non_contract_call {
127                if depth == call_depth {
128                    self.pending = self.reason();
129                } else {
130                    self.non_contract_call = None;
131                }
132                return;
133            }
134
135            // Check empty revert with same depth as a non-contract size check
136            if let Some(check) = self.non_contract_size_check {
137                let (_, check_depth) = check.target();
138                if check_depth == depth {
139                    self.pending = self.reason();
140                } else {
141                    self.non_contract_size_check = None;
142                }
143            }
144        }
145    }
146
147    /// When an `EXTCODESIZE` opcode occurs:
148    ///  - Optimistically caches the target address and current depth in `non_contract_size_check`,
149    ///    pending later validation.
150    #[cold]
151    fn handle_extcodesize<T: EvmTypes>(&mut self, interp: &mut Interpreter<'_, '_, T>) {
152        // EXTCODESIZE (address)
153        if let Some(word) = interp.stack().peek(0) {
154            let addr = Address::from_word(word.into());
155            let depth = interp.message().depth;
156            if IGNORE.contains(&addr) || interp.host().precompiles().contains(&addr) {
157                return;
158            }
159
160            // Optimistically cache --> validated and cleared (if necessary) at `fn
161            // step_end()`
162            self.non_contract_size_check = Some(SizeCheck::Pending { addr, depth });
163        }
164    }
165
166    /// Validates a pending `EXTCODESIZE` probe against its output: a non-zero size clears it,
167    /// otherwise the address is confirmed to have no code and supersedes any earlier non-contract
168    /// call.
169    #[cold]
170    fn handle_extcodesize_output<T: EvmTypes>(
171        &mut self,
172        interp: &Interpreter<'_, '_, T>,
173        addr: Address,
174        depth: u16,
175    ) {
176        self.non_contract_size_check = match interp.stack().peek(0) {
177            Some(size) if !size.is_zero() => None,
178            _ => {
179                self.non_contract_call = None;
180                Some(SizeCheck::NonContract { addr, depth })
181            }
182        };
183    }
184}
185
186impl<T: EvmTypes> Inspector<T> for RevertDiagnostic {
187    fn inspector_config(&self) -> InspectorConfig {
188        const STEPS: OpcodeSet = {
189            let mut steps = OpcodeSet::EMPTY;
190            steps.insert(op::REVERT);
191            steps.insert(op::EXTCODESIZE);
192            steps
193        };
194        InspectorConfig::new().with_steps(STEPS)
195    }
196
197    /// Tracks the latest call with non-zero calldata that targets a non-contract address. Excludes
198    /// precompiles and test addresses.
199    fn call(
200        &mut self,
201        interp: &mut Interpreter<'_, '_, T>,
202        message: &mut Message<T>,
203    ) -> Option<MessageResult<T>> {
204        if message.input.is_empty() {
205            return None;
206        }
207
208        // Delegate calls execute the callee's code in the caller's storage context.
209        let target =
210            if is_delegatecall(message.kind) { message.code_address } else { message.destination };
211
212        let host = interp.host();
213        if IGNORE.contains(&target) || host.precompiles().contains(&target) {
214            return None;
215        }
216
217        if let Ok(info) = host.state_mut().account_info_untracked(&target)
218            && info.is_none_or(|info| info.is_empty_code_hash())
219        {
220            // The revert happens in the calling frame. The hook can run on a frame EVM whose
221            // interpreter is not the caller's, so take the depth from the message.
222            self.non_contract_call = Some((target, message.kind, message.depth.saturating_sub(1)));
223            // The latest observation explains a following empty revert.
224            self.non_contract_size_check = None;
225        }
226        None
227    }
228
229    /// Handles `REVERT` and `EXTCODESIZE` opcodes for diagnostics.
230    fn step(&mut self, interp: &mut Interpreter<'_, '_, T>) {
231        match interp.opcode() {
232            op::REVERT => self.handle_revert(interp),
233            op::EXTCODESIZE => self.handle_extcodesize(interp),
234            _ => {}
235        }
236    }
237
238    fn step_end(&mut self, interp: &mut Interpreter<'_, '_, T>) {
239        if let Some(SizeCheck::Pending { addr, depth }) = self.non_contract_size_check {
240            self.handle_extcodesize_output(interp, addr, depth);
241        }
242    }
243}
244
245/// Checks if the call scheme corresponds to any sort of delegate call
246const fn is_delegatecall(kind: MessageKind) -> bool {
247    matches!(kind, MessageKind::DelegateCall | MessageKind::CallCode)
248}
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253    use alloy_network::TransactionBuilder;
254    use alloy_primitives::hex;
255    use evm2::{
256        bytecode::Bytecode,
257        evm::{AccountInfo, InMemoryDB},
258    };
259    use foundry_evm_core::evm::{
260        EthEvmNetwork, EvmEnv, EvmFactoryFor, FoundryEvmFactory, FoundryTxConversion, SpecFor,
261        TransactionRequestFor, TypesFor,
262    };
263
264    #[test]
265    fn latest_non_contract_observation_explains_empty_revert() {
266        let target = Address::with_last_byte(0x40);
267        let probed = Address::with_last_byte(0xe2);
268        let mut db = InMemoryDB::default();
269        let code = hex::decode(concat!(
270            "5f5f60015f5f60e15af150", // CALL(gas, 0xe1, 0, 0, 1, 0, 0) to an address without code.
271            "60e23b50",               // EXTCODESIZE(0xe2), which has no code either.
272            "5f5ffd"                  // REVERT(0, 0).
273        ))
274        .unwrap();
275        db.insert_account_info(
276            &target,
277            AccountInfo::default().with_code(Bytecode::new_legacy(code.into())),
278        );
279        let factory = EvmFactoryFor::<EthEvmNetwork>::default();
280        let spec = SpecFor::<EthEvmNetwork>::default();
281        let mut evm =
282            factory.create_evm(db, EvmEnv::new(spec, factory.version(spec, 1), Default::default()));
283        evm.set_inspector(RevertDiagnostic::default());
284        let request = TransactionRequestFor::<EthEvmNetwork>::default()
285            .with_from(Address::with_last_byte(0x30))
286            .with_to(target)
287            .with_nonce(0)
288            .with_chain_id(1)
289            .with_gas_limit(1_000_000)
290            .with_max_fee_per_gas(0)
291            .with_max_priority_fee_per_gas(0);
292        let tx = TypesFor::<EthEvmNetwork>::tx_from_request(request).unwrap();
293        let result = evm.transact(&tx).unwrap().commit();
294        let diagnostic = evm.clear_inspector_as::<RevertDiagnostic>().unwrap();
295        assert!(!result.status);
296        assert!(
297            matches!(
298                diagnostic.pending,
299                Some(DetailedRevertReason::CallToNonContract(addr)) if addr == probed
300            ),
301            "{:?}",
302            diagnostic.pending
303        );
304    }
305}