revm_inspector/
eip3155.rs

1use crate::inspectors::GasInspector;
2use crate::Inspector;
3use context::{Cfg, ContextTr, Journal, Transaction};
4use interpreter::{
5    interpreter_types::{Jumps, LoopControl, MemoryTr, RuntimeFlag, StackTr, SubRoutineStack},
6    CallInputs, CallOutcome, CreateInputs, CreateOutcome, Interpreter, InterpreterResult,
7    InterpreterTypes, Stack,
8};
9use primitives::{hex, HashMap, B256, U256};
10use serde::Serialize;
11use state::bytecode::opcode::OpCode;
12use std::io::Write;
13
14/// [EIP-3155](https://eips.ethereum.org/EIPS/eip-3155) tracer [Inspector].
15pub struct TracerEip3155 {
16    output: Box<dyn Write>,
17    gas_inspector: GasInspector,
18    /// Print summary of the execution.
19    print_summary: bool,
20    stack: Vec<U256>,
21    pc: u64,
22    section: Option<u64>,
23    function_depth: Option<u64>,
24    opcode: u8,
25    gas: u64,
26    refunded: i64,
27    mem_size: usize,
28    skip: bool,
29    include_memory: bool,
30    memory: Option<String>,
31}
32
33// # Output
34// The CUT MUST output a `json` object for EACH operation.
35#[derive(Serialize)]
36#[serde(rename_all = "camelCase")]
37struct Output<'a> {
38    // Required fields:
39    /// Program counter
40    pc: u64,
41    /// EOF code section
42    #[serde(default, skip_serializing_if = "Option::is_none")]
43    section: Option<u64>,
44    /// OpCode
45    op: u8,
46    /// Gas left before executing this operation
47    #[serde(serialize_with = "serde_hex_u64")]
48    gas: u64,
49    /// Gas cost of this operation
50    #[serde(serialize_with = "serde_hex_u64")]
51    gas_cost: u64,
52    /// Array of all values on the stack
53    stack: &'a [U256],
54    /// Depth of the call stack
55    depth: u64,
56    /// Depth of the EOF function call stack
57    #[serde(default, skip_serializing_if = "Option::is_none")]
58    function_depth: Option<u64>,
59    /// Data returned by the function call
60    return_data: &'static str,
61    /// Amount of **global** gas refunded
62    #[serde(serialize_with = "serde_hex_u64")]
63    refund: u64,
64    /// Size of memory array
65    #[serde(serialize_with = "serde_hex_u64")]
66    mem_size: u64,
67
68    // Optional fields:
69    /// Name of the operation
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    op_name: Option<&'static str>,
72    /// Description of an error (should contain revert reason if supported)
73    #[serde(default, skip_serializing_if = "Option::is_none")]
74    error: Option<String>,
75    /// Array of all allocated values
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    memory: Option<String>,
78    /// Array of all stored values
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    storage: Option<HashMap<String, String>>,
81    /// Array of values, Stack of the called function
82    #[serde(default, skip_serializing_if = "Option::is_none")]
83    return_stack: Option<Vec<String>>,
84}
85
86// # Summary and error handling
87#[derive(Serialize)]
88#[serde(rename_all = "camelCase")]
89struct Summary {
90    // Required fields:
91    /// Root of the state trie after executing the transaction
92    state_root: String,
93    /// Return values of the function
94    output: String,
95    /// All gas used by the transaction
96    #[serde(serialize_with = "serde_hex_u64")]
97    gas_used: u64,
98    /// Bool whether transaction was executed successfully
99    pass: bool,
100
101    // Optional fields:
102    /// Time in nanoseconds needed to execute the transaction
103    #[serde(default, skip_serializing_if = "Option::is_none")]
104    time: Option<u128>,
105    /// Name of the fork rules used for execution
106    #[serde(default, skip_serializing_if = "Option::is_none")]
107    fork: Option<String>,
108}
109
110impl TracerEip3155 {
111    /// Creates a new EIP-3155 tracer with the given output writer, by first wrapping it in a
112    /// [`BufWriter`](std::io::BufWriter).
113    pub fn buffered(output: impl Write + 'static) -> Self {
114        Self::new(Box::new(std::io::BufWriter::new(output)))
115    }
116
117    /// Creates a new EIP-3155 tracer with the given output writer.
118    pub fn new(output: Box<dyn Write>) -> Self {
119        Self {
120            output,
121            gas_inspector: GasInspector::new(),
122            print_summary: true,
123            include_memory: false,
124            stack: Default::default(),
125            memory: Default::default(),
126            pc: 0,
127            section: None,
128            function_depth: None,
129            opcode: 0,
130            gas: 0,
131            refunded: 0,
132            mem_size: 0,
133            skip: false,
134        }
135    }
136
137    /// Sets the writer to use for the output.
138    pub fn set_writer(&mut self, writer: Box<dyn Write>) {
139        self.output = writer;
140    }
141
142    /// Don't include a summary at the end of the trace
143    pub fn without_summary(mut self) -> Self {
144        self.print_summary = false;
145        self
146    }
147
148    /// Include a memory field for each step. This significantly increases processing time and output size.
149    pub fn with_memory(mut self) -> Self {
150        self.include_memory = true;
151        self
152    }
153
154    /// Resets the tracer to its initial state of [`Self::new`].
155    ///
156    /// This makes the inspector ready to be used again.
157    pub fn clear(&mut self) {
158        let Self {
159            gas_inspector,
160            stack,
161            pc,
162            opcode,
163            gas,
164            refunded,
165            mem_size,
166            skip,
167            ..
168        } = self;
169        *gas_inspector = GasInspector::new();
170        stack.clear();
171        *pc = 0;
172        *opcode = 0;
173        *gas = 0;
174        *refunded = 0;
175        *mem_size = 0;
176        *skip = false;
177    }
178
179    fn print_summary(&mut self, result: &InterpreterResult, context: &mut impl ContextTr) {
180        if !self.print_summary {
181            return;
182        }
183        let spec = context.cfg().spec().into();
184        let gas_limit = context.tx().gas_limit();
185        let value = Summary {
186            state_root: B256::ZERO.to_string(),
187            output: result.output.to_string(),
188            gas_used: gas_limit - self.gas_inspector.gas_remaining(),
189            pass: result.is_ok(),
190            time: None,
191            fork: Some(spec.to_string()),
192        };
193        let _ = self.write_value(&value);
194    }
195
196    fn write_value(&mut self, value: &impl serde::Serialize) -> std::io::Result<()> {
197        write_value(&mut *self.output, value)
198    }
199}
200
201pub trait CloneStack {
202    fn clone_into(&self, stack: &mut Vec<U256>);
203}
204
205impl CloneStack for Stack {
206    fn clone_into(&self, stack: &mut Vec<U256>) {
207        stack.extend_from_slice(self.data());
208    }
209}
210
211impl<CTX, INTR> Inspector<CTX, INTR> for TracerEip3155
212where
213    CTX: ContextTr,
214    INTR: InterpreterTypes<Stack: StackTr + CloneStack>,
215{
216    fn initialize_interp(&mut self, interp: &mut Interpreter<INTR>, _: &mut CTX) {
217        self.gas_inspector.initialize_interp(interp.control.gas());
218    }
219
220    fn step(&mut self, interp: &mut Interpreter<INTR>, _: &mut CTX) {
221        self.gas_inspector.step(interp.control.gas());
222        self.stack.clear();
223        interp.stack.clone_into(&mut self.stack);
224        self.memory = if self.include_memory {
225            Some(hex::encode_prefixed(
226                interp.memory.slice(0..interp.memory.size()).as_ref(),
227            ))
228        } else {
229            None
230        };
231        self.pc = interp.bytecode.pc() as u64;
232        self.section = if interp.runtime_flag.is_eof() {
233            Some(interp.sub_routine.routine_idx() as u64)
234        } else {
235            None
236        };
237        self.function_depth = if interp.runtime_flag.is_eof() {
238            Some(interp.sub_routine.len() as u64 + 1)
239        } else {
240            None
241        };
242        self.opcode = interp.bytecode.opcode();
243        self.mem_size = interp.memory.size();
244        self.gas = interp.control.gas().remaining();
245        self.refunded = interp.control.gas().refunded();
246    }
247
248    fn step_end(&mut self, interp: &mut Interpreter<INTR>, context: &mut CTX) {
249        self.gas_inspector.step_end(interp.control.gas());
250        if self.skip {
251            self.skip = false;
252            return;
253        }
254
255        let value = Output {
256            pc: self.pc,
257            section: self.section,
258            op: self.opcode,
259            gas: self.gas,
260            gas_cost: self.gas_inspector.last_gas_cost(),
261            stack: &self.stack,
262            depth: context.journal().depth() as u64,
263            function_depth: self.function_depth,
264            return_data: "0x",
265            refund: self.refunded as u64,
266            mem_size: self.mem_size as u64,
267
268            op_name: OpCode::new(self.opcode).map(|i| i.as_str()),
269            error: if !interp.control.instruction_result().is_ok() {
270                Some(format!("{:?}", interp.control.instruction_result()))
271            } else {
272                None
273            },
274            memory: self.memory.take(),
275            storage: None,
276            return_stack: None,
277        };
278        let _ = write_value(&mut self.output, &value);
279    }
280
281    fn call_end(&mut self, context: &mut CTX, _: &CallInputs, outcome: &mut CallOutcome) {
282        self.gas_inspector.call_end(outcome);
283
284        if context.journal().depth() == 0 {
285            self.print_summary(&outcome.result, context);
286            let _ = self.output.flush();
287            // Clear the state if we are at the top level.
288            self.clear();
289        }
290    }
291
292    fn create_end(&mut self, context: &mut CTX, _: &CreateInputs, outcome: &mut CreateOutcome) {
293        self.gas_inspector.create_end(outcome);
294
295        if context.journal().depth() == 0 {
296            self.print_summary(&outcome.result, context);
297            let _ = self.output.flush();
298            // Clear the state if we are at the top level.
299            self.clear();
300        }
301    }
302}
303
304fn write_value(
305    output: &mut dyn std::io::Write,
306    value: &impl serde::Serialize,
307) -> std::io::Result<()> {
308    serde_json::to_writer(&mut *output, value)?;
309    output.write_all(b"\n")
310}
311
312fn serde_hex_u64<S: serde::Serializer>(n: &u64, serializer: S) -> Result<S::Ok, S::Error> {
313    serializer.serialize_str(&format!("{:#x}", *n))
314}