1use std::collections::HashSet;
2
3use serde::Serialize;
4use serde_json::Value;
5
6use crate::decompiler::analysis::{
7 call_graph::CallGraph, method_contracts::MethodContracts, patterns::PatternInfo,
8 types::TypeInfo, xrefs::Xrefs,
9};
10use crate::decompiler::Decompilation;
11use crate::disassembler::DisassemblyOutput;
12use crate::instruction::{Instruction, OpCode, Operand};
13use crate::manifest::{
14 ContractManifest, ManifestPermissionContract, ManifestPermissionMethods, ManifestTrusts,
15};
16use crate::native_contracts;
17use crate::nef::{call_flag_labels, MethodToken, NefFile};
18use crate::util;
19
20#[derive(Debug, Clone, Serialize)]
22pub struct WebInfoReport {
23 compiler: String,
24 source: Option<String>,
25 script_length: usize,
26 script_hash_le: String,
27 script_hash_be: String,
28 checksum: String,
29 method_tokens: Vec<MethodTokenReport>,
30 manifest: Option<ManifestSummary>,
31 warnings: Vec<String>,
32}
33
34#[derive(Debug, Clone, Serialize)]
36pub struct WebDisasmReport {
37 script_hash_le: String,
38 script_hash_be: String,
39 instructions: Vec<InstructionReport>,
40 warnings: Vec<String>,
41}
42
43#[derive(Debug, Clone, Serialize)]
45pub struct WebDecompileReport {
46 compiler: String,
47 source: Option<String>,
48 script_hash_le: String,
49 script_hash_be: String,
50 csharp: String,
51 high_level: String,
52 pseudocode: String,
53 instructions: Vec<InstructionReport>,
54 method_tokens: Vec<MethodTokenReport>,
55 manifest: Option<ManifestSummary>,
56 analysis: AnalysisReport,
57 warnings: Vec<String>,
58}
59
60pub(super) fn build_info_report(
61 nef: &NefFile,
62 manifest: Option<&ContractManifest>,
63) -> WebInfoReport {
64 let script_hash = nef.script_hash();
65 let method_tokens: Vec<MethodTokenReport> = nef
66 .method_tokens
67 .iter()
68 .map(build_method_token_report)
69 .collect();
70 WebInfoReport {
71 compiler: nef.header.compiler.trim_end_matches('\0').to_string(),
72 source: (!nef.header.source.is_empty()).then(|| nef.header.source.clone()),
73 script_length: nef.script.len(),
74 script_hash_le: util::format_hash(&script_hash),
75 script_hash_be: util::format_hash_be(&script_hash),
76 checksum: format!("0x{:08X}", nef.checksum),
77 warnings: collect_warnings(&method_tokens),
78 method_tokens,
79 manifest: manifest.map(summarize_manifest),
80 }
81}
82
83pub(super) fn build_disasm_report(nef: &NefFile, output: DisassemblyOutput) -> WebDisasmReport {
84 let script_hash = nef.script_hash();
85 WebDisasmReport {
86 script_hash_le: util::format_hash(&script_hash),
87 script_hash_be: util::format_hash_be(&script_hash),
88 instructions: output
89 .instructions
90 .iter()
91 .map(InstructionReport::from)
92 .collect(),
93 warnings: output.warnings.iter().map(ToString::to_string).collect(),
94 }
95}
96
97pub(super) fn build_decompile_report(result: Decompilation) -> WebDecompileReport {
98 let Decompilation {
99 nef,
100 manifest,
101 warnings: decompile_warnings,
102 instructions,
103 call_graph,
104 method_contracts,
105 patterns,
106 xrefs,
107 types,
108 pseudocode,
109 high_level,
110 csharp,
111 ..
112 } = result;
113 let script_hash = nef.script_hash();
114 let method_tokens: Vec<MethodTokenReport> = nef
115 .method_tokens
116 .iter()
117 .map(build_method_token_report)
118 .collect();
119 let mut warnings = Vec::new();
120 let mut seen = HashSet::new();
121 for warning in collect_warnings(&method_tokens)
122 .into_iter()
123 .chain(decompile_warnings)
124 {
125 if seen.insert(warning.clone()) {
126 warnings.push(warning);
127 }
128 }
129
130 WebDecompileReport {
131 compiler: nef.header.compiler.trim_end_matches('\0').to_string(),
132 source: (!nef.header.source.is_empty()).then(|| nef.header.source.clone()),
133 script_hash_le: util::format_hash(&script_hash),
134 script_hash_be: util::format_hash_be(&script_hash),
135 csharp: csharp.unwrap_or_default(),
136 high_level: high_level.unwrap_or_default(),
137 pseudocode: pseudocode.unwrap_or_default(),
138 instructions: instructions.iter().map(InstructionReport::from).collect(),
139 method_tokens,
140 manifest: manifest.as_ref().map(summarize_manifest),
141 analysis: AnalysisReport {
142 call_graph,
143 method_contracts,
144 patterns,
145 xrefs,
146 types,
147 },
148 warnings,
149 }
150}
151
152#[derive(Debug, Clone, Serialize)]
153struct AnalysisReport {
154 call_graph: CallGraph,
155 method_contracts: MethodContracts,
156 xrefs: Xrefs,
157 types: TypeInfo,
158 patterns: PatternInfo,
159}
160
161#[derive(Debug, Clone, Serialize)]
162struct InstructionReport {
163 offset: usize,
164 opcode: String,
165 operand: Option<String>,
166 operand_kind: Option<String>,
167 operand_value: Option<OperandValueReport>,
168 returns_value: Option<bool>,
169}
170
171impl From<&Instruction> for InstructionReport {
172 fn from(instruction: &Instruction) -> Self {
173 InstructionReport {
174 offset: instruction.offset,
175 opcode: instruction.opcode.mnemonic().to_string(),
176 operand: instruction.operand.as_ref().map(ToString::to_string),
177 operand_kind: instruction
178 .operand
179 .as_ref()
180 .map(|op| operand_kind_name(op).to_string()),
181 operand_value: instruction.operand.as_ref().map(operand_value_report),
182 returns_value: returns_value_for_instruction(instruction),
183 }
184 }
185}
186
187fn operand_kind_name(operand: &Operand) -> &'static str {
188 match operand {
189 Operand::I8(_) => "I8",
190 Operand::I16(_) => "I16",
191 Operand::I32(_) => "I32",
192 Operand::I64(_) => "I64",
193 Operand::Bytes(_) => "Bytes",
194 Operand::Jump(_) => "Jump8",
195 Operand::Jump32(_) => "Jump32",
196 Operand::Syscall(_) => "Syscall",
197 Operand::U8(_) => "U8",
198 Operand::U16(_) => "U16",
199 Operand::U32(_) => "U32",
200 Operand::Bool(_) => "Bool",
201 Operand::Null => "Null",
202 }
203}
204
205#[derive(Debug, Clone, Serialize)]
206#[serde(tag = "type", content = "value")]
207enum OperandValueReport {
208 I8(i8),
209 I16(i16),
210 I32(i32),
211 I64(i64),
212 U8(u8),
213 U16(u16),
214 U32(u32),
215 Bool(bool),
216 Bytes(String),
217 Jump(i32),
218 Jump32(i32),
219 Syscall(u32),
220 Null,
221}
222
223fn operand_value_report(operand: &Operand) -> OperandValueReport {
224 match operand {
225 Operand::I8(value) => OperandValueReport::I8(*value),
226 Operand::I16(value) => OperandValueReport::I16(*value),
227 Operand::I32(value) => OperandValueReport::I32(*value),
228 Operand::I64(value) => OperandValueReport::I64(*value),
229 Operand::U8(value) => OperandValueReport::U8(*value),
230 Operand::U16(value) => OperandValueReport::U16(*value),
231 Operand::U32(value) => OperandValueReport::U32(*value),
232 Operand::Bool(value) => OperandValueReport::Bool(*value),
233 Operand::Jump(value) => OperandValueReport::Jump(*value as i32),
234 Operand::Jump32(value) => OperandValueReport::Jump32(*value),
235 Operand::Syscall(value) => OperandValueReport::Syscall(*value),
236 Operand::Bytes(bytes) => {
237 OperandValueReport::Bytes(format!("0x{}", util::upper_hex_string(bytes)))
238 }
239 Operand::Null => OperandValueReport::Null,
240 }
241}
242
243fn returns_value_for_instruction(instruction: &Instruction) -> Option<bool> {
244 if let OpCode::Syscall = instruction.opcode {
245 if let Some(Operand::Syscall(hash)) = instruction.operand {
246 return crate::syscalls::lookup(hash).map(|info| info.returns_value);
247 }
248 }
249 None
250}
251
252#[derive(Debug, Clone, Serialize)]
253struct MethodTokenReport {
254 method: String,
255 hash_le: String,
256 hash_be: String,
257 parameters: u16,
258 returns: bool,
259 call_flags: u8,
260 call_flag_labels: Vec<&'static str>,
261 returns_value: bool,
262 native_contract: Option<NativeContractReport>,
263 warning: Option<String>,
264}
265
266#[derive(Debug, Clone, Serialize)]
267struct NativeContractReport {
268 contract: String,
269 method: Option<String>,
270 label: String,
271}
272
273fn build_method_token_report(token: &MethodToken) -> MethodTokenReport {
274 let hint = native_contracts::describe_method_token(&token.hash, &token.method);
275 let warning = hint.as_ref().and_then(|h| {
276 if h.has_exact_method() {
277 None
278 } else {
279 Some(format!(
280 "native contract {} does not expose method {}",
281 h.contract, token.method
282 ))
283 }
284 });
285 let native_contract = hint.as_ref().map(|h| NativeContractReport {
286 contract: h.contract.to_string(),
287 method: h.canonical_method.map(ToString::to_string),
288 label: h.formatted_label(&token.method),
289 });
290
291 MethodTokenReport {
292 method: token.method.clone(),
293 hash_le: util::format_hash(&token.hash),
294 hash_be: util::format_hash_be(&token.hash),
295 parameters: token.parameters_count,
296 returns: token.has_return_value,
297 call_flags: token.call_flags,
298 call_flag_labels: call_flag_labels(token.call_flags),
299 returns_value: token.has_return_value,
300 native_contract,
301 warning,
302 }
303}
304
305fn collect_warnings(tokens: &[MethodTokenReport]) -> Vec<String> {
306 tokens
307 .iter()
308 .filter_map(|report| report.warning.as_ref().map(ToString::to_string))
309 .collect()
310}
311
312#[derive(Debug, Clone, Serialize)]
313struct ManifestSummary {
314 name: String,
315 supported_standards: Vec<String>,
316 features: serde_json::Map<String, Value>,
319 groups: Vec<GroupSummary>,
320 methods: usize,
321 events: usize,
322 permissions: Vec<PermissionSummary>,
323 trusts: Option<TrustSummary>,
324 abi: AbiSummary,
325 #[serde(skip_serializing_if = "Option::is_none")]
329 extra: Option<Value>,
330}
331
332#[derive(Debug, Clone, Serialize)]
333struct GroupSummary {
334 pubkey: String,
335 signature: String,
336}
337
338#[derive(Debug, Clone, Serialize)]
339struct PermissionSummary {
340 contract: PermissionContractSummary,
341 methods: PermissionMethodsSummary,
342}
343
344#[derive(Debug, Clone, Serialize)]
345#[serde(tag = "type", content = "value")]
346enum PermissionContractSummary {
347 Wildcard(String),
348 Hash(String),
349 Group(String),
350 Other(Value),
351}
352
353#[derive(Debug, Clone, Serialize)]
354#[serde(tag = "type", content = "value")]
355enum PermissionMethodsSummary {
356 Wildcard(String),
357 Methods(Vec<String>),
358}
359
360#[derive(Debug, Clone, Serialize)]
361#[serde(tag = "type", content = "value")]
362enum TrustSummary {
363 Wildcard(String),
364 Contracts(Vec<String>),
365 Other(Value),
366}
367
368#[derive(Debug, Clone, Serialize)]
369struct AbiSummary {
370 methods: Vec<MethodSummary>,
371 events: Vec<EventSummary>,
372}
373
374#[derive(Debug, Clone, Serialize)]
375struct MethodSummary {
376 name: String,
377 parameters: Vec<ParameterSummary>,
378 return_type: String,
379 safe: bool,
380 offset: Option<i32>,
381}
382
383#[derive(Debug, Clone, Serialize)]
384struct EventSummary {
385 name: String,
386 parameters: Vec<ParameterSummary>,
387}
388
389#[derive(Debug, Clone, Serialize)]
390struct ParameterSummary {
391 name: String,
392 ty: String,
393}
394
395fn summarize_manifest(manifest: &ContractManifest) -> ManifestSummary {
396 ManifestSummary {
397 name: manifest.name.clone(),
398 supported_standards: manifest.supported_standards.clone(),
399 features: manifest.features.clone(),
400 groups: manifest
401 .groups
402 .iter()
403 .map(|group| GroupSummary {
404 pubkey: group.pubkey.clone(),
405 signature: group.signature.clone(),
406 })
407 .collect(),
408 methods: manifest.abi.methods.len(),
409 events: manifest.abi.events.len(),
410 permissions: manifest
411 .permissions
412 .iter()
413 .map(|permission| PermissionSummary {
414 contract: PermissionContractSummary::from(&permission.contract),
415 methods: PermissionMethodsSummary::from(&permission.methods),
416 })
417 .collect(),
418 trusts: manifest.trusts.as_ref().map(TrustSummary::from),
419 extra: manifest.extra.clone(),
420 abi: AbiSummary {
421 methods: manifest
422 .abi
423 .methods
424 .iter()
425 .map(|method| MethodSummary {
426 name: method.name.clone(),
427 parameters: method
428 .parameters
429 .iter()
430 .map(|param| ParameterSummary {
431 name: param.name.clone(),
432 ty: param.kind.clone(),
433 })
434 .collect(),
435 return_type: method.return_type.clone(),
436 safe: method.safe,
437 offset: method.offset,
438 })
439 .collect(),
440 events: manifest
441 .abi
442 .events
443 .iter()
444 .map(|event| EventSummary {
445 name: event.name.clone(),
446 parameters: event
447 .parameters
448 .iter()
449 .map(|param| ParameterSummary {
450 name: param.name.clone(),
451 ty: param.kind.clone(),
452 })
453 .collect(),
454 })
455 .collect(),
456 },
457 }
458}
459
460impl From<&ManifestPermissionContract> for PermissionContractSummary {
461 fn from(contract: &ManifestPermissionContract) -> Self {
462 match contract {
463 ManifestPermissionContract::Wildcard(value) => {
464 PermissionContractSummary::Wildcard(value.clone())
465 }
466 ManifestPermissionContract::Hash { hash } => {
467 PermissionContractSummary::Hash(hash.clone())
468 }
469 ManifestPermissionContract::Group { group } => {
470 PermissionContractSummary::Group(group.clone())
471 }
472 ManifestPermissionContract::Other(value) => {
473 PermissionContractSummary::Other(value.clone())
474 }
475 }
476 }
477}
478
479impl From<&ManifestPermissionMethods> for PermissionMethodsSummary {
480 fn from(methods: &ManifestPermissionMethods) -> Self {
481 match methods {
482 ManifestPermissionMethods::Wildcard(value) => {
483 PermissionMethodsSummary::Wildcard(value.clone())
484 }
485 ManifestPermissionMethods::Methods(list) => {
486 PermissionMethodsSummary::Methods(list.clone())
487 }
488 }
489 }
490}
491
492impl From<&ManifestTrusts> for TrustSummary {
493 fn from(trusts: &ManifestTrusts) -> Self {
494 match trusts {
495 ManifestTrusts::Wildcard(value) => TrustSummary::Wildcard(value.clone()),
496 ManifestTrusts::Contracts(values) => TrustSummary::Contracts(values.clone()),
497 ManifestTrusts::Other(value) => TrustSummary::Other(value.clone()),
498 }
499 }
500}