Skip to main content

foundry_evm_traces/identifier/
local.rs

1use super::{IdentifiedAddress, TraceIdentifier};
2use crate::CallTraceNode;
3use alloy_dyn_abi::JsonAbiExt;
4use alloy_json_abi::JsonAbi;
5use alloy_primitives::{Bytes, map::AddressHashMap};
6use foundry_common::contracts::{
7    ContractData, ContractsByArtifact, bytecode_diff_score, matches_contract_creation,
8};
9use foundry_compilers::ArtifactId;
10use std::borrow::Cow;
11
12/// A trace identifier that tries to identify addresses using local contracts.
13pub struct LocalTraceIdentifier<'a> {
14    /// Known contracts to search through.
15    known_contracts: &'a ContractsByArtifact,
16    /// Artifact IDs and their contracts, ordered by the runtime code length of the artifact.
17    ordered_ids: Vec<(&'a ArtifactId, &'a ContractData, usize)>,
18    /// The contracts bytecode.
19    contracts_bytecode: Option<&'a AddressHashMap<Bytes>>,
20}
21
22impl<'a> LocalTraceIdentifier<'a> {
23    /// Creates a new local trace identifier.
24    pub fn new(known_contracts: &'a ContractsByArtifact) -> Self {
25        let mut ordered_ids = known_contracts
26            .iter()
27            .filter_map(|(id, contract)| Some((id, contract, contract.deployed_bytecode()?.len())))
28            .collect::<Vec<_>>();
29        ordered_ids.sort_by_key(|(_, _, len)| *len);
30        Self { known_contracts, ordered_ids, contracts_bytecode: None }
31    }
32
33    pub const fn with_bytecodes(mut self, contracts_bytecode: &'a AddressHashMap<Bytes>) -> Self {
34        self.contracts_bytecode = Some(contracts_bytecode);
35        self
36    }
37
38    /// Returns the known contracts.
39    #[inline]
40    pub const fn contracts(&self) -> &'a ContractsByArtifact {
41        self.known_contracts
42    }
43
44    /// Identifies the artifact based on score computed for both creation and deployed bytecodes.
45    pub fn identify_code(
46        &self,
47        runtime_code: &[u8],
48        creation_code: &[u8],
49    ) -> Option<(&'a ArtifactId, &'a JsonAbi, Option<usize>)> {
50        let len = runtime_code.len();
51
52        let mut min_score = f64::MAX;
53        let mut min_score_id = None;
54
55        let mut check = |id, contract: &'a ContractData, is_creation, min_score: &mut f64| {
56            // Select bytecodes to compare based on `is_creation` flag.
57            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                let mut constructor_args_offset = None;
66                if is_creation && current_bytecode.len() > bytecode.len() {
67                    // Try to decode ctor args with contract abi.
68                    if let Some(constructor) = contract.abi.constructor() {
69                        let constructor_args = &current_bytecode[bytecode.len()..];
70                        if constructor.abi_decode_input(constructor_args).is_ok() {
71                            // If we can decode args with current abi then remove args from
72                            // code to compare.
73                            current_bytecode = &current_bytecode[..bytecode.len()];
74                            constructor_args_offset = Some(bytecode.len());
75                        }
76                    }
77                }
78
79                let score = bytecode_diff_score(&bytecode, current_bytecode);
80                if score == 0.0 {
81                    trace!(target: "evm::traces::local", "found exact match");
82                    return Some((id, &contract.abi, constructor_args_offset));
83                }
84                if score < *min_score {
85                    *min_score = score;
86                    min_score_id = Some((id, &contract.abi, constructor_args_offset));
87                }
88            }
89            None
90        };
91
92        if !creation_code.is_empty() {
93            // Check `[len * 0.9, ..., len * 1.1]`.
94            let max_len = (len * 11) / 10;
95
96            // Start at artifacts with the same code length: `len..len*1.1`.
97            let same_length_idx = self.find_index(len);
98            for &(id, contract, len) in &self.ordered_ids[same_length_idx..] {
99                if len > max_len {
100                    break;
101                }
102                if let found @ Some(_) = check(id, contract, true, &mut min_score) {
103                    return found;
104                }
105            }
106
107            // Iterate over the remaining artifacts with less code length: `len*0.9..len`.
108            let min_len = (len * 9) / 10;
109            let idx = self.find_index(min_len);
110            for &(id, contract, _) in &self.ordered_ids[idx..same_length_idx] {
111                if let found @ Some(_) = check(id, contract, true, &mut min_score) {
112                    return found;
113                }
114            }
115        }
116
117        // Constructors can return custom runtime whose length differs from the artifact's.
118        // Try exact creation matches outside the runtime-length window before fuzzy runtime
119        // matches. Prefer the longest initcode if another artifact matches only its prefix.
120        if !creation_code.is_empty()
121            && !runtime_code.is_empty()
122            && let Some((id, contract)) = self
123                .known_contracts
124                .iter()
125                .filter(|(_, contract)| matches_contract_creation(contract, creation_code))
126                .max_by_key(|(_, contract)| contract.bytecode().map(|bytecode| bytecode.len()))
127        {
128            // A constructor can return another artifact's runtime, including populated immutables
129            // and library references. Preserve its identity and ABI only if metadata also matches.
130            if let Some((id, contract)) =
131                self.known_contracts.find_by_deployed_code_exact_with_metadata(runtime_code)
132            {
133                return Some((id, &contract.abi, None));
134            }
135
136            let constructor_args_offset = contract
137                .bytecode()
138                .map(|bytecode| bytecode.len())
139                .filter(|&offset| offset < creation_code.len());
140            return Some((id, &contract.abi, constructor_args_offset));
141        }
142
143        // Fallback to comparing deployed code if min score greater than threshold.
144        if min_score >= 0.85 {
145            for &(id, contract, _) in &self.ordered_ids {
146                if let found @ Some(_) = check(id, contract, false, &mut min_score) {
147                    return found;
148                }
149            }
150        }
151
152        trace!(target: "evm::traces::local", %min_score, "no exact match found");
153
154        // Note: the diff score can be inaccurate for small contracts so we're using a relatively
155        // high threshold here to avoid filtering out too many contracts.
156        if min_score < 0.85 { min_score_id } else { None }
157    }
158
159    /// Returns the index of the artifact with the given code length, or the index of the first
160    /// artifact with a greater code length if the exact code length is not found.
161    fn find_index(&self, len: usize) -> usize {
162        let (Ok(mut idx) | Err(mut idx)) =
163            self.ordered_ids.binary_search_by_key(&len, |(_, _, probe)| *probe);
164
165        // In case of multiple artifacts with the same code length, we need to find the first one.
166        while idx > 0 && self.ordered_ids[idx - 1].2 == len {
167            idx -= 1;
168        }
169
170        idx
171    }
172}
173
174impl TraceIdentifier for LocalTraceIdentifier<'_> {
175    fn identify_addresses(&mut self, nodes: &[&CallTraceNode]) -> Vec<IdentifiedAddress<'_>> {
176        if nodes.is_empty() {
177            return Vec::new();
178        }
179
180        trace!(target: "evm::traces::local", "identify {} addresses", nodes.len());
181
182        nodes
183            .iter()
184            .map(|&node| {
185                (
186                    node.trace.address,
187                    node.trace.kind.is_any_create().then_some(&node.trace.output[..]),
188                    (node.trace.kind.is_any_create() && node.trace.success)
189                        .then_some(&node.trace.data[..]),
190                )
191            })
192            .filter_map(|(address, runtime_code, creation_code)| {
193                let _span =
194                    trace_span!(target: "evm::traces::local", "identify", %address).entered();
195
196                // In order to identify the addresses, we need at least the runtime code. It can be
197                // obtained from the trace itself (if it's a CREATE* call), or from the fetched
198                // bytecodes.
199                let (runtime_code, creation_code) = match (runtime_code, creation_code) {
200                    (Some(runtime_code), Some(creation_code)) => (runtime_code, creation_code),
201                    (Some(runtime_code), _) => (runtime_code, &[] as &[u8]),
202                    _ => {
203                        let code = self.contracts_bytecode?.get(&address)?;
204                        (code.as_ref(), &[] as &[u8])
205                    }
206                };
207                let (id, abi, constructor_args_offset) =
208                    self.identify_code(runtime_code, creation_code)?;
209                trace!(target: "evm::traces::local", id=%id.identifier(), "identified");
210
211                Some(IdentifiedAddress {
212                    address,
213                    contract: Some(id.identifier()),
214                    label: Some(id.name.clone()),
215                    abi: Some(Cow::Borrowed(abi)),
216                    constructor_args_offset,
217                    artifact_id: Some(id.clone()),
218                })
219            })
220            .collect()
221    }
222}
223
224#[cfg(test)]
225mod tests {
226    use super::*;
227    use crate::{CallKind, CallTrace};
228    use foundry_compilers::artifacts::{
229        BytecodeObject, CompactBytecode, CompactContractBytecode, CompactDeployedBytecode, Offsets,
230    };
231
232    fn artifact(
233        name: &str,
234        abi: JsonAbi,
235        creation: &[u8],
236        runtime: &[u8],
237    ) -> (ArtifactId, CompactContractBytecode) {
238        (
239            ArtifactId {
240                path: format!("out/{name}.json").into(),
241                source: format!("{name}.sol").into(),
242                name: name.to_owned(),
243                version: "0.8.30".parse().unwrap(),
244                build_id: String::new(),
245                profile: "default".to_owned(),
246            },
247            CompactContractBytecode {
248                abi: Some(abi),
249                bytecode: Some(CompactBytecode {
250                    object: BytecodeObject::Bytecode(Bytes::copy_from_slice(creation)),
251                    source_map: None,
252                    link_references: Default::default(),
253                }),
254                deployed_bytecode: Some(CompactDeployedBytecode {
255                    bytecode: Some(CompactBytecode {
256                        object: BytecodeObject::Bytecode(Bytes::copy_from_slice(runtime)),
257                        source_map: None,
258                        link_references: Default::default(),
259                    }),
260                    immutable_references: Default::default(),
261                }),
262            },
263        )
264    }
265
266    #[test]
267    fn identifies_creation_with_different_runtime_length() {
268        let creation = [0x60; 64];
269        let runtime = [0x5b; 64];
270        let mut decoy_runtime = runtime;
271        decoy_runtime[0] = 0x5a;
272        let abi = JsonAbi::parse(["constructor(uint256 value)"]).unwrap();
273        let mut input = creation.to_vec();
274        input.extend_from_slice(&[0; 32]);
275
276        // A constructor can return arbitrary runtime via assembly. Its artifact's runtime
277        // length does not have to resemble the code returned by CREATE.
278        for compiled_runtime in [vec![0], vec![0; 128]] {
279            let contracts = ContractsByArtifact::new([
280                artifact("Decoy", JsonAbi::default(), &[0xff; 64], &decoy_runtime),
281                artifact("ReturnedRuntime", abi.clone(), &creation, &compiled_runtime),
282            ]);
283            let identifier = LocalTraceIdentifier::new(&contracts);
284            let (id, _, offset) = identifier.identify_code(&runtime, &input).unwrap();
285            assert_eq!(id.name, "ReturnedRuntime");
286            assert_eq!(offset, Some(creation.len()));
287
288            // Calls without initcode still use the runtime match.
289            let (id, _, offset) = identifier.identify_code(&runtime, &[]).unwrap();
290            assert_eq!(id.name, "Decoy");
291            assert_eq!(offset, None);
292        }
293    }
294
295    #[test]
296    fn identifies_creation_without_constructor_arguments() {
297        let creation = [0x60; 64];
298        let runtime = [0x5b; 64];
299        let mut decoy_runtime = runtime;
300        decoy_runtime[0] = 0x5a;
301        let contracts = ContractsByArtifact::new([
302            artifact("Decoy", JsonAbi::default(), &[0xff; 64], &decoy_runtime),
303            artifact("ReturnedRuntime", JsonAbi::default(), &creation, &[0]),
304        ]);
305        let identifier = LocalTraceIdentifier::new(&contracts);
306        let (id, _, offset) = identifier.identify_code(&runtime, &creation).unwrap();
307        assert_eq!(id.name, "ReturnedRuntime");
308        assert_eq!(offset, None);
309    }
310
311    #[test]
312    fn creation_fallback_rejects_invalid_constructor_arguments() {
313        let creation = [0x60; 64];
314        let runtime = [0x5b; 64];
315        let mut decoy_runtime = runtime;
316        decoy_runtime[0] = 0x5a;
317        let contracts = ContractsByArtifact::new([
318            artifact("Decoy", JsonAbi::default(), &[0xff; 64], &decoy_runtime),
319            artifact(
320                "ReturnedRuntime",
321                JsonAbi::parse(["constructor(uint256 value)"]).unwrap(),
322                &creation,
323                &[0],
324            ),
325        ]);
326        let identifier = LocalTraceIdentifier::new(&contracts);
327        for suffix in [vec![], vec![0; 31], vec![0; 33]] {
328            let input = [creation.as_slice(), &suffix].concat();
329            let (id, _, offset) = identifier.identify_code(&runtime, &input).unwrap();
330            assert_eq!(id.name, "Decoy");
331            assert_eq!(offset, None);
332        }
333    }
334
335    #[test]
336    fn exact_creation_match_overrides_similar_in_range_creation() {
337        let creation = [0x60; 64];
338        let runtime = [0x5b; 64];
339        let mut decoy_runtime = runtime;
340        decoy_runtime[0] = 0x5a;
341        let mut similar_creation = creation;
342        similar_creation[0] = 0x61;
343        let contracts = ContractsByArtifact::new([
344            artifact("Decoy", JsonAbi::default(), &similar_creation, &decoy_runtime),
345            artifact("ReturnedRuntime", JsonAbi::default(), &creation, &[0]),
346        ]);
347        let identifier = LocalTraceIdentifier::new(&contracts);
348        let (id, _, _) = identifier.identify_code(&runtime, &creation).unwrap();
349        assert_eq!(id.name, "ReturnedRuntime");
350    }
351
352    #[test]
353    fn creation_fallback_prefers_longer_initcode() {
354        let creation = [0x60; 64];
355        let input = [creation.as_slice(), &[0; 32]].concat();
356        let runtime = [0x5b; 64];
357        let contracts = ContractsByArtifact::new([
358            artifact(
359                "Prefix",
360                JsonAbi::parse(["constructor(uint256 value)"]).unwrap(),
361                &creation,
362                &[0],
363            ),
364            artifact("ReturnedRuntime", JsonAbi::default(), &input, &[0, 0]),
365        ]);
366        let identifier = LocalTraceIdentifier::new(&contracts);
367        let (id, _, offset) = identifier.identify_code(&runtime, &input).unwrap();
368        assert_eq!(id.name, "ReturnedRuntime");
369        assert_eq!(offset, None);
370    }
371
372    #[test]
373    fn exact_runtime_match_precedes_creation_fallback() {
374        let creation = [0x60; 64];
375        let runtime = [0x5b; 64];
376        let contracts = ContractsByArtifact::new([
377            artifact("Runtime", JsonAbi::default(), &[0xff; 64], &runtime),
378            artifact("RuntimeDeployer", JsonAbi::default(), &creation, &[0]),
379        ]);
380        let identifier = LocalTraceIdentifier::new(&contracts);
381        let (id, _, offset) = identifier.identify_code(&runtime, &creation).unwrap();
382        assert_eq!(id.name, "Runtime");
383        assert_eq!(offset, None);
384    }
385
386    #[test]
387    fn failed_creates_do_not_use_creation_fallback() {
388        let creation = [0x60; 64];
389        let contracts = ContractsByArtifact::new([artifact(
390            "ReturnedRuntime",
391            JsonAbi::default(),
392            &creation,
393            &[0],
394        )]);
395        let mut identifier = LocalTraceIdentifier::new(&contracts);
396        for kind in [CallKind::Create, CallKind::Create2] {
397            for output in [Bytes::new(), Bytes::from_static(&[0x08, 0xc3, 0x79, 0xa0])] {
398                let mut node = CallTraceNode {
399                    trace: CallTrace {
400                        kind,
401                        success: false,
402                        data: Bytes::copy_from_slice(&creation),
403                        output,
404                        ..Default::default()
405                    },
406                    ..Default::default()
407                };
408                assert!(identifier.identify_addresses(&[&node]).is_empty());
409
410                // Successful custom-runtime creates must still be identified.
411                node.trace.success = true;
412                node.trace.output = Bytes::from_static(&[0x5b; 64]);
413                let identified = identifier.identify_addresses(&[&node]);
414                assert_eq!(identified.len(), 1);
415                assert_eq!(identified[0].label.as_deref(), Some("ReturnedRuntime"));
416            }
417        }
418    }
419
420    #[test]
421    fn successful_create_without_runtime_does_not_use_creation_fallback() {
422        let creation = [0x60; 64];
423        let contracts = ContractsByArtifact::new([artifact(
424            "EmptyRuntime",
425            JsonAbi::default(),
426            &creation,
427            &[0],
428        )]);
429        let mut identifier = LocalTraceIdentifier::new(&contracts);
430        for kind in [CallKind::Create, CallKind::Create2] {
431            let node = CallTraceNode {
432                trace: CallTrace {
433                    kind,
434                    success: true,
435                    data: Bytes::copy_from_slice(&creation),
436                    ..Default::default()
437                },
438                ..Default::default()
439            };
440            assert!(identifier.identify_addresses(&[&node]).is_empty());
441        }
442    }
443
444    #[test]
445    fn creation_fallback_preserves_runtime_references() {
446        let creation = [0x60; 64];
447        let runtime = [0x5b; 64];
448        let mut compiled_runtime = runtime;
449        compiled_runtime[8..28].fill(0);
450        let runtime_abi = JsonAbi::parse(["function increment()"]).unwrap();
451
452        for immutable in [true, false] {
453            let (id, mut contract) =
454                artifact("Runtime", runtime_abi.clone(), &[0xff; 64], &compiled_runtime);
455            let deployed = contract.deployed_bytecode.as_mut().unwrap();
456            let offsets = vec![Offsets { start: 8, length: 20 }];
457            if immutable {
458                deployed.immutable_references.insert("value".to_owned(), offsets);
459            } else {
460                deployed
461                    .bytecode
462                    .as_mut()
463                    .unwrap()
464                    .link_references
465                    .insert("Library.sol".to_owned(), [("Library".to_owned(), offsets)].into());
466            }
467            let contracts = ContractsByArtifact::new([
468                (id, contract),
469                artifact("RuntimeDeployer", JsonAbi::default(), &creation, &[0]),
470            ]);
471            let identifier = LocalTraceIdentifier::new(&contracts);
472            let (id, abi, offset) = identifier.identify_code(&runtime, &creation).unwrap();
473            assert_eq!(id.name, "Runtime");
474            assert_eq!(abi, &runtime_abi);
475            assert_eq!(offset, None);
476
477            // A difference outside the declared references is not an exact runtime match.
478            let mut unrelated_runtime = runtime;
479            unrelated_runtime[40] = 0x5a;
480            let (id, _, _) = identifier.identify_code(&unrelated_runtime, &creation).unwrap();
481            assert_eq!(id.name, "RuntimeDeployer");
482        }
483    }
484
485    #[test]
486    fn creation_fallback_rejects_runtime_with_different_metadata() {
487        let creation = [0x60; 64];
488        let mut runtime = [0x5b; 64];
489        runtime[61..].copy_from_slice(&[0xa0, 0x00, 0x01]);
490        let mut compiled_runtime = runtime;
491        compiled_runtime[61] = 0xf6;
492        let contracts = ContractsByArtifact::new([
493            artifact("Runtime", JsonAbi::default(), &[0xff; 64], &compiled_runtime),
494            artifact("RuntimeDeployer", JsonAbi::default(), &creation, &[0]),
495        ]);
496        let identifier = LocalTraceIdentifier::new(&contracts);
497        let (id, _, _) = identifier.identify_code(&runtime, &creation).unwrap();
498        assert_eq!(id.name, "RuntimeDeployer");
499    }
500}