Skip to main content

neo_decompiler/
native_contracts.rs

1//! Lookup information for Neo native contracts.
2
3#[allow(missing_docs)]
4mod generated {
5    include!("native_contracts_generated.rs");
6}
7
8/// Metadata describing a native contract.
9pub use generated::NativeContractInfo;
10
11#[allow(dead_code)]
12const fn script_hash_lt(left: &[u8; 20], right: &[u8; 20]) -> bool {
13    let mut i = 0usize;
14    while i < 20 {
15        if left[i] < right[i] {
16            return true;
17        }
18        if left[i] > right[i] {
19            return false;
20        }
21        i += 1;
22    }
23    false
24}
25
26#[allow(dead_code)]
27const fn assert_native_contracts_sorted_by_hash(contracts: &[NativeContractInfo]) {
28    let mut i = 1usize;
29    while i < contracts.len() {
30        assert!(
31            script_hash_lt(&contracts[i - 1].script_hash, &contracts[i].script_hash),
32            "generated::NATIVE_CONTRACTS must be sorted by script_hash (strictly increasing)"
33        );
34        i += 1;
35    }
36}
37
38const _: () = assert_native_contracts_sorted_by_hash(generated::NATIVE_CONTRACTS);
39
40/// Return the native contract that matches the provided script hash (little-endian bytes).
41#[must_use]
42pub fn lookup(hash: &[u8; 20]) -> Option<&'static NativeContractInfo> {
43    generated::NATIVE_CONTRACTS
44        .binary_search_by_key(hash, |info| info.script_hash)
45        .ok()
46        .map(|index| &generated::NATIVE_CONTRACTS[index])
47}
48
49/// Return the full list of bundled native contracts.
50#[must_use]
51pub fn all() -> &'static [NativeContractInfo] {
52    generated::NATIVE_CONTRACTS
53}
54
55#[derive(Debug, Clone, PartialEq, Eq)]
56/// Additional metadata explaining how a method token maps to a native contract.
57///
58/// This is returned by [`describe_method_token`] to help callers surface a friendly
59/// label for native calls.
60///
61/// The [`NativeMethodHint::contract`] field always contains the canonical native
62/// contract name. The [`NativeMethodHint::canonical_method`] field is `Some` when
63/// the provided method name matches one of the known native methods.
64pub struct NativeMethodHint {
65    /// Canonical native contract name.
66    pub contract: &'static str,
67    /// Canonical method name when it could be resolved.
68    pub canonical_method: Option<&'static str>,
69}
70
71impl NativeMethodHint {
72    /// Format a label for displaying this hint.
73    ///
74    /// When [`NativeMethodHint::canonical_method`] is known, this returns
75    /// `<contract>::<method>`. Otherwise it embeds the provided method name as
76    /// `<contract>::<unknown <provided>>`.
77    ///
78    /// # Examples
79    /// ```
80    /// use neo_decompiler::native_contracts::NativeMethodHint;
81    ///
82    /// let hint = NativeMethodHint { contract: "Contract", canonical_method: Some("Method") };
83    /// assert_eq!(hint.formatted_label("ignored"), "Contract::Method");
84    ///
85    /// let hint = NativeMethodHint { contract: "Contract", canonical_method: None };
86    /// assert_eq!(hint.formatted_label("Provided"), "Contract::<unknown Provided>");
87    /// ```
88    #[must_use]
89    pub fn formatted_label(&self, provided: &str) -> String {
90        match self.canonical_method {
91            Some(method) => format!("{}::{method}", self.contract),
92            None => format!("{}::<unknown {provided}>", self.contract),
93        }
94    }
95
96    /// Return `true` if the hint resolved the provided method to a known native method.
97    #[must_use]
98    pub fn has_exact_method(&self) -> bool {
99        self.canonical_method.is_some()
100    }
101}
102
103/// Return native contract guidance for the supplied method token.
104#[must_use]
105pub fn describe_method_token(hash: &[u8; 20], method: &str) -> Option<NativeMethodHint> {
106    let contract = lookup(hash)?;
107    let canonical_method = contract
108        .methods
109        .iter()
110        .find(|candidate| **candidate == method)
111        .copied()
112        .or_else(|| {
113            contract
114                .methods
115                .iter()
116                .find(|candidate| candidate.eq_ignore_ascii_case(method))
117                .copied()
118        });
119    Some(NativeMethodHint {
120        contract: contract.name,
121        canonical_method,
122    })
123}
124
125#[cfg(test)]
126mod tests;