foundry_evm_traces/identifier/
local.rs1use super::{IdentifiedAddress, TraceIdentifier};
2use alloy_dyn_abi::JsonAbiExt;
3use alloy_json_abi::JsonAbi;
4use alloy_primitives::{Address, Bytes, map::HashMap};
5use foundry_common::contracts::{ContractsByArtifact, bytecode_diff_score};
6use foundry_compilers::ArtifactId;
7use revm_inspectors::tracing::types::CallTraceNode;
8use std::borrow::Cow;
9
10pub struct LocalTraceIdentifier<'a> {
12 known_contracts: &'a ContractsByArtifact,
14 ordered_ids: Vec<(&'a ArtifactId, usize)>,
16 contracts_bytecode: Option<&'a HashMap<Address, Bytes>>,
18}
19
20impl<'a> LocalTraceIdentifier<'a> {
21 pub fn new(known_contracts: &'a ContractsByArtifact) -> Self {
23 let mut ordered_ids = known_contracts
24 .iter()
25 .filter_map(|(id, contract)| Some((id, contract.deployed_bytecode()?)))
26 .map(|(id, bytecode)| (id, bytecode.len()))
27 .collect::<Vec<_>>();
28 ordered_ids.sort_by_key(|(_, len)| *len);
29 Self { known_contracts, ordered_ids, contracts_bytecode: None }
30 }
31
32 pub fn with_bytecodes(mut self, contracts_bytecode: &'a HashMap<Address, Bytes>) -> Self {
33 self.contracts_bytecode = Some(contracts_bytecode);
34 self
35 }
36
37 #[inline]
39 pub fn contracts(&self) -> &'a ContractsByArtifact {
40 self.known_contracts
41 }
42
43 pub fn identify_code(
45 &self,
46 runtime_code: &[u8],
47 creation_code: &[u8],
48 ) -> Option<(&'a ArtifactId, &'a JsonAbi)> {
49 let len = runtime_code.len();
50
51 let mut min_score = f64::MAX;
52 let mut min_score_id = None;
53
54 let mut check = |id, is_creation, min_score: &mut f64| {
55 let contract = self.known_contracts.get(id)?;
56 let (contract_bytecode, current_bytecode) = if is_creation {
58 (contract.bytecode_without_placeholders(), creation_code)
59 } else {
60 (contract.deployed_bytecode_without_placeholders(), runtime_code)
61 };
62
63 if let Some(bytecode) = contract_bytecode {
64 let mut current_bytecode = current_bytecode;
65 if is_creation && current_bytecode.len() > bytecode.len() {
66 if let Some(constructor) = contract.abi.constructor() {
68 let constructor_args = ¤t_bytecode[bytecode.len()..];
69 if constructor.abi_decode_input(constructor_args).is_ok() {
70 current_bytecode = ¤t_bytecode[..bytecode.len()]
73 }
74 }
75 }
76
77 let score = bytecode_diff_score(&bytecode, current_bytecode);
78 if score == 0.0 {
79 trace!(target: "evm::traces::local", "found exact match");
80 return Some((id, &contract.abi));
81 }
82 if score < *min_score {
83 *min_score = score;
84 min_score_id = Some((id, &contract.abi));
85 }
86 }
87 None
88 };
89
90 let max_len = (len * 11) / 10;
92
93 let same_length_idx = self.find_index(len);
95 for idx in same_length_idx..self.ordered_ids.len() {
96 let (id, len) = self.ordered_ids[idx];
97 if len > max_len {
98 break;
99 }
100 if let found @ Some(_) = check(id, true, &mut min_score) {
101 return found;
102 }
103 }
104
105 let min_len = (len * 9) / 10;
107 let idx = self.find_index(min_len);
108 for i in idx..same_length_idx {
109 let (id, _) = self.ordered_ids[i];
110 if let found @ Some(_) = check(id, true, &mut min_score) {
111 return found;
112 }
113 }
114
115 if min_score >= 0.85 {
117 for (artifact, _) in &self.ordered_ids {
118 if let found @ Some(_) = check(artifact, false, &mut min_score) {
119 return found;
120 }
121 }
122 }
123
124 trace!(target: "evm::traces::local", %min_score, "no exact match found");
125
126 if min_score < 0.85 { min_score_id } else { None }
129 }
130
131 fn find_index(&self, len: usize) -> usize {
134 let (Ok(mut idx) | Err(mut idx)) =
135 self.ordered_ids.binary_search_by_key(&len, |(_, probe)| *probe);
136
137 while idx > 0 && self.ordered_ids[idx - 1].1 == len {
139 idx -= 1;
140 }
141
142 idx
143 }
144}
145
146impl TraceIdentifier for LocalTraceIdentifier<'_> {
147 fn identify_addresses(&mut self, nodes: &[&CallTraceNode]) -> Vec<IdentifiedAddress<'_>> {
148 if nodes.is_empty() {
149 return Vec::new();
150 }
151
152 trace!(target: "evm::traces::local", "identify {} addresses", nodes.len());
153
154 nodes
155 .iter()
156 .map(|&node| {
157 (
158 node.trace.address,
159 node.trace.kind.is_any_create().then_some(&node.trace.output[..]),
160 node.trace.kind.is_any_create().then_some(&node.trace.data[..]),
161 )
162 })
163 .filter_map(|(address, runtime_code, creation_code)| {
164 let _span =
165 trace_span!(target: "evm::traces::local", "identify", %address).entered();
166
167 let (runtime_code, creation_code) = match (runtime_code, creation_code) {
171 (Some(runtime_code), Some(creation_code)) => (runtime_code, creation_code),
172 (Some(runtime_code), _) => (runtime_code, &[] as &[u8]),
173 _ => {
174 let code = self.contracts_bytecode?.get(&address)?;
175 (code.as_ref(), &[] as &[u8])
176 }
177 };
178 let (id, abi) = self.identify_code(runtime_code, creation_code)?;
179 trace!(target: "evm::traces::local", id=%id.identifier(), "identified");
180
181 Some(IdentifiedAddress {
182 address,
183 contract: Some(id.identifier()),
184 label: Some(id.name.clone()),
185 abi: Some(Cow::Borrowed(abi)),
186 artifact_id: Some(id.clone()),
187 })
188 })
189 .collect()
190 }
191}