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 /// For CALL/DELEGATECALL opcodes:
84 /// - `gas_limit`: gas forwarded to the child call
85 fn enter_child_span(
86 &mut self,
87 _from: H160,
88 _to: H160,
89 _delegate_call: Option<H160>,
90 _is_read_only: bool,
91 _value: U256,
92 _input: &[u8],
93 _gas_limit: u64,
94 ) {
95 }
96
97 /// Called when a contract calls terminates (selfdestructs)
98 fn terminate(
99 &mut self,
100 _contract_address: H160,
101 _beneficiary_address: H160,
102 _gas_left: u64,
103 _value: U256,
104 ) {
105 }
106
107 /// Record the next code and salt to be instantiated.
108 fn instantiate_code(&mut self, _code: &Code, _salt: Option<&[u8; 32]>) {}
109
110 /// Called when a balance is read
111 fn balance_read(&mut self, _addr: &H160, _value: U256) {}
112
113 /// Called when storage read is called
114 fn storage_read(&mut self, _key: &Key, _value: Option<&[u8]>) {}
115
116 /// Called when storage write is called
117 fn storage_write(
118 &mut self,
119 _key: &Key,
120 _old_value: Option<Vec<u8>>,
121 _new_value: Option<&[u8]>,
122 ) {
123 }
124
125 /// Record a log event
126 fn log_event(&mut self, _event: H160, _topics: &[H256], _data: &[u8], _log_index: u32) {}
127
128 /// Called after a contract call is executed
129 fn exit_child_span(
130 &mut self,
131 _output: &ExecReturnValue,
132 _gas_used: u64,
133 _weight_consumed: Weight,
134 ) {
135 }
136
137 /// Called when a contract call terminates with an error
138 fn exit_child_span_with_error(
139 &mut self,
140 _error: DispatchError,
141 _gas_used: u64,
142 _weight_consumed: Weight,
143 ) {
144 }
145
146 /// Check if the tracer is an execution tracer.
147 fn is_execution_tracer(&self) -> bool {
148 false
149 }
150
151 /// Called before an EVM opcode is executed.
152 ///
153 /// # Parameters
154 /// - `pc`: The current program counter.
155 /// - `opcode`: The opcode being executed.
156 /// - `trace_info`: Information about the current execution frame.
157 fn enter_opcode(&mut self, _pc: u64, _opcode: u8, _trace_info: &dyn EVMFrameTraceInfo) {}
158
159 /// Called before a PVM syscall is executed.
160 ///
161 /// # Parameters
162 /// - `ecall`: The name of the syscall being executed.
163 /// - `args`: The syscall arguments (register values).
164 /// - `trace_info`: Information about the current execution frame.
165 fn enter_ecall(
166 &mut self,
167 _ecall: &'static str,
168 _args: &[u64],
169 _trace_info: &dyn FrameTraceInfo,
170 ) {
171 }
172
173 /// Called after an EVM opcode or PVM syscall is executed to record the gas cost.
174 ///
175 /// # Parameters
176 /// - `trace_info`: Information about the current execution frame.
177 /// - `returned`: The syscall return value (PVM only, `None` for EVM opcodes).
178 fn exit_step(&mut self, _trace_info: &dyn FrameTraceInfo, _returned: Option<u64>) {}
179
180 /// Called once the transaction completes to report the gas consumed by the meter.
181 ///
182 /// # Parameters
183 /// - `base_call_weight`: Extrinsic base weight that is added on top of `weight_consumed` when
184 /// charging.
185 /// - `weight_consumed`: Weight used by the transaction logic, excluding the extrinsic base
186 /// weight.
187 fn dispatch_result(&mut self, _base_call_weight: Weight, _weight_consumed: Weight) {}
188}