pallet_revive/tracing.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use crate::{Code, DispatchError, Key, Weight, evm::Bytes, primitives::ExecReturnValue};
19use alloc::vec::Vec;
20use environmental::environmental;
21use sp_core::{H160, H256, U256};
22
23environmental!(tracer: dyn Tracing + 'static);
24
25/// Synthetic syscall name used for tracing PVM interpreter fuel consumption between real syscalls.
26pub const PVM_FUEL_NAME: &str = "pvm_fuel";
27
28/// Trace the execution of the given closure.
29///
30/// # Warning
31///
32/// Only meant to be called from off-chain code as its additional resource usage is
33/// not accounted for in the weights or memory envelope.
34pub fn trace<R, F: FnOnce() -> R>(tracer: &mut (dyn Tracing + 'static), f: F) -> R {
35 tracer::using_once(tracer, f)
36}
37
38/// Run the closure when tracing is enabled.
39///
40/// This is safe to be called from on-chain code as tracing will never be activated
41/// there. Hence the closure is not executed in this case.
42pub(crate) fn if_tracing<R, F: FnOnce(&mut (dyn Tracing + 'static)) -> R>(f: F) -> Option<R> {
43 tracer::with(f)
44}
45
46/// Interface to provide frame trace information for the current execution frame.
47pub trait FrameTraceInfo {
48 /// Get the amount of gas remaining in the current frame.
49 fn gas_left(&self) -> u64;
50
51 /// Returns how much weight was spent
52 fn weight_consumed(&self) -> Weight;
53
54 /// Get the output from the last frame.
55 fn last_frame_output(&self) -> Bytes;
56}
57
58/// Interface to provide EVM-specific trace information for the current execution frame.
59pub trait EVMFrameTraceInfo: FrameTraceInfo {
60 /// Get a snapshot of the memory at this point in execution.
61 ///
62 /// # Parameters
63 /// - `limit`: Maximum number of memory words to capture.
64 fn memory_snapshot(&self, limit: usize) -> Vec<Bytes>;
65
66 /// Get a snapshot of the stack at this point in execution.
67 fn stack_snapshot(&self) -> Vec<Bytes>;
68}
69
70/// Defines methods to trace contract interactions.
71///
72/// # Contract
73///
74/// Every [`Tracing::enter_opcode`] and [`Tracing::enter_ecall`] must be followed by exactly one
75/// [`Tracing::exit_step`], on every path including reverts and traps. Tracers pair the two to
76/// attribute a step's cost, so an unmatched call charges that step to an enclosing one.
77pub trait Tracing {
78 /// Register an address that should be traced.
79 fn watch_address(&mut self, _addr: &H160) {}
80
81 /// Called before a contract call is executed.
82 ///
83 /// - `code_address`: When code is loaded from a different address than `to` (DELEGATECALL or
84 /// EIP-7702 delegation), this is that source address.
85 /// - `is_delegate_call`: true for DELEGATECALL frames (not EIP-7702 delegation).
86 /// - `gas_limit`: gas forwarded to the child call
87 fn enter_child_span(
88 &mut self,
89 _from: H160,
90 _to: H160,
91 _code_address: Option<H160>,
92 _is_delegate_call: bool,
93 _is_read_only: bool,
94 _value: U256,
95 _input: &[u8],
96 _gas_limit: u64,
97 ) {
98 }
99
100 /// Called when a contract calls terminates (selfdestructs)
101 fn terminate(
102 &mut self,
103 _contract_address: H160,
104 _beneficiary_address: H160,
105 _gas_left: u64,
106 _value: U256,
107 ) {
108 }
109
110 /// Record the next code and salt to be instantiated.
111 fn instantiate_code(&mut self, _code: &Code, _salt: Option<&[u8; 32]>) {}
112
113 /// Called when a balance is read
114 fn balance_read(&mut self, _addr: &H160, _value: U256) {}
115
116 /// Called when storage read is called
117 fn storage_read(&mut self, _key: &Key, _value: Option<&[u8]>) {}
118
119 /// Called when storage write is called
120 fn storage_write(
121 &mut self,
122 _key: &Key,
123 _old_value: Option<Vec<u8>>,
124 _new_value: Option<&[u8]>,
125 ) {
126 }
127
128 /// Record a log event
129 fn log_event(&mut self, _event: H160, _topics: &[H256], _data: &[u8], _log_index: u32) {}
130
131 /// Called after a contract call is executed
132 fn exit_child_span(
133 &mut self,
134 _output: &ExecReturnValue,
135 _gas_used: u64,
136 _weight_consumed: Weight,
137 ) {
138 }
139
140 /// Called when a contract call terminates with an error
141 fn exit_child_span_with_error(
142 &mut self,
143 _error: DispatchError,
144 _gas_used: u64,
145 _weight_consumed: Weight,
146 ) {
147 }
148
149 /// Check if the tracer is an execution tracer.
150 fn is_execution_tracer(&self) -> bool {
151 false
152 }
153
154 /// Called before an EVM opcode is executed.
155 ///
156 /// # Parameters
157 /// - `pc`: The current program counter.
158 /// - `opcode`: The opcode being executed.
159 /// - `trace_info`: Information about the current execution frame.
160 fn enter_opcode(&mut self, _pc: u64, _opcode: u8, _trace_info: &dyn EVMFrameTraceInfo) {}
161
162 /// Called before a PVM syscall is executed.
163 ///
164 /// # Parameters
165 /// - `ecall`: The name of the syscall being executed.
166 /// - `args`: The syscall arguments (register values).
167 /// - `trace_info`: Information about the current execution frame.
168 fn enter_ecall(
169 &mut self,
170 _ecall: &'static str,
171 _args: &[u64],
172 _trace_info: &dyn FrameTraceInfo,
173 ) {
174 }
175
176 /// Called after an EVM opcode or PVM syscall is executed to record the gas cost.
177 ///
178 /// # Parameters
179 /// - `trace_info`: Information about the current execution frame.
180 /// - `returned`: The syscall return value (PVM only, `None` for EVM opcodes).
181 fn exit_step(&mut self, _trace_info: &dyn FrameTraceInfo, _returned: Option<u64>) {}
182
183 /// Called once the transaction completes to report the gas consumed by the meter.
184 ///
185 /// # Parameters
186 /// - `base_call_weight`: Extrinsic base weight that is added on top of `weight_consumed` when
187 /// charging.
188 /// - `weight_consumed`: Weight used by the transaction logic, excluding the extrinsic base
189 /// weight.
190 fn dispatch_result(&mut self, _base_call_weight: Weight, _weight_consumed: Weight) {}
191}