-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathlib.rs
319 lines (283 loc) · 9.79 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
//! # foundry-evm-traces
//!
//! EVM trace identifying and decoding.
#![warn(unreachable_pub, unused_crate_dependencies, rust_2018_idioms)]
#[macro_use]
extern crate tracing;
use alloy_primitives::LogData;
use foundry_common::contracts::{ContractsByAddress, ContractsByArtifact};
use foundry_evm_core::constants::CHEATCODE_ADDRESS;
use futures::{future::BoxFuture, FutureExt};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, fmt::Write};
use yansi::{Color, Paint};
/// Call trace address identifiers.
///
/// Identifiers figure out what ABIs and labels belong to all the addresses of the trace.
pub mod identifier;
use identifier::LocalTraceIdentifier;
mod decoder;
pub use decoder::{CallTraceDecoder, CallTraceDecoderBuilder};
use revm_inspectors::tracing::types::LogCallOrder;
pub use revm_inspectors::tracing::{
types::{CallKind, CallTrace, CallTraceNode},
CallTraceArena, GethTraceBuilder, ParityTraceBuilder, StackSnapshotType, TracingInspector,
TracingInspectorConfig,
};
pub type Traces = Vec<(TraceKind, CallTraceArena)>;
#[derive(Default, Debug, Eq, PartialEq)]
pub struct DecodedCallData {
pub signature: String,
pub args: Vec<String>,
}
#[derive(Default, Debug)]
pub struct DecodedCallTrace {
pub label: Option<String>,
pub return_data: Option<String>,
pub func: Option<DecodedCallData>,
pub contract: Option<String>,
}
#[derive(Debug)]
pub enum DecodedCallLog<'a> {
/// A raw log.
Raw(&'a LogData),
/// A decoded log.
///
/// The first member of the tuple is the event name, and the second is a vector of decoded
/// parameters.
Decoded(String, Vec<(String, String)>),
}
const PIPE: &str = " │ ";
const EDGE: &str = " └─ ";
const BRANCH: &str = " ├─ ";
const CALL: &str = "→ ";
const RETURN: &str = "← ";
/// Render a collection of call traces.
///
/// The traces will be decoded using the given decoder, if possible.
pub async fn render_trace_arena(
arena: &CallTraceArena,
decoder: &CallTraceDecoder,
) -> Result<String, std::fmt::Error> {
decoder.prefetch_signatures(arena.nodes()).await;
fn inner<'a>(
arena: &'a [CallTraceNode],
decoder: &'a CallTraceDecoder,
s: &'a mut String,
idx: usize,
left: &'a str,
child: &'a str,
) -> BoxFuture<'a, Result<(), std::fmt::Error>> {
async move {
let node = &arena[idx];
// Display trace header
let (trace, return_data) = render_trace(&node.trace, decoder).await?;
writeln!(s, "{left}{}", trace)?;
// Display logs and subcalls
let left_prefix = format!("{child}{BRANCH}");
let right_prefix = format!("{child}{PIPE}");
for child in &node.ordering {
match child {
LogCallOrder::Log(index) => {
let log = render_trace_log(&node.logs[*index], decoder).await?;
// Prepend our tree structure symbols to each line of the displayed log
log.lines().enumerate().try_for_each(|(i, line)| {
writeln!(
s,
"{}{}",
if i == 0 { &left_prefix } else { &right_prefix },
line
)
})?;
}
LogCallOrder::Call(index) => {
inner(
arena,
decoder,
s,
node.children[*index],
&left_prefix,
&right_prefix,
)
.await?;
}
}
}
// Display trace return data
let color = trace_color(&node.trace);
write!(s, "{child}{EDGE}{}", color.paint(RETURN))?;
if node.trace.kind.is_any_create() {
match &return_data {
None => {
writeln!(s, "{} bytes of code", node.trace.data.len())?;
}
Some(val) => {
writeln!(s, "{val}")?;
}
}
} else {
match &return_data {
None if node.trace.output.is_empty() => writeln!(s, "()")?,
None => writeln!(s, "{}", node.trace.output)?,
Some(val) => writeln!(s, "{val}")?,
}
}
Ok(())
}
.boxed()
}
let mut s = String::new();
inner(arena.nodes(), decoder, &mut s, 0, " ", " ").await?;
Ok(s)
}
/// Render a call trace.
///
/// The trace will be decoded using the given decoder, if possible.
pub async fn render_trace(
trace: &CallTrace,
decoder: &CallTraceDecoder,
) -> Result<(String, Option<String>), std::fmt::Error> {
let mut s = String::new();
write!(&mut s, "[{}] ", trace.gas_used)?;
let address = trace.address.to_checksum(None);
let decoded = decoder.decode_function(trace).await;
if trace.kind.is_any_create() {
write!(
&mut s,
"{}{} {}@{}",
Paint::yellow(CALL),
Paint::yellow("new"),
decoded.label.as_deref().unwrap_or("<unknown>"),
address
)?;
} else {
let (func_name, inputs) = match &decoded.func {
Some(DecodedCallData { signature, args }) => {
let name = signature.split('(').next().unwrap();
(name.to_string(), args.join(", "))
}
None => {
debug!(target: "evm::traces", trace=?trace, "unhandled raw calldata");
if trace.data.len() < 4 {
("fallback".to_string(), hex::encode(&trace.data))
} else {
let (selector, data) = trace.data.split_at(4);
(hex::encode(selector), hex::encode(data))
}
}
};
let action = match trace.kind {
CallKind::Call => "",
CallKind::StaticCall => " [staticcall]",
CallKind::CallCode => " [callcode]",
CallKind::DelegateCall => " [delegatecall]",
CallKind::Create | CallKind::Create2 => unreachable!(),
};
let color = trace_color(trace);
write!(
&mut s,
"{addr}::{func_name}{opt_value}({inputs}){action}",
addr = color.paint(decoded.label.as_deref().unwrap_or(&address)),
func_name = color.paint(func_name),
opt_value = if trace.value.is_zero() {
String::new()
} else {
format!("{{value: {}}}", trace.value)
},
action = Paint::yellow(action),
)?;
}
Ok((s, decoded.return_data))
}
/// Render a trace log.
async fn render_trace_log(
log: &LogData,
decoder: &CallTraceDecoder,
) -> Result<String, std::fmt::Error> {
let mut s = String::new();
let decoded = decoder.decode_event(log).await;
match decoded {
DecodedCallLog::Raw(log) => {
for (i, topic) in log.topics().iter().enumerate() {
writeln!(
s,
"{:>13}: {}",
if i == 0 { "emit topic 0".to_string() } else { format!("topic {i}") },
Paint::cyan(format!("{topic:?}"))
)?;
}
write!(s, " data: {}", Paint::cyan(hex::encode_prefixed(&log.data)))?;
}
DecodedCallLog::Decoded(name, params) => {
let params = params
.iter()
.map(|(name, value)| format!("{name}: {value}"))
.collect::<Vec<String>>()
.join(", ");
write!(s, "emit {}({params})", Paint::cyan(name.clone()))?;
}
}
Ok(s)
}
/// Specifies the kind of trace.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum TraceKind {
Deployment,
Setup,
Execution,
}
impl TraceKind {
/// Returns `true` if the trace kind is [`Deployment`].
///
/// [`Deployment`]: TraceKind::Deployment
#[must_use]
pub fn is_deployment(self) -> bool {
matches!(self, Self::Deployment)
}
/// Returns `true` if the trace kind is [`Setup`].
///
/// [`Setup`]: TraceKind::Setup
#[must_use]
pub fn is_setup(self) -> bool {
matches!(self, Self::Setup)
}
/// Returns `true` if the trace kind is [`Execution`].
///
/// [`Execution`]: TraceKind::Execution
#[must_use]
pub fn is_execution(self) -> bool {
matches!(self, Self::Execution)
}
}
/// Chooses the color of the trace depending on the destination address and status of the call.
fn trace_color(trace: &CallTrace) -> Color {
if trace.address == CHEATCODE_ADDRESS {
Color::Blue
} else if trace.success {
Color::Green
} else {
Color::Red
}
}
/// Given a list of traces and artifacts, it returns a map connecting address to abi
pub fn load_contracts(
traces: Traces,
known_contracts: Option<&ContractsByArtifact>,
) -> ContractsByAddress {
let Some(contracts) = known_contracts else { return BTreeMap::new() };
let mut local_identifier = LocalTraceIdentifier::new(contracts);
let mut decoder = CallTraceDecoderBuilder::new().build();
for (_, trace) in &traces {
decoder.identify(trace, &mut local_identifier);
}
decoder
.contracts
.iter()
.filter_map(|(addr, name)| {
if let Ok(Some((_, (abi, _)))) = contracts.find_by_name_or_identifier(name) {
return Some((*addr, (name.clone(), abi.clone())));
}
None
})
.collect()
}