ethrex_levm/tracing.rs
1pub use crate::opcode_tracer::{LevmOpcodeTracer, OpcodeTracerConfig};
2use crate::{
3 errors::{ContextResult, InternalError, TxResult, VMError},
4 vm::VM,
5};
6use bytes::Bytes;
7use ethrex_common::{
8 Address, U256,
9 tracing::{CallLog, CallTraceFrame, CallType},
10 types::Log,
11};
12
13/// Geth's callTracer (https://geth.ethereum.org/docs/developers/evm-tracing/built-in-tracers)
14/// Use `LevmCallTracer::disabled()` when tracing is not wanted.
15#[derive(Debug, Default)]
16pub struct LevmCallTracer {
17 /// Stack for tracer callframes, at the end of execution there will be only one element.
18 pub callframes: Vec<CallTraceFrame>,
19 /// If true, trace only the top call (a.k.a. the external transaction)
20 pub only_top_call: bool,
21 /// If true, trace logs
22 pub with_log: bool,
23 /// If active is set to false it won't trace.
24 pub active: bool,
25 /// Next block-absolute log index to assign (geth's `log.Index`). Seeded with the
26 /// count of logs emitted by preceding txs in the block and bumped on each log.
27 pub next_log_index: u64,
28}
29
30impl LevmCallTracer {
31 /// `log_index_base` is the number of logs emitted by preceding txs in the block, so
32 /// the first log this tx traces gets geth's block-absolute index. Pass 0 when there
33 /// is no preceding context (e.g. the first tx, or `with_log` disabled).
34 pub fn new(only_top_call: bool, with_log: bool, log_index_base: u64) -> Self {
35 LevmCallTracer {
36 callframes: vec![],
37 only_top_call,
38 with_log,
39 active: true,
40 next_log_index: log_index_base,
41 }
42 }
43
44 /// This is to keep LEVM's code clean, like `self.tracer.enter(...)`,
45 /// instead of something more complex or uglier when we don't want to trace.
46 /// (For now that we only implement one tracer it may be the most convenient solution)
47 pub fn disabled() -> Self {
48 LevmCallTracer {
49 active: false,
50 ..Default::default()
51 }
52 }
53
54 /// Starts trace call.
55 pub fn enter(
56 &mut self,
57 call_type: CallType,
58 from: Address,
59 to: Address,
60 value: U256,
61 gas: u64,
62 input: &Bytes, // For avoiding cloning when calling (cleaner code)
63 ) {
64 if !self.active {
65 return;
66 }
67
68 // geth traces STATICCALL with a nil value; every other call type carries one.
69 let value = if matches!(call_type, CallType::STATICCALL) {
70 None
71 } else {
72 Some(value)
73 };
74
75 let callframe = CallTraceFrame {
76 call_type,
77 from,
78 to: Some(to),
79 value,
80 gas,
81 input: input.clone(),
82 ..Default::default()
83 };
84
85 self.callframes.push(callframe);
86 }
87
88 /// Exits trace call.
89 /// Has no validations because it's a private method.
90 fn exit(
91 &mut self,
92 gas_used: u64,
93 output: Bytes,
94 error: Option<String>,
95 revert_reason: Option<String>,
96 ) -> Result<(), InternalError> {
97 let mut callframe = self.callframes.pop().ok_or(InternalError::CallFrame)?;
98
99 process_output(&mut callframe, gas_used, output, error, revert_reason);
100
101 // Append executed callframe to parent callframe if appropriate.
102 if let Some(parent_callframe) = self.callframes.last_mut() {
103 parent_callframe.calls.push(callframe);
104 } else {
105 self.callframes.push(callframe);
106 };
107 Ok(())
108 }
109
110 /// Exits trace call using the ContextResult.
111 pub fn exit_context(
112 &mut self,
113 ctx_result: &ContextResult,
114 is_top_call: bool,
115 ) -> Result<(), InternalError> {
116 if !self.active {
117 return Ok(());
118 }
119 if is_top_call {
120 // After finishing transaction execution clear all logs of callframes that reverted,
121 // then assign block-absolute indices to the survivors in emission order.
122 //
123 // The top frame's own `error` is still unset here — it is applied by the `exit`
124 // call at the end of this function, and moving the sweep after that is not an
125 // option because `exit` pops the frame. So its failure is read from
126 // `ctx_result` and seeded as the sweep's `parent_failed`; without that, a
127 // transaction whose top-level frame reverts would keep its logs, while geth
128 // drops them. Sub-frames are unaffected either way: they exited earlier, so
129 // their own `error` is already set.
130 let top_failed = matches!(ctx_result.result, TxResult::Revert(_));
131 clear_reverted_logs(self.current_callframe_mut()?, top_failed);
132 let mut next_index = self.next_log_index;
133 assign_log_indices(self.current_callframe_mut()?, &mut next_index);
134 self.next_log_index = next_index;
135 // onlyTopCall drops the subcalls only now: the full tree is needed above so
136 // the unreported nested logs still consume their block-absolute indices.
137 if self.only_top_call {
138 let callframe = self.current_callframe_mut()?;
139 callframe.calls.clear();
140 for log in &mut callframe.logs {
141 log.position = 0;
142 }
143 }
144 }
145 // The top-level frame reports the transaction's total gas used, matching the
146 // receipt (post-refund). geth does the same: `callstack[0].GasUsed = receipt.GasUsed`.
147 // `ctx_result.gas_used` is the EIP-7778 block-accounting value on Amsterdam+ and the
148 // pre-refund total elsewhere; `gas_spent` is always the post-refund amount the sender
149 // pays. Inner frames keep their own consumed gas (`gas_used`).
150 let gas_used = if is_top_call {
151 ctx_result.gas_spent
152 } else {
153 ctx_result.gas_used
154 };
155 // geth's `processOutput`: a successful frame carries the return data; a REVERT
156 // with data exposes the data and decodes any `Error(string)` revert reason; any
157 // other failure (exceptional halt / empty revert) carries neither.
158 let output = ctx_result.output.clone();
159 let (output, error, revert_reason) = match ctx_result.result {
160 TxResult::Revert(ref err) => {
161 let error = Some(geth_error_string(err));
162 if err.is_revert_opcode() && !output.is_empty() {
163 (output.clone(), error, decode_revert_reason(&output))
164 } else {
165 (Bytes::new(), error, None)
166 }
167 }
168 _ => (output, None, None),
169 };
170
171 self.exit(gas_used, output, error, revert_reason)
172 }
173
174 /// Exits trace call when CALL or CREATE opcodes return early or in case SELFDESTRUCT is called.
175 pub fn exit_early(
176 &mut self,
177 gas_used: u64,
178 error: Option<String>,
179 ) -> Result<(), InternalError> {
180 if !self.active {
181 return Ok(());
182 }
183 // Early-out reasons are internal tokens (e.g. "OutOfFund"); normalize to the
184 // geth-compatible error string the callTracer reports.
185 let error = error.map(|token| geth_error_from_token(&token));
186 self.exit(gas_used, Bytes::new(), error, None)
187 }
188
189 /// Registers log when opcode log is executed.
190 /// Note: Logs of callframes that reverted will be removed at end of execution.
191 pub fn log(&mut self, log: &Log) -> Result<(), InternalError> {
192 if !self.active || !self.with_log {
193 return Ok(());
194 }
195 let callframe = self.current_callframe_mut()?;
196
197 let log = CallLog {
198 address: log.address,
199 topics: log.topics.clone(),
200 data: log.data.clone(),
201 // Placeholder: the block-absolute index is assigned in `assign_log_indices`
202 // after reverted logs are pruned, so surviving logs stay gap-free like geth.
203 index: 0,
204 position: match callframe.calls.len().try_into() {
205 Ok(pos) => pos,
206 Err(_) => return Err(InternalError::TypeConversion),
207 },
208 };
209
210 callframe.logs.push(log);
211 Ok(())
212 }
213
214 fn current_callframe_mut(&mut self) -> Result<&mut CallTraceFrame, InternalError> {
215 self.callframes.last_mut().ok_or(InternalError::CallFrame)
216 }
217}
218
219fn process_output(
220 callframe: &mut CallTraceFrame,
221 gas_used: u64,
222 output: Bytes,
223 error: Option<String>,
224 revert_reason: Option<String>,
225) {
226 callframe.gas_used = gas_used;
227 callframe.output = output;
228 // geth drops `to` on a failed CREATE/CREATE2 (no contract was deployed).
229 if error.is_some() && matches!(callframe.call_type, CallType::CREATE | CallType::CREATE2) {
230 callframe.to = None;
231 }
232 callframe.error = error;
233 callframe.revert_reason = revert_reason;
234}
235
236/// Maps a LEVM [`VMError`] to the error string geth's callTracer emits (from
237/// `core/vm/errors.go`).
238///
239/// The static errors match geth byte-for-byte. `stack underflow`, `stack overflow`
240/// and `invalid opcode` are geth-formatted with operands (`stack underflow (1 <=> 2)`,
241/// `invalid opcode: STOP`) that LEVM's unit variants don't carry, so we emit geth's
242/// base wording for those. Variants without a geth analogue keep LEVM's own message.
243fn geth_error_string(err: &VMError) -> String {
244 use crate::errors::ExceptionalHalt::*;
245 let mapped = match err {
246 VMError::RevertOpcode => "execution reverted",
247 VMError::ExceptionalHalt(halt) => match halt {
248 OutOfGas => "out of gas",
249 InvalidJump => "invalid jump destination",
250 OpcodeNotAllowedInStaticContext => "write protection",
251 AddressAlreadyOccupied => "contract address collision",
252 ContractOutputTooBig => "max code size exceeded",
253 InvalidContractPrefix => "invalid code: must not begin with 0xef",
254 // geth formats these with operands we don't carry — emit its base wording.
255 StackUnderflow => "stack underflow",
256 StackOverflow => "stack overflow",
257 InvalidOpcode => "invalid opcode",
258 // No direct geth analogue; keep LEVM's message.
259 VeryLargeNumber | OutOfBounds | Precompile(_) => return err.to_string(),
260 },
261 _ => return err.to_string(),
262 };
263 mapped.to_string()
264}
265
266/// Maps a CALL/CREATE early-out token (passed to [`LevmCallTracer::exit_early`]) to
267/// the geth-compatible error string the callTracer reports.
268fn geth_error_from_token(token: &str) -> String {
269 match token {
270 "OutOfFund" => "insufficient balance for transfer",
271 "MaxDepth" => "max call depth exceeded",
272 "MaxNonce" => "nonce uint64 overflow",
273 "CreateAccExists" => "contract address collision",
274 other => return other.to_string(),
275 }
276 .to_string()
277}
278
279/// Decodes an ABI-encoded `Error(string)` revert payload into its message, mirroring
280/// geth's `abi.UnpackRevert`. Returns `None` for any payload that isn't a canonical
281/// `Error(string)` (e.g. `Panic(uint256)` or custom errors), matching geth.
282fn decode_revert_reason(output: &[u8]) -> Option<String> {
283 // selector("Error(string)") = 0x08c379a0
284 const SELECTOR: [u8; 4] = [0x08, 0xc3, 0x79, 0xa0];
285 if output.get(..4)? != SELECTOR {
286 return None;
287 }
288 let word_as_usize = |start: usize| -> Option<usize> {
289 let word = output.get(start..start.checked_add(32)?)?;
290 usize::try_from(U256::from_big_endian(word)).ok()
291 };
292 // head: offset to the string's dynamic-data region (relative to the args block,
293 // i.e. after the 4-byte selector).
294 let len_start = 4usize.checked_add(word_as_usize(4)?)?;
295 let len = word_as_usize(len_start)?;
296 let data_start = len_start.checked_add(32)?;
297 let data = output.get(data_start..data_start.checked_add(len)?)?;
298 String::from_utf8(data.to_vec()).ok()
299}
300
301/// Assigns each surviving log its block-absolute `index` (geth's `log.Index`) by walking
302/// the frame tree in emission order and counting from `*next`. A log with `position == p`
303/// was emitted after `p` subcalls completed, so within a frame the order is: logs at
304/// position 0, subcall 0, logs at position 1, subcall 1, …, trailing logs. Because
305/// reverted logs were already pruned, the survivors get contiguous, gap-free indices —
306/// matching geth, which decrements `logSize` on revert.
307fn assign_log_indices(callframe: &mut CallTraceFrame, next: &mut u64) {
308 let mut logs = callframe.logs.iter_mut().peekable();
309 for (call_idx, subcall) in callframe.calls.iter_mut().enumerate() {
310 let call_idx = u64::try_from(call_idx).unwrap_or(u64::MAX);
311 while let Some(log) = logs.next_if(|l| l.position == call_idx) {
312 log.index = *next;
313 *next = next.saturating_add(1);
314 }
315 assign_log_indices(subcall, next);
316 }
317 for log in logs {
318 log.index = *next;
319 *next = next.saturating_add(1);
320 }
321}
322
323/// Clears logs of any frame that failed *or* whose ancestor failed, since a reverted
324/// frame rolls back its whole subtree's state (including subcall logs). Mirrors geth's
325/// `clearFailedLogs`, which threads a `parentFailed` flag down the tree.
326fn clear_reverted_logs(callframe: &mut CallTraceFrame, parent_failed: bool) {
327 let failed = parent_failed || callframe.error.is_some();
328 if failed {
329 callframe.logs.clear();
330 }
331 for subcall in &mut callframe.calls {
332 clear_reverted_logs(subcall, failed);
333 }
334}
335
336impl<'a> VM<'a> {
337 /// This method is intended to be accessed after transaction execution
338 pub fn get_trace_result(&mut self) -> Result<CallTraceFrame, VMError> {
339 self.tracer
340 .callframes
341 .pop()
342 .ok_or(InternalError::CallFrame.into())
343 }
344}