Skip to main content

foundry_common/
contracts.rs

1//! Commonly used contract types and functions.
2
3use crate::{compile::PathOrContractInfo, find_metadata_start, strip_bytecode_placeholders};
4use alloy_dyn_abi::JsonAbiExt;
5use alloy_json_abi::{Event, Function, JsonAbi};
6use alloy_primitives::{Address, B256, Bytes, Selector, address, hex};
7use eyre::{OptionExt, Result};
8use foundry_compilers::{
9    ArtifactId, Project, ProjectCompileOutput,
10    artifacts::{
11        BytecodeObject, CompactBytecode, CompactContractBytecode, CompactContractBytecodeCow,
12        CompactDeployedBytecode, ConfigurableContractArtifact, ContractBytecodeSome, Offsets,
13        StorageLayout,
14    },
15    utils::canonicalized,
16};
17use std::{
18    collections::BTreeMap,
19    ops::Deref,
20    path::{Path, PathBuf},
21    str::FromStr,
22    sync::Arc,
23};
24
25/// Libraries' runtime code always starts with the following instruction:
26/// `PUSH20 0x0000000000000000000000000000000000000000`
27///
28/// See: <https://docs.soliditylang.org/en/latest/contracts.html#call-protection-for-libraries>
29const CALL_PROTECTION_BYTECODE_PREFIX: [u8; 21] =
30    hex!("730000000000000000000000000000000000000000");
31
32/// Immutable holding a library's own address in its runtime code under the IR pipeline, which
33/// replaces the `PUSH20` call protection prefix.
34const LIBRARY_DEPLOY_ADDRESS_IMMUTABLE: &str = "library_deploy_address";
35
36/// Isolated account used to deploy libraries needed only while executing locally.
37///
38/// `address(uint160(uint256(keccak256("foundry library deployer"))))`
39pub const LIBRARY_DEPLOYER: Address = address!("0x1F95D37F27EA0dEA9C252FC09D5A6eaA97647353");
40
41/// Subset of [CompactBytecode] excluding sourcemaps.
42#[expect(missing_docs)]
43#[derive(Debug, Clone)]
44pub struct BytecodeData {
45    pub object: Option<BytecodeObject>,
46    pub link_references: BTreeMap<String, BTreeMap<String, Vec<Offsets>>>,
47    pub immutable_references: BTreeMap<String, Vec<Offsets>>,
48}
49
50impl BytecodeData {
51    fn bytes(&self) -> Option<&Bytes> {
52        self.object.as_ref().and_then(|b| b.as_bytes())
53    }
54}
55
56/// Returns whether Solidity deployed code starts with the library call protection prefix.
57///
58/// See <https://docs.soliditylang.org/en/latest/contracts.html#call-protection-for-libraries>.
59fn has_call_protection(code: &BytecodeObject) -> bool {
60    match code {
61        BytecodeObject::Bytecode(bytes) => bytes.starts_with(&CALL_PROTECTION_BYTECODE_PREFIX),
62        BytecodeObject::Unlinked(bytes) => bytes
63            .get(..CALL_PROTECTION_BYTECODE_PREFIX.len() * 2)
64            .and_then(|prefix| Bytes::from_str(prefix).ok())
65            .is_some_and(|prefix| prefix.starts_with(&CALL_PROTECTION_BYTECODE_PREFIX)),
66    }
67}
68
69/// Sorts and merges overlapping or adjacent byte ranges.
70fn normalize_offsets(offsets: &mut Vec<Offsets>) {
71    offsets.sort_by_key(|o| o.start);
72
73    let mut merged: Vec<Offsets> = Vec::with_capacity(offsets.len());
74    for offset in offsets.drain(..) {
75        if let Some(last) = merged.last_mut() {
76            let last_end = last.start as u64 + last.length as u64;
77            if offset.start as u64 <= last_end {
78                let this_end = offset.start as u64 + offset.length as u64;
79                if this_end > last_end {
80                    last.length = (this_end - last.start as u64) as u32;
81                }
82                continue;
83            }
84        }
85        merged.push(offset);
86    }
87    *offsets = merged;
88}
89
90impl From<CompactBytecode> for BytecodeData {
91    fn from(bytecode: CompactBytecode) -> Self {
92        Self {
93            object: Some(bytecode.object),
94            link_references: bytecode.link_references,
95            immutable_references: BTreeMap::new(),
96        }
97    }
98}
99
100impl From<CompactDeployedBytecode> for BytecodeData {
101    fn from(bytecode: CompactDeployedBytecode) -> Self {
102        let (object, link_references) = if let Some(compact) = bytecode.bytecode {
103            (Some(compact.object), compact.link_references)
104        } else {
105            (None, BTreeMap::new())
106        };
107        Self { object, link_references, immutable_references: bytecode.immutable_references }
108    }
109}
110
111/// Container for commonly used contract data.
112#[derive(Debug)]
113pub struct ContractData {
114    /// Contract name.
115    pub name: String,
116    /// Contract ABI.
117    pub abi: JsonAbi,
118    /// Contract creation code.
119    pub bytecode: Option<BytecodeData>,
120    /// Contract runtime code.
121    pub deployed_bytecode: Option<BytecodeData>,
122    /// Contract storage layout, if available.
123    pub storage_layout: Option<Arc<StorageLayout>>,
124}
125
126impl ContractData {
127    /// Returns reference to bytes of contract creation code, if present.
128    pub fn bytecode(&self) -> Option<&Bytes> {
129        self.bytecode.as_ref()?.bytes().filter(|b| !b.is_empty())
130    }
131
132    /// Returns reference to bytes of contract deployed code, if present.
133    pub fn deployed_bytecode(&self) -> Option<&Bytes> {
134        self.deployed_bytecode.as_ref()?.bytes().filter(|b| !b.is_empty())
135    }
136
137    /// Returns the bytecode without placeholders, if present.
138    pub fn bytecode_without_placeholders(&self) -> Option<Bytes> {
139        strip_bytecode_placeholders(self.bytecode.as_ref()?.object.as_ref()?)
140    }
141
142    /// Returns the deployed bytecode without placeholders, if present.
143    pub fn deployed_bytecode_without_placeholders(&self) -> Option<Bytes> {
144        strip_bytecode_placeholders(self.deployed_bytecode.as_ref()?.object.as_ref()?)
145    }
146
147    /// Returns whether this is a Solidity library, from the call protection the compiler emits:
148    /// a `library_deploy_address` immutable under the IR pipeline, or a `PUSH20` prefix otherwise.
149    pub fn is_library(&self) -> bool {
150        let Some(deployed_bytecode) = &self.deployed_bytecode else { return false };
151        deployed_bytecode.immutable_references.contains_key(LIBRARY_DEPLOY_ADDRESS_IMMUTABLE)
152            || deployed_bytecode.object.as_ref().is_some_and(has_call_protection)
153    }
154}
155
156/// Builder for creating a `ContractsByArtifact` instance, optionally including storage layouts
157/// from project compile output.
158pub struct ContractsByArtifactBuilder<'a> {
159    /// All compiled artifact bytecodes (borrowed).
160    artifacts: BTreeMap<ArtifactId, CompactContractBytecodeCow<'a>>,
161    /// Optionally collected storage layouts for matching artifact IDs.
162    storage_layouts: BTreeMap<ArtifactId, StorageLayout>,
163}
164
165impl<'a> ContractsByArtifactBuilder<'a> {
166    /// Creates a new builder from artifacts with present bytecode iterator.
167    pub fn new(
168        artifacts: impl IntoIterator<Item = (ArtifactId, CompactContractBytecodeCow<'a>)>,
169    ) -> Self {
170        Self { artifacts: artifacts.into_iter().collect(), storage_layouts: BTreeMap::new() }
171    }
172
173    /// Add storage layouts from the given `ProjectCompileOutput` to known artifacts.
174    pub fn with_output(self, output: &ProjectCompileOutput, base: &Path) -> Self {
175        self.with_storage_layouts(output.artifact_ids().filter_map(|(id, artifact)| {
176            artifact
177                .storage_layout
178                .as_ref()
179                .map(|layout| (id.with_stripped_file_prefixes(base), layout.clone()))
180        }))
181    }
182
183    /// Add storage layouts.
184    pub fn with_storage_layouts(
185        mut self,
186        layouts: impl IntoIterator<Item = (ArtifactId, StorageLayout)>,
187    ) -> Self {
188        self.storage_layouts.extend(layouts);
189        self
190    }
191
192    /// Builds `ContractsByArtifact`.
193    pub fn build(self) -> ContractsByArtifact {
194        let map = self
195            .artifacts
196            .into_iter()
197            .filter_map(|(id, artifact)| {
198                let name = id.name.clone();
199                let CompactContractBytecodeCow { abi, bytecode, deployed_bytecode } = artifact;
200
201                Some((
202                    id.clone(),
203                    ContractData {
204                        name,
205                        abi: abi?.into_owned(),
206                        bytecode: bytecode.map(|b| b.into_owned().into()),
207                        deployed_bytecode: deployed_bytecode.map(|b| b.into_owned().into()),
208                        storage_layout: self.storage_layouts.get(&id).map(|l| Arc::new(l.clone())),
209                    },
210                ))
211            })
212            .collect();
213
214        ContractsByArtifact(Arc::new(map))
215    }
216}
217
218type ArtifactWithContractRef<'a> = (&'a ArtifactId, &'a ContractData);
219
220/// Wrapper type that maps an artifact to a contract ABI and bytecode.
221#[derive(Clone, Default, Debug)]
222pub struct ContractsByArtifact(Arc<BTreeMap<ArtifactId, ContractData>>);
223
224impl ContractsByArtifact {
225    /// Creates a new instance by collecting all artifacts with present bytecode from an iterator.
226    pub fn new(artifacts: impl IntoIterator<Item = (ArtifactId, CompactContractBytecode)>) -> Self {
227        let map = artifacts
228            .into_iter()
229            .filter_map(|(id, artifact)| {
230                let name = id.name.clone();
231                let CompactContractBytecode { abi, bytecode, deployed_bytecode } = artifact;
232                Some((
233                    id,
234                    ContractData {
235                        name,
236                        abi: abi?,
237                        bytecode: bytecode.map(Into::into),
238                        deployed_bytecode: deployed_bytecode.map(Into::into),
239                        storage_layout: None,
240                    },
241                ))
242            })
243            .collect();
244        Self(Arc::new(map))
245    }
246
247    /// Clears all contracts.
248    pub fn clear(&mut self) {
249        *self = Self::default();
250    }
251
252    /// Finds a contract which has a similar bytecode as `code`.
253    pub fn find_by_creation_code(&self, code: &[u8]) -> Option<ArtifactWithContractRef<'_>> {
254        self.find_by_code(code, 0.1, true, ContractData::bytecode)
255    }
256
257    /// Finds the first artifact whose nonempty creation bytecode is a prefix of `code`.
258    /// Unlike [`matches_contract_creation`], this does not validate the trailing constructor data.
259    pub fn find_by_creation_code_prefix(&self, code: &[u8]) -> Option<ArtifactWithContractRef<'_>> {
260        self.iter().find(|(_, contract)| {
261            contract.bytecode().is_some_and(|bytecode| code.starts_with(bytecode))
262        })
263    }
264
265    /// Finds a contract which has a similar deployed bytecode as `code`.
266    pub fn find_by_deployed_code(&self, code: &[u8]) -> Option<ArtifactWithContractRef<'_>> {
267        self.find_by_code(code, 0.15, false, ContractData::deployed_bytecode)
268    }
269
270    /// Finds a contract based on provided bytecode and accepted match score.
271    /// If strip constructor args flag is true then removes args from bytecode to compare.
272    fn find_by_code(
273        &self,
274        code: &[u8],
275        accepted_score: f64,
276        strip_ctor_args: bool,
277        get: impl Fn(&ContractData) -> Option<&Bytes>,
278    ) -> Option<ArtifactWithContractRef<'_>> {
279        self.iter()
280            .filter_map(|(id, contract)| {
281                get(contract).and_then(|deployed_bytecode| {
282                    let mut code = code;
283                    if strip_ctor_args && code.len() > deployed_bytecode.len() {
284                        // Try to decode ctor args with contract abi.
285                        if let Some(constructor) = contract.abi.constructor() {
286                            let constructor_args = &code[deployed_bytecode.len()..];
287                            if constructor.abi_decode_input(constructor_args).is_ok() {
288                                // If we can decode args with current abi then remove args from
289                                // code to compare.
290                                code = &code[..deployed_bytecode.len()]
291                            }
292                        }
293                    };
294
295                    let score = bytecode_diff_score(deployed_bytecode.as_ref(), code);
296                    (score <= accepted_score).then_some((score, (id, contract)))
297                })
298            })
299            .min_by(|(score1, _), (score2, _)| score1.total_cmp(score2))
300            .map(|(_, data)| data)
301    }
302
303    /// Finds a contract which deployed bytecode exactly matches the given code. Accounts for link
304    /// references and immutables.
305    pub fn find_by_deployed_code_exact(&self, code: &[u8]) -> Option<ArtifactWithContractRef<'_>> {
306        self.find_by_deployed_code_exact_preferred(code, |_| true)
307    }
308
309    /// Same as [`Self::find_by_deployed_code_exact`], preferring artifacts matching `preferred`
310    /// only among equally strong matches. Metadata-exact matches always take precedence.
311    pub fn find_by_deployed_code_exact_preferred(
312        &self,
313        code: &[u8],
314        preferred: impl Fn(&ArtifactId) -> bool,
315    ) -> Option<ArtifactWithContractRef<'_>> {
316        let (exact, partial, _) = self.find_by_deployed_code_exact_inner(code, false, preferred);
317        exact.or(partial)
318    }
319
320    /// Finds the only contract whose deployed bytecode exactly matches the given code.
321    pub fn find_by_deployed_code_exact_unique(
322        &self,
323        code: &[u8],
324    ) -> Option<ArtifactWithContractRef<'_>> {
325        self.find_by_deployed_code_exact_inner(code, true, |_| false).0
326    }
327
328    /// Finds a deployed-code match, preferring exact metadata matches and rejecting ambiguous
329    /// partial metadata matches. A single partial match is accepted.
330    pub fn find_by_deployed_code_exact_unambiguous(
331        &self,
332        code: &[u8],
333    ) -> Result<Option<ArtifactWithContractRef<'_>>> {
334        let (exact, partial, ambiguous_partial) =
335            self.find_by_deployed_code_exact_inner(code, false, |_| true);
336        if ambiguous_partial {
337            eyre::bail!(
338                "Multiple local contracts match the deployed bytecode with different metadata. Specify the contract as <path>:<contract>"
339            );
340        }
341        Ok(exact.or(partial))
342    }
343
344    /// Finds an exact deployed-code match, including metadata. Accounts for link references,
345    /// immutables, library call protection, and Vyper's appended immutable data, but does not
346    /// accept matches differing only in metadata.
347    pub fn find_by_deployed_code_exact_with_metadata(
348        &self,
349        code: &[u8],
350    ) -> Option<ArtifactWithContractRef<'_>> {
351        self.find_by_deployed_code_exact_inner(code, false, |_| true).0
352    }
353
354    fn find_by_deployed_code_exact_inner(
355        &self,
356        code: &[u8],
357        unique: bool,
358        preferred: impl Fn(&ArtifactId) -> bool,
359    ) -> (Option<ArtifactWithContractRef<'_>>, Option<ArtifactWithContractRef<'_>>, bool) {
360        // Immediately return None if the code is empty.
361        if code.is_empty() {
362            return (None, None, false);
363        }
364
365        let mut partial_match = None;
366        let mut exact_match = None;
367        let mut ambiguous_partial = false;
368        'contracts: for (id, contract) in self.iter() {
369            let Some(deployed_bytecode) = &contract.deployed_bytecode else {
370                continue;
371            };
372            let Some(deployed_code) = &deployed_bytecode.object else {
373                continue;
374            };
375
376            let len = match deployed_code {
377                BytecodeObject::Bytecode(bytes) => bytes.len(),
378                BytecodeObject::Unlinked(bytes) => bytes.len() / 2,
379            };
380
381            // Vyper artifacts contain the complete runtime, but omit the immutable data
382            // appended on deployment. Compare that runtime in full, without treating any of
383            // its bytes (or the immutable suffix) as Solidity metadata.
384            let is_vyper = id.source.extension().is_some_and(|extension| extension == "vy");
385            let code = if is_vyper {
386                let Some(runtime) = code.get(..len) else { continue };
387                runtime
388            } else {
389                code
390            };
391            if len == 0 || len != code.len() {
392                continue;
393            }
394
395            // Collect ignored offsets by chaining link and immutable references.
396            let mut ignored = deployed_bytecode
397                .immutable_references
398                .values()
399                .chain(deployed_bytecode.link_references.values().flat_map(|v| v.values()))
400                .flatten()
401                .cloned()
402                .collect::<Vec<_>>();
403
404            // For libraries solidity adds a call protection prefix to the bytecode. We need to
405            // ignore it as it includes library address determined at runtime.
406            // See https://docs.soliditylang.org/en/latest/contracts.html#call-protection-for-libraries and
407            // https://github.com/NomicFoundation/hardhat/blob/af7807cf38842a4f56e7f4b966b806e39631568a/packages/hardhat-verify/src/internal/solc/bytecode.ts#L172
408            if !is_vyper && has_call_protection(deployed_code) {
409                ignored.push(Offsets { start: 1, length: 20 });
410            }
411
412            let metadata_start = if is_vyper { None } else { find_metadata_start(code) };
413
414            // Keep the trailing CBOR length in the comparison: it is read from `code`, so ignoring
415            // it would let crafted code declare arbitrary bytes as metadata.
416            if let Some(metadata) = metadata_start {
417                ignored.push(Offsets {
418                    start: metadata as u32,
419                    length: (code.len() - 2 - metadata) as u32,
420                });
421            }
422
423            // Merge ranges from independent sources before slicing between them.
424            normalize_offsets(&mut ignored);
425
426            let mut left = 0;
427            for offset in ignored {
428                let right = offset.start as usize;
429
430                let matched = match deployed_code {
431                    BytecodeObject::Bytecode(bytes) => bytes[left..right] == code[left..right],
432                    BytecodeObject::Unlinked(bytes) => {
433                        if let Ok(bytes) = Bytes::from_str(&bytes[left * 2..right * 2]) {
434                            bytes == code[left..right]
435                        } else {
436                            false
437                        }
438                    }
439                };
440
441                if !matched {
442                    continue 'contracts;
443                }
444
445                left = right + offset.length as usize;
446            }
447
448            let is_partial = if left < code.len() {
449                match deployed_code {
450                    BytecodeObject::Bytecode(bytes) => bytes[left..] == code[left..],
451                    BytecodeObject::Unlinked(bytes) => {
452                        if let Ok(bytes) = Bytes::from_str(&bytes[left * 2..]) {
453                            bytes == code[left..]
454                        } else {
455                            false
456                        }
457                    }
458                }
459            } else {
460                true
461            };
462
463            if !is_partial {
464                continue;
465            }
466
467            let matches_metadata = metadata_start.is_none_or(|metadata| match deployed_code {
468                BytecodeObject::Bytecode(bytes) => bytes[metadata..] == code[metadata..],
469                BytecodeObject::Unlinked(bytes) => Bytes::from_str(&bytes[metadata * 2..])
470                    .is_ok_and(|bytes| bytes == code[metadata..]),
471            });
472
473            if matches_metadata {
474                if unique && exact_match.is_some() {
475                    return (None, None, false);
476                }
477                if exact_match.is_none() || preferred(id) {
478                    exact_match = Some((id, contract));
479                }
480                if !unique && preferred(id) {
481                    return (exact_match, None, false);
482                }
483            } else {
484                ambiguous_partial |= partial_match.is_some();
485                if preferred(id) || partial_match.is_none_or(|(id, _)| !preferred(id)) {
486                    partial_match = Some((id, contract));
487                }
488            }
489        }
490
491        let ambiguous_partial = exact_match.is_none() && ambiguous_partial;
492        (exact_match, partial_match, ambiguous_partial)
493    }
494
495    /// Finds a contract which has the same contract name or identifier as `id`. If more than one is
496    /// found, return error.
497    pub fn find_by_name_or_identifier(
498        &self,
499        id: &str,
500    ) -> Result<Option<ArtifactWithContractRef<'_>>> {
501        let mut iter =
502            self.iter().filter(|(artifact, _)| artifact.name == id || artifact.identifier() == id);
503        let first = iter.next();
504        if first.is_some() && iter.next().is_some() {
505            eyre::bail!("{id} has more than one implementation.");
506        }
507
508        Ok(first)
509    }
510
511    /// Finds abi by name or source path
512    ///
513    /// Returns the abi and the contract name.
514    pub fn find_abi_by_name_or_src_path(&self, name_or_path: &str) -> Option<(JsonAbi, String)> {
515        self.iter()
516            .find(|(artifact, _)| {
517                artifact.name == name_or_path || artifact.source == Path::new(name_or_path)
518            })
519            .map(|(_, contract)| (contract.abi.clone(), contract.name.clone()))
520    }
521
522    /// Flattens the contracts into functions, events and errors.
523    pub fn flatten(&self) -> (BTreeMap<Selector, Function>, BTreeMap<B256, Event>, JsonAbi) {
524        let mut funcs = BTreeMap::new();
525        let mut events = BTreeMap::new();
526        let mut errors_abi = JsonAbi::new();
527        for contract in self.values() {
528            for func in contract.abi.functions() {
529                funcs.insert(func.selector(), func.clone());
530            }
531            for event in contract.abi.events() {
532                events.insert(event.selector(), event.clone());
533            }
534            for error in contract.abi.errors() {
535                errors_abi.errors.entry(error.name.clone()).or_default().push(error.clone());
536            }
537        }
538        (funcs, events, errors_abi)
539    }
540}
541
542impl From<ProjectCompileOutput> for ContractsByArtifact {
543    fn from(value: ProjectCompileOutput) -> Self {
544        Self::new(value.into_artifacts().map(|(id, ar)| {
545            (
546                id,
547                CompactContractBytecode {
548                    abi: ar.abi,
549                    bytecode: ar.bytecode,
550                    deployed_bytecode: ar.deployed_bytecode,
551                },
552            )
553        }))
554    }
555}
556
557impl Deref for ContractsByArtifact {
558    type Target = BTreeMap<ArtifactId, ContractData>;
559
560    fn deref(&self) -> &Self::Target {
561        &self.0
562    }
563}
564
565/// Wrapper type that maps an address to a contract identifier and contract ABI.
566pub type ContractsByAddress = BTreeMap<Address, (String, JsonAbi)>;
567
568/// Very simple fuzzy matching of contract bytecode.
569///
570/// Returns a value between `0.0` (identical) and `1.0` (completely different).
571/// Returns whether `creation_code` is exactly this contract's linked creation bytecode followed by
572/// a complete, canonically encoded constructor argument tuple.
573pub fn matches_contract_creation(contract: &ContractData, creation_code: &[u8]) -> bool {
574    let Some(bytecode) = contract.bytecode() else { return false };
575    let Some(arguments) = creation_code.strip_prefix(bytecode.as_ref()) else { return false };
576    match contract.abi.constructor() {
577        Some(constructor) => constructor
578            .abi_decode_input(arguments)
579            .ok()
580            .and_then(|values| constructor.abi_encode_input(&values).ok())
581            .is_some_and(|encoded| encoded == arguments),
582        None => arguments.is_empty(),
583    }
584}
585
586pub fn bytecode_diff_score<'a>(mut a: &'a [u8], mut b: &'a [u8]) -> f64 {
587    // Make sure `a` is the longer one.
588    if a.len() < b.len() {
589        std::mem::swap(&mut a, &mut b);
590    }
591
592    // Account for different lengths.
593    let mut n_different_bytes = a.len() - b.len();
594
595    // If the difference is more than 32 bytes and more than 10% of the total length,
596    // we assume the bytecodes are completely different.
597    // This is a simple heuristic to avoid checking every byte when the lengths are very different.
598    // 32 is chosen to be a reasonable minimum as it's the size of metadata hashes and one EVM word.
599    if n_different_bytes > 32 && n_different_bytes * 10 > a.len() {
600        return 1.0;
601    }
602
603    // Count different bytes.
604    // SAFETY: `a` is longer than `b`.
605    n_different_bytes += unsafe { count_different_bytes(a, b) };
606
607    n_different_bytes as f64 / a.len() as f64
608}
609
610/// Returns the amount of different bytes between two slices.
611///
612/// # Safety
613///
614/// `a` must be at least as long as `b`.
615const unsafe fn count_different_bytes(a: &[u8], b: &[u8]) -> usize {
616    // This could've been written as `std::iter::zip(a, b).filter(|(x, y)| x != y).count()`,
617    // however this function is very hot, and has been written to be as primitive as
618    // possible for lower optimization levels.
619
620    let a_ptr = a.as_ptr();
621    let b_ptr = b.as_ptr();
622    let len = b.len();
623
624    let mut sum = 0;
625    let mut i = 0;
626    while i < len {
627        // SAFETY: `a` is at least as long as `b`, and `i` is in bound of `b`.
628        sum += unsafe { *a_ptr.add(i) != *b_ptr.add(i) } as usize;
629        i += 1;
630    }
631    sum
632}
633
634/// Returns contract name for a given contract identifier.
635///
636/// Artifact/Contract identifier can take the following form:
637/// `<artifact file name>:<contract name>`, the `artifact file name` is the name of the json file of
638/// the contract's artifact and the contract name is the name of the solidity contract, like
639/// `SafeTransferLibTest.json:SafeTransferLibTest`
640///
641/// This returns the `contract name` part
642///
643/// # Example
644///
645/// ```
646/// use foundry_common::*;
647/// assert_eq!(
648///     "SafeTransferLibTest",
649///     get_contract_name("SafeTransferLibTest.json:SafeTransferLibTest")
650/// );
651/// ```
652pub fn get_contract_name(id: &str) -> &str {
653    id.rsplit(':').next().unwrap_or(id)
654}
655
656/// This returns the `file name` part, See [`get_contract_name`]
657///
658/// # Example
659///
660/// ```
661/// use foundry_common::*;
662/// assert_eq!(
663///     "SafeTransferLibTest.json",
664///     get_file_name("SafeTransferLibTest.json:SafeTransferLibTest")
665/// );
666/// ```
667pub fn get_file_name(id: &str) -> &str {
668    id.split(':').next().unwrap_or(id)
669}
670
671/// Helper function to convert CompactContractBytecode ~> ContractBytecodeSome
672pub fn compact_to_contract(contract: CompactContractBytecode) -> Result<ContractBytecodeSome> {
673    Ok(ContractBytecodeSome {
674        abi: contract.abi.ok_or_else(|| eyre::eyre!("No contract abi"))?,
675        bytecode: contract.bytecode.ok_or_else(|| eyre::eyre!("No contract bytecode"))?.into(),
676        deployed_bytecode: contract
677            .deployed_bytecode
678            .ok_or_else(|| eyre::eyre!("No contract deployed bytecode"))?
679            .into(),
680    })
681}
682
683/// Returns the canonicalized target path for the given identifier.
684pub fn find_target_path(project: &Project, identifier: &PathOrContractInfo) -> Result<PathBuf> {
685    match identifier {
686        PathOrContractInfo::Path(path) => Ok(canonicalized(project.root().join(path))),
687        PathOrContractInfo::ContractInfo(info) => {
688            if let Some(path) = info.path.as_ref() {
689                let path = canonicalized(project.root().join(path));
690                if !path.is_file() {
691                    eyre::bail!(
692                        "Could not find source file for contract `{}` at {}",
693                        info.name,
694                        path.strip_prefix(project.root()).unwrap_or(&path).display()
695                    );
696                }
697                return Ok(path);
698            }
699            // If ContractInfo.path hasn't been provided we try to find the contract using the name.
700            // This will fail if projects have multiple contracts with the same name. In that case,
701            // path must be specified.
702            let path = project.find_contract_path(&info.name)?;
703            Ok(path)
704        }
705    }
706}
707
708/// Returns the target artifact given the path and name.
709pub fn find_matching_contract_artifact(
710    output: &mut ProjectCompileOutput,
711    target_path: &Path,
712    target_name: Option<&str>,
713) -> eyre::Result<ConfigurableContractArtifact> {
714    if let Some(name) = target_name {
715        if let Some(artifact) = output.remove(target_path, name) {
716            return Ok(artifact);
717        }
718
719        let target_path = canonicalized(target_path);
720        let matching_source = output.artifact_ids().find_map(|(id, _artifact)| {
721            (id.name == name && canonicalized(&id.source) == target_path).then(|| id.source.clone())
722        });
723
724        matching_source
725            .and_then(|source| output.remove(&source, name))
726            .ok_or_eyre(format!("Could not find artifact `{name}` in the compiled artifacts"))
727    } else {
728        let possible_targets = output
729            .artifact_ids()
730            .filter(|(id, _artifact)| id.source == target_path)
731            .collect::<Vec<_>>();
732
733        if possible_targets.is_empty() {
734            eyre::bail!(
735                "Could not find artifact linked to source `{target_path:?}` in the compiled artifacts"
736            );
737        }
738
739        let (target_id, target_artifact) = possible_targets[0].clone();
740        if possible_targets.len() == 1 {
741            return Ok(target_artifact.clone());
742        }
743
744        // If all artifact_ids in `possible_targets` have the same name (without ".", indicates
745        // additional compiler profiles), it means that there are multiple contracts in the
746        // same file.
747        if !target_id.name.contains('.')
748            && possible_targets.iter().any(|(id, _)| id.name != target_id.name)
749        {
750            eyre::bail!(
751                "Multiple contracts found in the same file, please specify the target <path>:<contract> or <contract>"
752            );
753        }
754
755        // Otherwise, we're dealing with additional compiler profiles wherein `id.source` is the
756        // same but `id.path` is different.
757        let artifact = possible_targets
758            .iter()
759            .find_map(|(id, artifact)| (id.profile == "default").then_some(*artifact))
760            .unwrap_or(target_artifact);
761
762        Ok(artifact.clone())
763    }
764}
765
766#[cfg(test)]
767mod tests {
768    use super::*;
769    use alloy_dyn_abi::DynSolValue;
770    use alloy_primitives::U256;
771    use semver::Version;
772
773    fn deployed_artifact(name: &str, code: Bytes) -> (ArtifactId, CompactContractBytecode) {
774        deployed_artifact_with_immutables(name, code, Default::default())
775    }
776
777    fn deployed_artifact_with_immutables(
778        name: &str,
779        code: Bytes,
780        immutable_references: BTreeMap<String, Vec<Offsets>>,
781    ) -> (ArtifactId, CompactContractBytecode) {
782        (
783            ArtifactId {
784                path: format!("out/{name}.json").into(),
785                name: name.to_owned(),
786                source: format!("src/{name}.sol").into(),
787                version: Version::new(0, 8, 30),
788                build_id: String::new(),
789                profile: "default".to_owned(),
790            },
791            CompactContractBytecode {
792                abi: Some(Default::default()),
793                bytecode: None,
794                deployed_bytecode: Some(CompactDeployedBytecode {
795                    bytecode: Some(CompactBytecode {
796                        object: BytecodeObject::Bytecode(code),
797                        source_map: None,
798                        link_references: Default::default(),
799                    }),
800                    immutable_references,
801                }),
802            },
803        )
804    }
805
806    #[test]
807    fn exact_creation_match_requires_canonical_constructor_suffix() {
808        let abi = JsonAbi::parse(["constructor(uint256 value)"]).unwrap();
809        let bytecode = Bytes::from_static(&[0x60, 0x00]);
810        let contract = ContractData {
811            name: "C".to_owned(),
812            abi,
813            bytecode: Some(BytecodeData {
814                object: Some(BytecodeObject::Bytecode(bytecode.clone())),
815                link_references: BTreeMap::new(),
816                immutable_references: BTreeMap::new(),
817            }),
818            deployed_bytecode: None,
819            storage_layout: None,
820        };
821        let arguments = contract
822            .abi
823            .constructor()
824            .unwrap()
825            .abi_encode_input(&[DynSolValue::Uint(U256::ONE, 256)])
826            .unwrap();
827        let creation = [bytecode.as_ref(), &arguments].concat();
828
829        assert!(matches_contract_creation(&contract, &creation));
830        assert!(!matches_contract_creation(&contract, &creation[..creation.len() - 1]));
831        assert!(!matches_contract_creation(&contract, &[creation, vec![0]].concat()));
832    }
833
834    #[test]
835    fn bytecode_diffing() {
836        assert_eq!(bytecode_diff_score(b"a", b"a"), 0.0);
837        assert_eq!(bytecode_diff_score(b"a", b"b"), 1.0);
838
839        let a_100 = &b"a".repeat(100)[..];
840        assert_eq!(bytecode_diff_score(a_100, &b"b".repeat(100)), 1.0);
841        assert_eq!(bytecode_diff_score(a_100, &b"b".repeat(99)), 1.0);
842        assert_eq!(bytecode_diff_score(a_100, &b"b".repeat(101)), 1.0);
843        assert_eq!(bytecode_diff_score(a_100, &b"b".repeat(120)), 1.0);
844        assert_eq!(bytecode_diff_score(a_100, &b"b".repeat(1000)), 1.0);
845
846        let a_99 = &b"a".repeat(99)[..];
847        assert!(bytecode_diff_score(a_100, a_99) <= 0.01);
848    }
849
850    #[test]
851    fn find_by_deployed_code_exact_with_empty_deployed() {
852        let contracts = ContractsByArtifact::new(vec![]);
853
854        assert!(contracts.find_by_deployed_code_exact(&[]).is_none());
855    }
856
857    #[test]
858    fn find_by_deployed_code_exact_unique_rejects_ambiguity() {
859        let code = Bytes::from_static(&[0x60, 0x00]);
860        let contracts = ContractsByArtifact::new([
861            deployed_artifact("A", code.clone()),
862            deployed_artifact("B", code.clone()),
863        ]);
864
865        assert!(contracts.find_by_deployed_code_exact_unique(&code).is_none());
866        assert_eq!(contracts.find_by_deployed_code_exact_with_metadata(&code).unwrap().0.name, "A");
867
868        let contracts = ContractsByArtifact::new([deployed_artifact("A", code.clone())]);
869        assert_eq!(contracts.find_by_deployed_code_exact_unique(&code).unwrap().0.name, "A");
870    }
871
872    #[test]
873    fn find_by_deployed_code_exact_unique_rejects_partial_metadata_match() {
874        let artifact_code = Bytes::from_static(&[0x60, 0x00, 0xa0, 0x00, 0x01]);
875        let deployed_code = Bytes::from_static(&[0x60, 0x00, 0xf6, 0x00, 0x01]);
876        let contracts = ContractsByArtifact::new([deployed_artifact("A", artifact_code)]);
877
878        assert!(contracts.find_by_deployed_code_exact(&deployed_code).is_some());
879        assert!(contracts.find_by_deployed_code_exact_unique(&deployed_code).is_none());
880        assert!(contracts.find_by_deployed_code_exact_with_metadata(&deployed_code).is_none());
881    }
882
883    #[test]
884    fn find_by_deployed_code_exact_unambiguous_preserves_single_partial() {
885        let artifact_code = Bytes::from_static(&[0x60, 0x00, 0xa0, 0x00, 0x01]);
886        let deployed_code = Bytes::from_static(&[0x60, 0x00, 0xf6, 0x00, 0x01]);
887        let contracts = ContractsByArtifact::new([deployed_artifact("A", artifact_code)]);
888
889        assert_eq!(
890            contracts
891                .find_by_deployed_code_exact_unambiguous(&deployed_code)
892                .unwrap()
893                .unwrap()
894                .0
895                .name,
896            "A"
897        );
898        assert!(contracts.find_by_deployed_code_exact_unambiguous(&[0x00]).unwrap().is_none());
899    }
900
901    #[test]
902    fn find_by_deployed_code_exact_unambiguous_prefers_exact_over_ambiguous_partial() {
903        let partial_code = Bytes::from_static(&[0x60, 0x00, 0xa0, 0x00, 0x01]);
904        let deployed_code = Bytes::from_static(&[0x60, 0x00, 0xf6, 0x00, 0x01]);
905        for exact_name in ["A", "Z"] {
906            let contracts = ContractsByArtifact::new([
907                deployed_artifact("B", partial_code.clone()),
908                deployed_artifact("C", partial_code.clone()),
909            ]);
910            assert!(contracts.find_by_deployed_code_exact(&deployed_code).is_some());
911            assert!(contracts.find_by_deployed_code_exact_unique(&deployed_code).is_none());
912            assert_eq!(
913                contracts
914                    .find_by_deployed_code_exact_unambiguous(&deployed_code)
915                    .unwrap_err()
916                    .to_string(),
917                "Multiple local contracts match the deployed bytecode with different metadata. Specify the contract as <path>:<contract>"
918            );
919
920            let contracts = ContractsByArtifact::new([
921                deployed_artifact(exact_name, deployed_code.clone()),
922                deployed_artifact("B", partial_code.clone()),
923                deployed_artifact("C", partial_code.clone()),
924            ]);
925            assert_eq!(
926                contracts
927                    .find_by_deployed_code_exact_unambiguous(&deployed_code)
928                    .unwrap()
929                    .unwrap()
930                    .0
931                    .name,
932                exact_name
933            );
934        }
935    }
936
937    /// Tests an immutable reference within a library call-protection prefix.
938    #[test]
939    fn find_by_deployed_code_exact_handles_overlapping_ignored_ranges() {
940        // Call-protection prefix covering [1, 21).
941        let mut code = vec![0x73u8];
942        code.extend(std::iter::repeat_n(0u8, 20));
943        // Bytes matched after the ignored range.
944        code.extend_from_slice(&[0xAA, 0xBB, 0xCC, 0xDD]);
945        let code = Bytes::from(code);
946
947        // Immutable reference [5, 8) lies within [1, 21).
948        let immutable_references =
949            BTreeMap::from([("someImmutable".to_string(), vec![Offsets { start: 5, length: 3 }])]);
950
951        let contracts = ContractsByArtifact::new([deployed_artifact_with_immutables(
952            "LibWithEarlyImmutable",
953            code.clone(),
954            immutable_references,
955        )]);
956
957        // The overlap must not panic or prevent a match.
958        assert!(contracts.find_by_deployed_code_exact(&code).is_some());
959    }
960
961    #[test]
962    fn find_by_deployed_code_exact_rejects_forged_metadata_length() {
963        // `PUSH1 0 PUSH1 1` followed by one byte of CBOR metadata and its length.
964        let contracts = ContractsByArtifact::new([deployed_artifact(
965            "A",
966            Bytes::from_static(&[0x60, 0x00, 0x60, 0x01, 0xa0, 0x00, 0x01]),
967        )]);
968
969        // Different metadata with the same length is still a partial match.
970        assert!(
971            contracts
972                .find_by_deployed_code_exact(&[0x60, 0x00, 0x60, 0x01, 0xf6, 0x00, 0x01])
973                .is_some()
974        );
975        // A forged length that declares modified code as metadata is not.
976        assert!(
977            contracts
978                .find_by_deployed_code_exact(&[0x60, 0x00, 0x60, 0x02, 0xa0, 0x00, 0x04])
979                .is_none()
980        );
981    }
982
983    #[test]
984    fn normalize_offsets_merges_overlaps_and_adjacency() {
985        // Contained overlap.
986        let mut offsets = vec![Offsets { start: 1, length: 20 }, Offsets { start: 5, length: 3 }];
987        normalize_offsets(&mut offsets);
988        assert_eq!(offsets, vec![Offsets { start: 1, length: 20 }]);
989
990        // Extending overlap.
991        let mut offsets = vec![Offsets { start: 1, length: 20 }, Offsets { start: 15, length: 15 }];
992        normalize_offsets(&mut offsets);
993        assert_eq!(offsets, vec![Offsets { start: 1, length: 29 }]);
994
995        // Adjacent ranges.
996        let mut offsets = vec![Offsets { start: 1, length: 20 }, Offsets { start: 21, length: 4 }];
997        normalize_offsets(&mut offsets);
998        assert_eq!(offsets, vec![Offsets { start: 1, length: 24 }]);
999
1000        // Disjoint ranges.
1001        let mut offsets = vec![Offsets { start: 1, length: 5 }, Offsets { start: 10, length: 5 }];
1002        normalize_offsets(&mut offsets);
1003        assert_eq!(
1004            offsets,
1005            vec![Offsets { start: 1, length: 5 }, Offsets { start: 10, length: 5 }]
1006        );
1007
1008        // Unsorted ranges.
1009        let mut offsets = vec![Offsets { start: 10, length: 5 }, Offsets { start: 1, length: 5 }];
1010        normalize_offsets(&mut offsets);
1011        assert_eq!(
1012            offsets,
1013            vec![Offsets { start: 1, length: 5 }, Offsets { start: 10, length: 5 }]
1014        );
1015    }
1016}