ethrex_common/tracing.rs
1//! Trace data types and their wire-format serializers.
2//!
3//! ## Architecture
4//!
5//! Capture, data, and output format are separated:
6//!
7//! - **Capture** lives in `ethrex-levm` (`LevmOpcodeTracer`, the dispatch-loop hook).
8//! It runs once per tx and produces a [`Vec<OpcodeStep>`] plus the trailing
9//! metadata in [`OpcodeTraceResult`].
10//! - **Data** are the bare structs [`OpcodeStep`] and [`OpcodeTraceResult`] in this
11//! module. They carry no `Serialize` impl — they're consumer-agnostic. The same
12//! captured data feeds every downstream wire format.
13//! - **Wire format** is a newtype wrapper around one of those data structs with its
14//! own `Serialize` impl. Two shapes coexist:
15//! - [`StructLoggerStep`] / [`StructLoggerResult`] — the geth-RPC `debug_traceTransaction`
16//! structLogger shape: `op` as string mnemonic, no `opName`, decimal `gas`, etc.
17//! Used by the RPC handler and matches what every major client (geth, besu, …) emits
18//! from this endpoint. Consumers: Blockscout, Foundry, Tenderly, anything reading
19//! `debug_traceTransaction`.
20//! - [`Eip3155Step`] — strict [EIP-3155](https://eips.ethereum.org/EIPS/eip-3155)
21//! shape: numeric `op` byte + separate `opName`, `"0xN"` hex `gas`/`gasCost`/`refund`,
22//! `stack:[]` (never null) when disabled. Used by streaming sinks that want
23//! spec-conformant per-step JSONL — e.g. the `ef-tests-statev2 statetest` subcommand
24//! feeding goevmlab.
25//!
26//! Adding a third format (Parity-style flat call, opcode-count tracers, …) means another
27//! newtype with its own `Serialize` impl. No changes to the data types or capture layer.
28//!
29//! ## Why not match geth-RPC everywhere
30//!
31//! `debug_traceTransaction` predates EIP-3155 by years and its de-facto shape diverges
32//! from the spec on three points: `op` is a string, `opName` is absent, and `gas`/`gasCost`
33//! are decimal numbers instead of `"0xN"` hex strings. Every major client matches geth's
34//! shape there for tooling compat, not EIP-3155. So:
35//! - RPC consumer expects structLogger → use [`StructLoggerStep`]/[`StructLoggerResult`].
36//! - EIP-3155-conformant CLI consumer (goevmlab, fuzzers) → use [`Eip3155Step`].
37
38use bytes::Bytes;
39use ethereum_types::H256;
40use ethereum_types::{Address, U256};
41use serde::Serialize;
42use std::collections::BTreeMap;
43
44/// Collection of traces of each call frame as defined in geth's `callTracer` output
45/// https://geth.ethereum.org/docs/developers/evm-tracing/built-in-tracers#call-tracer
46pub type CallTrace = Vec<CallTraceFrame>;
47
48/// Trace of each call frame as defined in geth's `callTracer` output
49/// https://geth.ethereum.org/docs/developers/evm-tracing/built-in-tracers#call-tracer
50#[derive(Debug, Serialize, Default)]
51#[serde(rename_all = "camelCase")]
52pub struct CallTraceFrame {
53 /// Type of the Call
54 #[serde(rename = "type")]
55 pub call_type: CallType,
56 /// Address that initiated the call
57 pub from: Address,
58 /// Address that received the call. Omitted when absent (geth's `to,omitempty`),
59 /// e.g. nil'd for a failed CREATE/CREATE2.
60 #[serde(skip_serializing_if = "Option::is_none")]
61 pub to: Option<Address>,
62 /// Amount transferred. Omitted when absent (geth's `value,omitempty`) — notably
63 /// `STATICCALL`, which geth traces with a nil value.
64 #[serde(skip_serializing_if = "Option::is_none")]
65 pub value: Option<U256>,
66 /// Gas provided for the call
67 #[serde(with = "crate::serde_utils::u64::hex_str")]
68 pub gas: u64,
69 /// Gas used by the call
70 #[serde(with = "crate::serde_utils::u64::hex_str")]
71 pub gas_used: u64,
72 /// Call data (always present, matching geth's non-optional `input`)
73 #[serde(with = "crate::serde_utils::bytes")]
74 pub input: Bytes,
75 /// Return data. Omitted when empty (geth's `output,omitempty`).
76 #[serde(
77 with = "crate::serde_utils::bytes",
78 skip_serializing_if = "Bytes::is_empty"
79 )]
80 pub output: Bytes,
81 /// Error returned if the call failed. Omitted when absent (geth's `error,omitempty`).
82 #[serde(skip_serializing_if = "Option::is_none")]
83 pub error: Option<String>,
84 /// Revert reason if the call reverted. Omitted when absent (geth's `revertReason,omitempty`).
85 #[serde(skip_serializing_if = "Option::is_none")]
86 pub revert_reason: Option<String>,
87 /// List of nested sub-calls. Omitted when empty (geth's `calls,omitempty`).
88 #[serde(skip_serializing_if = "Vec::is_empty")]
89 pub calls: Vec<CallTraceFrame>,
90 /// Logs (if enabled)
91 #[serde(skip_serializing_if = "Vec::is_empty")]
92 pub logs: Vec<CallLog>,
93}
94
95#[derive(Serialize, Debug, Default)]
96pub enum CallType {
97 #[default]
98 CALL,
99 CALLCODE,
100 STATICCALL,
101 DELEGATECALL,
102 CREATE,
103 CREATE2,
104 SELFDESTRUCT,
105}
106
107#[derive(Serialize, Debug)]
108#[serde(rename_all = "camelCase")]
109pub struct CallLog {
110 pub address: Address,
111 pub topics: Vec<H256>,
112 #[serde(with = "crate::serde_utils::bytes")]
113 pub data: Bytes,
114 /// Block-absolute log index, matching geth's `log.Index` (a counter running across
115 /// every tx in the block). Seeded per tx from the preceding txs' log count.
116 pub index: u64,
117 /// Position of this log relative to the subcalls of the enclosing frame.
118 pub position: u64,
119}
120
121/// Per-account state entry emitted by the prestateTracer.
122///
123/// `balance` is `Option<U256>`: `None` means "field absent from output",
124/// `Some(0)` still serializes (lets diff post emit a balance that became zero).
125#[derive(Debug, Serialize, Default, Clone)]
126#[serde(rename_all = "camelCase")]
127pub struct PrestateAccountState {
128 #[serde(default, skip_serializing_if = "Option::is_none")]
129 pub balance: Option<U256>,
130 #[serde(default, skip_serializing_if = "is_zero_nonce")]
131 pub nonce: u64,
132 #[serde(
133 default,
134 skip_serializing_if = "Bytes::is_empty",
135 with = "crate::serde_utils::bytes"
136 )]
137 pub code: Bytes,
138 #[serde(default, skip_serializing_if = "H256::is_zero")]
139 pub code_hash: H256,
140 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
141 pub storage: BTreeMap<H256, H256>,
142}
143
144impl PrestateAccountState {
145 /// True when no field conveys information; `Some(0)` balance counts as empty.
146 pub fn is_empty(&self) -> bool {
147 self.balance.unwrap_or_default().is_zero()
148 && self.nonce == 0
149 && self.code.is_empty()
150 && self.code_hash.is_zero()
151 && self.storage.is_empty()
152 }
153}
154
155/// Per-transaction prestate trace (non-diff mode). `BTreeMap` keeps JSON output
156/// deterministic via sorted keys.
157pub type PrestateTrace = BTreeMap<Address, PrestateAccountState>;
158
159/// Result of a prestateTracer execution — either a plain prestate map or a diff.
160#[derive(Debug, Clone)]
161pub enum PrestateResult {
162 /// Non-diff mode: map of address → pre-tx account state.
163 Prestate(PrestateTrace),
164 /// Diff mode: pre-tx and post-tx state for all touched accounts.
165 Diff(PrePostState),
166}
167
168/// Per-transaction prestate trace (diff mode).
169/// Contains the pre-tx and post-tx state for all touched accounts.
170#[derive(Debug, Serialize, Default, Clone)]
171pub struct PrePostState {
172 pub pre: BTreeMap<Address, PrestateAccountState>,
173 pub post: BTreeMap<Address, PrestateAccountState>,
174}
175
176fn is_zero_nonce(n: &u64) -> bool {
177 *n == 0
178}
179
180// ─── OpcodeTracer types ──────────────────────────────────────────────────────
181
182/// Per-opcode trace entry — pure data, no `Serialize` impl.
183///
184/// To get this on the wire, wrap in one of the format newtypes:
185/// - [`StructLoggerStep`] for geth-RPC `debug_traceTransaction` shape.
186/// - [`Eip3155Step`] for EIP-3155 spec shape.
187///
188/// See the module-level doc for why both formats coexist.
189#[derive(Debug)]
190pub struct OpcodeStep {
191 pub pc: u64,
192 /// Raw opcode byte value (e.g. 0x60 for PUSH1). Each format serializer decides
193 /// how to render this (numeric byte, hex string, mnemonic string).
194 pub op: u8,
195 pub gas: u64,
196 pub gas_cost: u64,
197 /// Current memory size in bytes.
198 pub mem_size: u64,
199 pub depth: u32,
200 /// Return data from the previous sub-call.
201 pub return_data: bytes::Bytes,
202 /// Gas refund counter.
203 pub refund: u64,
204 /// `Some(vec)` when stack capture is enabled (bottom-first); `None` when disabled.
205 /// Each format serializer decides how to render `None`: structLogger emits JSON null,
206 /// EIP-3155 emits `[]` (per spec's "MUST initialize to empty array" rule).
207 pub stack: Option<Vec<U256>>,
208 /// `Some(chunks)` when memory capture is enabled; `None` when disabled (field omitted).
209 pub memory: Option<Vec<MemoryChunk>>,
210 /// `Some(map)` at SLOAD/SSTORE steps when storage capture is enabled; `None`
211 /// otherwise. The map is a cumulative snapshot of every slot touched by an
212 /// SLOAD/SSTORE so far in the transaction — matching geth's structLogger.
213 /// The tracer maintains this in `LevmOpcodeTracer::cumulative_storage`.
214 pub storage: Option<BTreeMap<H256, H256>>,
215 pub error: Option<String>,
216}
217
218/// A 32-byte chunk of EVM memory, serialized as `"0x" + 64 lowercase hex chars`.
219/// The *caller* zero-pads the last partial chunk before constructing this type.
220#[derive(Debug)]
221pub struct MemoryChunk(pub [u8; 32]);
222
223/// Top-level result of one opcode-traced transaction — pure data, no `Serialize` impl.
224///
225/// Wrap in [`StructLoggerResult`] to get the geth-RPC `{failed, gas, returnValue, structLogs}`
226/// wire shape. EIP-3155-conformant CLI consumers stream per-step [`OpcodeStep`]s
227/// directly (via [`Eip3155Step`]) and emit their own summary line, so there's no
228/// EIP-3155 wrapper newtype for the result.
229#[derive(Debug)]
230pub struct OpcodeTraceResult {
231 pub gas_used: u64,
232 /// True iff the transaction completed without error.
233 pub pass: bool,
234 pub output: bytes::Bytes,
235 pub steps: Vec<OpcodeStep>,
236}
237
238// ─── Helpers ──────────────────────────────────────────────────────────────
239
240/// Returns the opcode mnemonic for `byte`.
241///
242/// Known opcodes → their uppercase name (`"PUSH1"`, `"ADD"`, `"INVALID"` for
243/// 0xFE). Unassigned bytes → `None`; callers wanting the conventional unknown
244/// string should fall back to `format!("opcode 0x{:02x} not defined", byte)`.
245///
246/// The table is **fork-agnostic by design**, matching geth's
247/// `core/vm/opcodes.go::opCodeToString` (also a flat 256-entry table). Fork
248/// validity is enforced at *dispatch* via the VM's per-fork opcode table:
249/// e.g. byte `0x5F` (PUSH0) halts pre-Shanghai with `InvalidOpcode` before
250/// the tracer ever emits a step for it, so the name lookup never fires for
251/// invalid-for-this-fork bytes in practice.
252pub fn opcode_name(byte: u8) -> Option<&'static str> {
253 match byte {
254 0x00 => Some("STOP"),
255 0x01 => Some("ADD"),
256 0x02 => Some("MUL"),
257 0x03 => Some("SUB"),
258 0x04 => Some("DIV"),
259 0x05 => Some("SDIV"),
260 0x06 => Some("MOD"),
261 0x07 => Some("SMOD"),
262 0x08 => Some("ADDMOD"),
263 0x09 => Some("MULMOD"),
264 0x0A => Some("EXP"),
265 0x0B => Some("SIGNEXTEND"),
266 0x10 => Some("LT"),
267 0x11 => Some("GT"),
268 0x12 => Some("SLT"),
269 0x13 => Some("SGT"),
270 0x14 => Some("EQ"),
271 0x15 => Some("ISZERO"),
272 0x16 => Some("AND"),
273 0x17 => Some("OR"),
274 0x18 => Some("XOR"),
275 0x19 => Some("NOT"),
276 0x1A => Some("BYTE"),
277 0x1B => Some("SHL"),
278 0x1C => Some("SHR"),
279 0x1D => Some("SAR"),
280 0x1E => Some("CLZ"),
281 0x20 => Some("KECCAK256"),
282 0x30 => Some("ADDRESS"),
283 0x31 => Some("BALANCE"),
284 0x32 => Some("ORIGIN"),
285 0x33 => Some("CALLER"),
286 0x34 => Some("CALLVALUE"),
287 0x35 => Some("CALLDATALOAD"),
288 0x36 => Some("CALLDATASIZE"),
289 0x37 => Some("CALLDATACOPY"),
290 0x38 => Some("CODESIZE"),
291 0x39 => Some("CODECOPY"),
292 0x3A => Some("GASPRICE"),
293 0x3B => Some("EXTCODESIZE"),
294 0x3C => Some("EXTCODECOPY"),
295 0x3D => Some("RETURNDATASIZE"),
296 0x3E => Some("RETURNDATACOPY"),
297 0x3F => Some("EXTCODEHASH"),
298 0x40 => Some("BLOCKHASH"),
299 0x41 => Some("COINBASE"),
300 0x42 => Some("TIMESTAMP"),
301 0x43 => Some("NUMBER"),
302 0x44 => Some("PREVRANDAO"),
303 0x45 => Some("GASLIMIT"),
304 0x46 => Some("CHAINID"),
305 0x47 => Some("SELFBALANCE"),
306 0x48 => Some("BASEFEE"),
307 0x49 => Some("BLOBHASH"),
308 0x4A => Some("BLOBBASEFEE"),
309 0x4B => Some("SLOTNUM"),
310 0x50 => Some("POP"),
311 0x51 => Some("MLOAD"),
312 0x52 => Some("MSTORE"),
313 0x53 => Some("MSTORE8"),
314 0x54 => Some("SLOAD"),
315 0x55 => Some("SSTORE"),
316 0x56 => Some("JUMP"),
317 0x57 => Some("JUMPI"),
318 0x58 => Some("PC"),
319 0x59 => Some("MSIZE"),
320 0x5A => Some("GAS"),
321 0x5B => Some("JUMPDEST"),
322 0x5C => Some("TLOAD"),
323 0x5D => Some("TSTORE"),
324 0x5E => Some("MCOPY"),
325 0x5F => Some("PUSH0"),
326 0x60 => Some("PUSH1"),
327 0x61 => Some("PUSH2"),
328 0x62 => Some("PUSH3"),
329 0x63 => Some("PUSH4"),
330 0x64 => Some("PUSH5"),
331 0x65 => Some("PUSH6"),
332 0x66 => Some("PUSH7"),
333 0x67 => Some("PUSH8"),
334 0x68 => Some("PUSH9"),
335 0x69 => Some("PUSH10"),
336 0x6A => Some("PUSH11"),
337 0x6B => Some("PUSH12"),
338 0x6C => Some("PUSH13"),
339 0x6D => Some("PUSH14"),
340 0x6E => Some("PUSH15"),
341 0x6F => Some("PUSH16"),
342 0x70 => Some("PUSH17"),
343 0x71 => Some("PUSH18"),
344 0x72 => Some("PUSH19"),
345 0x73 => Some("PUSH20"),
346 0x74 => Some("PUSH21"),
347 0x75 => Some("PUSH22"),
348 0x76 => Some("PUSH23"),
349 0x77 => Some("PUSH24"),
350 0x78 => Some("PUSH25"),
351 0x79 => Some("PUSH26"),
352 0x7A => Some("PUSH27"),
353 0x7B => Some("PUSH28"),
354 0x7C => Some("PUSH29"),
355 0x7D => Some("PUSH30"),
356 0x7E => Some("PUSH31"),
357 0x7F => Some("PUSH32"),
358 0x80 => Some("DUP1"),
359 0x81 => Some("DUP2"),
360 0x82 => Some("DUP3"),
361 0x83 => Some("DUP4"),
362 0x84 => Some("DUP5"),
363 0x85 => Some("DUP6"),
364 0x86 => Some("DUP7"),
365 0x87 => Some("DUP8"),
366 0x88 => Some("DUP9"),
367 0x89 => Some("DUP10"),
368 0x8A => Some("DUP11"),
369 0x8B => Some("DUP12"),
370 0x8C => Some("DUP13"),
371 0x8D => Some("DUP14"),
372 0x8E => Some("DUP15"),
373 0x8F => Some("DUP16"),
374 0x90 => Some("SWAP1"),
375 0x91 => Some("SWAP2"),
376 0x92 => Some("SWAP3"),
377 0x93 => Some("SWAP4"),
378 0x94 => Some("SWAP5"),
379 0x95 => Some("SWAP6"),
380 0x96 => Some("SWAP7"),
381 0x97 => Some("SWAP8"),
382 0x98 => Some("SWAP9"),
383 0x99 => Some("SWAP10"),
384 0x9A => Some("SWAP11"),
385 0x9B => Some("SWAP12"),
386 0x9C => Some("SWAP13"),
387 0x9D => Some("SWAP14"),
388 0x9E => Some("SWAP15"),
389 0x9F => Some("SWAP16"),
390 0xA0 => Some("LOG0"),
391 0xA1 => Some("LOG1"),
392 0xA2 => Some("LOG2"),
393 0xA3 => Some("LOG3"),
394 0xA4 => Some("LOG4"),
395 0xE6 => Some("DUPN"),
396 0xE7 => Some("SWAPN"),
397 0xE8 => Some("EXCHANGE"),
398 0xF0 => Some("CREATE"),
399 0xF1 => Some("CALL"),
400 0xF2 => Some("CALLCODE"),
401 0xF3 => Some("RETURN"),
402 0xF4 => Some("DELEGATECALL"),
403 0xF5 => Some("CREATE2"),
404 0xFA => Some("STATICCALL"),
405 0xFD => Some("REVERT"),
406 0xFE => Some("INVALID"),
407 0xFF => Some("SELFDESTRUCT"),
408 _ => None,
409 }
410}
411
412/// Converts a `U256` to geth's `uint256.Int.Hex()` form: `"0x"` followed by
413/// lowercase hex with leading zeros stripped. Zero → `"0x0"` (not `"0x"`).
414pub fn geth_uint256_hex(v: &U256) -> String {
415 if v.is_zero() {
416 return "0x0".to_string();
417 }
418 // U256 words are little-endian; convert to big-endian bytes.
419 let bytes = crate::utils::u256_to_big_endian(*v);
420 let hex_str = hex::encode(bytes);
421 let stripped = hex_str.trim_start_matches('0');
422 format!("0x{}", stripped)
423}
424
425// ─── Serialize impls ──────────────────────────────────────────────────────
426
427impl serde::Serialize for MemoryChunk {
428 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
429 serializer.serialize_str(&format!("0x{}", hex::encode(self.0)))
430 }
431}
432
433// Shared utilities used by both wire-format serializers below.
434
435fn serialize_storage_map<S: serde::Serializer>(
436 serializer: S,
437 storage: &BTreeMap<H256, H256>,
438) -> Result<S::Ok, S::Error> {
439 use serde::ser::SerializeMap;
440 let mut m = serializer.serialize_map(Some(storage.len()))?;
441 for (k, v) in storage {
442 let k_str = format!("0x{}", hex::encode(k.as_bytes()));
443 let v_str = format!("0x{}", hex::encode(v.as_bytes()));
444 m.serialize_entry(&k_str, &v_str)?;
445 }
446 m.end()
447}
448
449/// Mnemonic string for an opcode byte, falling back to `"opcode 0xNN not defined"`
450/// for bytes outside the assigned table.
451fn opcode_name_or_fallback(byte: u8) -> String {
452 opcode_name(byte)
453 .map(str::to_owned)
454 .unwrap_or_else(|| format!("opcode 0x{byte:02x} not defined"))
455}
456
457// ─── Wire format: geth-RPC structLogger ───────────────────────────────────
458//
459// The de-facto `debug_traceTransaction` response shape, emitted by every major
460// execution client (geth, besu, reth, erigon, nethermind). Predates EIP-3155
461// and diverges from it on three per-step fields:
462//
463// - `op`: string mnemonic (`"PUSH1"`), not the numeric opcode byte.
464// - No separate `opName` field.
465// - `gas`, `gasCost`, `refund`: decimal JSON numbers, not `"0xN"` hex strings.
466//
467// `stack` is serialized as JSON `null` when capture is disabled — also a divergence
468// from EIP-3155, which mandates `[]` — but it matches geth's RPC behavior so we
469// preserve it on this code path.
470//
471// Verified against geth and besu on a kurtosis localnet via `debug_traceTransaction`:
472// byte-for-byte identical to the StructLogger output.
473
474/// Controls which always-populated per-step fields the structLogger wire format emits.
475///
476/// `mem_size`, `return_data`, and `refund` are always present in the captured
477/// [`OpcodeStep`] (the capture layer just defaults them to zero/empty when the
478/// corresponding capture config is off). geth's `debug_traceTransaction` *suppresses*
479/// these fields unless their data is actually captured. To match geth byte-for-byte
480/// we honor the caller's intent explicitly here.
481///
482/// Typical mapping at the RPC layer:
483///
484/// ```ignore
485/// let emit = StructLoggerEmit {
486/// mem_size: cfg.enable_memory, // memSize travels with memory
487/// return_data: cfg.enable_return_data,
488/// refund: false, // no equivalent geth flag; off by default
489/// };
490/// ```
491#[derive(Debug, Clone, Copy, Default)]
492pub struct StructLoggerEmit {
493 /// Emit `memSize` even when its value is meaningful at every step.
494 /// Geth ties this to memory capture; default `false` matches geth's default config.
495 pub mem_size: bool,
496 /// Emit `returnData` (as `"0x..."` hex). Default `false` matches geth.
497 pub return_data: bool,
498 /// Force-emit `refund` even when it's zero. Default `false` matches geth's
499 /// `omitempty` behavior — non-zero refund is always emitted regardless of this flag.
500 pub refund: bool,
501}
502
503/// Wraps an [`OpcodeStep`] to serialize in the geth-RPC `structLogger` shape used by
504/// `debug_traceTransaction`. See module-level docs and the comment above this type
505/// for the field-shape divergences from EIP-3155.
506pub struct StructLoggerStep<'a> {
507 pub step: &'a OpcodeStep,
508 pub emit: StructLoggerEmit,
509}
510
511impl serde::Serialize for StructLoggerStep<'_> {
512 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
513 use serde::ser::SerializeMap;
514 let step = self.step;
515 let emit = self.emit;
516
517 // pc, op, gas, gasCost, depth, stack are always emitted (6 base fields).
518 let mut field_count = 6;
519 if emit.mem_size {
520 field_count += 1;
521 }
522 if emit.return_data {
523 field_count += 1;
524 }
525 if emit.refund || step.refund != 0 {
526 field_count += 1;
527 }
528 if step.error.is_some() {
529 field_count += 1;
530 }
531 if step.memory.is_some() {
532 field_count += 1;
533 }
534 if step.storage.is_some() {
535 field_count += 1;
536 }
537
538 let mut map = serializer.serialize_map(Some(field_count))?;
539
540 map.serialize_entry("pc", &step.pc)?;
541 // op: string mnemonic, matching geth's wire output (NOT EIP-3155's numeric form).
542 map.serialize_entry("op", &opcode_name_or_fallback(step.op))?;
543 // gas/gasCost/refund: decimal JSON numbers, matching geth's wire output.
544 map.serialize_entry("gas", &step.gas)?;
545 map.serialize_entry("gasCost", &step.gas_cost)?;
546 map.serialize_entry("depth", &step.depth)?;
547
548 // stack: JSON null when disabled, array of `"0xN"` hex strings when enabled.
549 // Matches geth's RPC behavior; diverges from EIP-3155's "MUST be []" rule.
550 struct StackSerializer<'a>(&'a Option<Vec<U256>>);
551 impl serde::Serialize for StackSerializer<'_> {
552 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
553 use serde::ser::SerializeSeq;
554 match self.0 {
555 None => serializer.serialize_none(),
556 Some(vec) => {
557 let mut seq = serializer.serialize_seq(Some(vec.len()))?;
558 for v in vec {
559 seq.serialize_element(&geth_uint256_hex(v))?;
560 }
561 seq.end()
562 }
563 }
564 }
565 }
566 map.serialize_entry("stack", &StackSerializer(&step.stack))?;
567
568 if emit.mem_size {
569 map.serialize_entry("memSize", &step.mem_size)?;
570 }
571 if emit.return_data {
572 map.serialize_entry(
573 "returnData",
574 &format!("0x{}", hex::encode(&step.return_data)),
575 )?;
576 }
577 // `refund` is omitempty-for-zero in geth's wire output: always emitted when
578 // non-zero; emitted-when-zero only when the caller forces it via `emit.refund`.
579 if emit.refund || step.refund != 0 {
580 map.serialize_entry("refund", &step.refund)?;
581 }
582
583 if let Some(err) = &step.error {
584 map.serialize_entry("error", err)?;
585 }
586 if let Some(mem) = &step.memory {
587 map.serialize_entry("memory", mem)?;
588 }
589 if let Some(storage) = &step.storage {
590 struct Wrap<'a>(&'a BTreeMap<H256, H256>);
591 impl serde::Serialize for Wrap<'_> {
592 fn serialize<S: serde::Serializer>(
593 &self,
594 serializer: S,
595 ) -> Result<S::Ok, S::Error> {
596 serialize_storage_map(serializer, self.0)
597 }
598 }
599 map.serialize_entry("storage", &Wrap(storage))?;
600 }
601
602 map.end()
603 }
604}
605
606/// Wraps an [`OpcodeTraceResult`] to serialize as the geth-RPC `debug_traceTransaction`
607/// response: `{failed, gas, returnValue, structLogs: [...]}`. Each step inside
608/// `structLogs` is itself serialized via [`StructLoggerStep`] using the same `emit` flags.
609pub struct StructLoggerResult<'a> {
610 pub result: &'a OpcodeTraceResult,
611 pub emit: StructLoggerEmit,
612}
613
614impl serde::Serialize for StructLoggerResult<'_> {
615 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
616 use serde::ser::{SerializeMap, SerializeSeq};
617 let r = self.result;
618 let emit = self.emit;
619
620 // structLogs uses StructLoggerStep for each entry, with the same emit options.
621 struct Steps<'a> {
622 steps: &'a [OpcodeStep],
623 emit: StructLoggerEmit,
624 }
625 impl serde::Serialize for Steps<'_> {
626 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
627 let mut seq = serializer.serialize_seq(Some(self.steps.len()))?;
628 for s in self.steps {
629 seq.serialize_element(&StructLoggerStep {
630 step: s,
631 emit: self.emit,
632 })?;
633 }
634 seq.end()
635 }
636 }
637
638 let mut map = serializer.serialize_map(Some(4))?;
639 // `failed` is the inverse of `pass` — matches the geth wire shape.
640 map.serialize_entry("failed", &!r.pass)?;
641 map.serialize_entry("gas", &r.gas_used)?;
642 map.serialize_entry("returnValue", &format!("0x{}", hex::encode(&r.output)))?;
643 map.serialize_entry(
644 "structLogs",
645 &Steps {
646 steps: &r.steps,
647 emit,
648 },
649 )?;
650 map.end()
651 }
652}
653
654// ─── Wire format: EIP-3155 ────────────────────────────────────────────────
655//
656// The shape defined by EIP-3155 §"Required Fields":
657//
658// - `op`: numeric opcode byte (e.g. `96` for PUSH1).
659// - `opName`: separate string mnemonic, always emitted (technically optional per spec).
660// - `gas`, `gasCost`, `refund`: `"0xN"` hex strings ("Hex-Number" per spec).
661// - `stack`: always an array, never null (spec: "All array attributes MUST be
662// initialized to empty arrays NOT to null").
663//
664// Field order matches the spec's listed order. Used by streaming sinks that feed
665// EIP-3155-conformant tooling (goevmlab, fuzzers). NOT used by `debug_traceTransaction`,
666// where existing tooling expects the structLogger shape above.
667
668/// Wraps an [`OpcodeStep`] to serialize in strict EIP-3155 shape. See module-level
669/// docs and the comment above this type for the field-shape choices.
670pub struct Eip3155Step<'a>(pub &'a OpcodeStep);
671
672impl serde::Serialize for Eip3155Step<'_> {
673 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
674 use serde::ser::SerializeMap;
675 let step = self.0;
676
677 let mut field_count = 10; // required 9 + always-emitted opName
678 if step.error.is_some() {
679 field_count += 1;
680 }
681 if step.memory.is_some() {
682 field_count += 1;
683 }
684 if step.storage.is_some() {
685 field_count += 1;
686 }
687
688 let mut map = serializer.serialize_map(Some(field_count))?;
689
690 // Required fields in spec order.
691 map.serialize_entry("pc", &step.pc)?;
692 map.serialize_entry("op", &step.op)?;
693 map.serialize_entry("gas", &format!("{:#x}", step.gas))?;
694 map.serialize_entry("gasCost", &format!("{:#x}", step.gas_cost))?;
695 map.serialize_entry("memSize", &step.mem_size)?;
696
697 // stack: always an array; `None` (disabled) becomes `[]`.
698 struct StackSerializer<'a>(&'a Option<Vec<U256>>);
699 impl serde::Serialize for StackSerializer<'_> {
700 fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
701 use serde::ser::SerializeSeq;
702 let vec_ref: &[U256] = self.0.as_deref().unwrap_or(&[]);
703 let mut seq = serializer.serialize_seq(Some(vec_ref.len()))?;
704 for v in vec_ref {
705 seq.serialize_element(&geth_uint256_hex(v))?;
706 }
707 seq.end()
708 }
709 }
710 map.serialize_entry("stack", &StackSerializer(&step.stack))?;
711
712 map.serialize_entry("depth", &step.depth)?;
713 map.serialize_entry(
714 "returnData",
715 &format!("0x{}", hex::encode(&step.return_data)),
716 )?;
717 map.serialize_entry("refund", &format!("{:#x}", step.refund))?;
718
719 // Optional fields in spec order: opName, error, memory, storage.
720 // opName always emitted (covers both known and unknown opcode bytes).
721 map.serialize_entry("opName", &opcode_name_or_fallback(step.op))?;
722
723 if let Some(err) = &step.error {
724 map.serialize_entry("error", err)?;
725 }
726 if let Some(mem) = &step.memory {
727 map.serialize_entry("memory", mem)?;
728 }
729 if let Some(storage) = &step.storage {
730 struct Wrap<'a>(&'a BTreeMap<H256, H256>);
731 impl serde::Serialize for Wrap<'_> {
732 fn serialize<S: serde::Serializer>(
733 &self,
734 serializer: S,
735 ) -> Result<S::Ok, S::Error> {
736 serialize_storage_map(serializer, self.0)
737 }
738 }
739 map.serialize_entry("storage", &Wrap(storage))?;
740 }
741
742 map.end()
743 }
744}