Skip to main content

neo_decompiler/decompiler/analysis/
patterns.rs

1//! Conservative contract and C# target metadata identification.
2//!
3//! Manifest declarations are authoritative. Bytecode and ABI names are useful
4//! hints, but they are reported with lower confidence and retained as evidence
5//! so callers can distinguish detection from a guess.
6
7use std::collections::BTreeSet;
8
9use serde::Serialize;
10
11use crate::instruction::{Instruction, OpCode, Operand};
12use crate::manifest::ContractManifest;
13use crate::manifest::{ManifestPermissionContract, ManifestPermissionMethods};
14use crate::native_contracts;
15use crate::nef::NefFile;
16
17mod abi;
18mod language;
19mod native_patterns;
20mod syscall_patterns;
21
22/// Confidence assigned to an identified pattern or C# target hint.
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize)]
24#[serde(rename_all = "lowercase")]
25pub enum PatternConfidence {
26    /// Evidence directly declared by the manifest.
27    High,
28    /// Multiple independent ABI, bytecode, or metadata hints agree.
29    Medium,
30    /// A single weak hint is available.
31    Low,
32    /// No reliable pattern signal was found.
33    #[default]
34    Unknown,
35}
36
37/// A signal supporting one or more detected patterns.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
39#[serde(rename_all = "camelCase")]
40pub struct PatternEvidence {
41    /// Analysis surface that produced the signal.
42    pub source: String,
43    /// Human-readable signal value.
44    pub value: String,
45}
46
47/// Best-effort contract standard and C# target summary.
48#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]
49#[serde(rename_all = "camelCase")]
50pub struct PatternInfo {
51    /// Declared or inferred Neo standards, sorted and deduplicated.
52    pub standards: Vec<String>,
53    /// Contract behavior patterns such as `storage`, `storage_writes`, or
54    /// `notifications`.
55    pub patterns: Vec<String>,
56    /// Inferred source target. This is currently limited to C# because C# is
57    /// the only generated source backend.
58    pub language: Option<String>,
59    /// Raw compiler identifier from the NEF header.
60    pub compiler: Option<String>,
61    /// Aggregate confidence for the summary.
62    pub confidence: PatternConfidence,
63    /// Signals retained for explainability.
64    pub evidence: Vec<PatternEvidence>,
65}
66
67/// Identify standards, common contract shapes, and C# compiler hints.
68#[must_use]
69pub fn identify_patterns(
70    nef: &NefFile,
71    instructions: &[Instruction],
72    manifest: Option<&ContractManifest>,
73) -> PatternInfo {
74    let mut info = PatternInfo::default();
75    let mut standards = BTreeSet::new();
76    let mut patterns = BTreeSet::new();
77    let mut evidence = Vec::new();
78    let mut strong_standard = false;
79
80    if let Some(manifest) = manifest {
81        for standard in &manifest.supported_standards {
82            let standard = standard.trim().to_uppercase();
83            if standard.is_empty() {
84                continue;
85            }
86            standards.insert(standard.clone());
87            strong_standard = true;
88            evidence.push(PatternEvidence {
89                source: "manifest.supportedstandards".to_string(),
90                value: standard.clone(),
91            });
92            if standard.starts_with("NEP-") {
93                patterns.insert(standard);
94            }
95        }
96
97        let names: BTreeSet<_> = manifest
98            .abi
99            .methods
100            .iter()
101            .map(|method| method.name.to_ascii_lowercase())
102            .collect();
103        abi::infer_abi_patterns(&names, &mut standards, &mut patterns, &mut evidence);
104
105        if !manifest.abi.events.is_empty() {
106            patterns.insert("events".to_string());
107            evidence.push(PatternEvidence {
108                source: "manifest.abi.events".to_string(),
109                value: manifest.abi.events.len().to_string(),
110            });
111        }
112        let has_transfer_event = manifest
113            .abi
114            .events
115            .iter()
116            .any(|event| event.name.eq_ignore_ascii_case("Transfer"));
117        if has_transfer_event {
118            evidence.push(PatternEvidence {
119                source: "manifest.abi.events".to_string(),
120                value: "Transfer".to_string(),
121            });
122            if names.contains("transfer") {
123                patterns.insert("token_transfers".to_string());
124                evidence.push(PatternEvidence {
125                    source: "manifest.abi.methods".to_string(),
126                    value: "transfer + Transfer".to_string(),
127                });
128            }
129        }
130
131        if !manifest.permissions.is_empty() {
132            patterns.insert("call_permissions".to_string());
133            evidence.push(PatternEvidence {
134                source: "manifest.permissions".to_string(),
135                value: manifest.permissions.len().to_string(),
136            });
137        }
138        if manifest.permissions.iter().any(|permission| {
139            matches!(
140                &permission.contract,
141                ManifestPermissionContract::Wildcard(_)
142            ) || matches!(&permission.methods, ManifestPermissionMethods::Wildcard(_))
143        }) {
144            patterns.insert("wildcard_permissions".to_string());
145            evidence.push(PatternEvidence {
146                source: "manifest.permissions".to_string(),
147                value: "wildcard".to_string(),
148            });
149        }
150    }
151
152    let syscall_names: BTreeSet<_> = instructions
153        .iter()
154        .filter_map(|instruction| match instruction.opcode {
155            OpCode::Syscall => match instruction.operand {
156                Some(Operand::Syscall(hash)) => crate::syscalls::lookup(hash).map(|info| info.name),
157                _ => None,
158            },
159            _ => None,
160        })
161        .collect();
162    if !nef.method_tokens.is_empty() {
163        patterns.insert("method_tokens".to_string());
164        evidence.push(PatternEvidence {
165            source: "nef.method_tokens".to_string(),
166            value: nef.method_tokens.len().to_string(),
167        });
168    }
169    for token in &nef.method_tokens {
170        if let Some(hint) = native_contracts::describe_method_token(&token.hash, &token.method)
171            .filter(|hint| hint.has_exact_method())
172        {
173            patterns.insert("native_contract_calls".to_string());
174            let label = hint.formatted_label(&token.method);
175            evidence.push(PatternEvidence {
176                source: "nef.method_tokens.native".to_string(),
177                value: label.clone(),
178            });
179            native_patterns::infer_native_patterns(&hint, &label, &mut patterns, &mut evidence);
180        }
181    }
182    if instructions.iter().any(|instruction| {
183        matches!(instruction.opcode, OpCode::CallA | OpCode::CallT)
184            || matches!(
185                instruction.operand,
186                Some(Operand::Syscall(hash))
187                    if crate::syscalls::lookup(hash)
188                        .is_some_and(|info| info.name == "System.Contract.Call")
189            )
190    }) {
191        patterns.insert("external_calls".to_string());
192        evidence.push(PatternEvidence {
193            source: "bytecode.calls".to_string(),
194            value: "CALLA/CALLT/Contract.Call".to_string(),
195        });
196    }
197    for name in syscall_names {
198        syscall_patterns::infer_syscall_patterns(name, &mut patterns, &mut evidence);
199    }
200
201    // Backward relative jumps are a reliable structural signal for recovered
202    // loop / iteration shapes (while/for/do-while), independent of rendering.
203    if instructions.iter().any(|instruction| {
204        matches!(
205            instruction.opcode,
206            OpCode::Jmp
207                | OpCode::Jmpif
208                | OpCode::Jmpifnot
209                | OpCode::JmpEq
210                | OpCode::JmpNe
211                | OpCode::JmpLt
212                | OpCode::JmpLe
213                | OpCode::JmpGt
214                | OpCode::JmpGe
215                | OpCode::Jmp_L
216                | OpCode::Jmpif_L
217                | OpCode::Jmpifnot_L
218                | OpCode::JmpEq_L
219                | OpCode::JmpNe_L
220                | OpCode::JmpLt_L
221                | OpCode::JmpLe_L
222                | OpCode::JmpGt_L
223                | OpCode::JmpGe_L
224        ) && match &instruction.operand {
225            Some(Operand::Jump(delta)) => *delta < 0,
226            Some(Operand::Jump32(delta)) => *delta < 0,
227            _ => false,
228        }
229    }) {
230        patterns.insert("loops".to_string());
231        evidence.push(PatternEvidence {
232            source: "bytecode.control_flow".to_string(),
233            value: "backward jump".to_string(),
234        });
235    }
236
237    let compiler = (!nef.header.compiler.trim().is_empty()).then(|| nef.header.compiler.clone());
238    if let Some(compiler) = compiler.as_deref() {
239        evidence.push(PatternEvidence {
240            source: "nef.header.compiler".to_string(),
241            value: compiler.to_string(),
242        });
243    }
244    if !nef.header.source.trim().is_empty() {
245        evidence.push(PatternEvidence {
246            source: "nef.header.source".to_string(),
247            value: nef.header.source.clone(),
248        });
249    }
250    let compiler_language = compiler.as_deref().and_then(language::infer_language);
251    let language =
252        compiler_language.or_else(|| language::infer_language_from_source(&nef.header.source));
253
254    let confidence = if strong_standard {
255        PatternConfidence::High
256    } else if compiler_language.is_some()
257        || patterns.contains("NEP-17")
258        || patterns.contains("NEP-11")
259        || (evidence.len() >= 2 && !patterns.is_empty())
260    {
261        PatternConfidence::Medium
262    } else if !evidence.is_empty() {
263        PatternConfidence::Low
264    } else {
265        PatternConfidence::Unknown
266    };
267
268    info.standards = standards.into_iter().collect();
269    info.patterns = patterns.into_iter().collect();
270    info.language = language.map(str::to_string);
271    info.compiler = compiler;
272    info.confidence = confidence;
273    evidence.sort_by(|left, right| {
274        left.source
275            .cmp(&right.source)
276            .then_with(|| left.value.cmp(&right.value))
277    });
278    info.evidence = evidence;
279    info
280}
281
282#[cfg(test)]
283#[path = "patterns/tests.rs"]
284mod tests;