neo-decompiler 0.11.0

Neo N3 NEF decompiler: parse, disassemble, lift bytecode to high-level pseudocode and C# skeletons, with a CLI, JSON reports, and optional WebAssembly bindings.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
//! End-to-end coverage for `Decompiler::with_typed_declarations`.
//!
//! Phase 1 of the advanced-decompiler evolution: the existing-but-unused
//! type-inference engine (`analysis::types`) now annotates inferred argument
//! signatures plus local/static declarations. Opt-in (default off) so
//! historical output is unchanged.

#![allow(clippy::unwrap_used)]

use std::fs;

use neo_decompiler::instruction::OpCode;
use neo_decompiler::{ContractManifest, Decompiler, OutputFormat};

/// Locate the repo root from CARGO_MANIFEST_DIR.
fn repo_root() -> std::path::PathBuf {
    std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
}

/// Read a `(nef, manifest)` pair from TestingArtifacts.
fn artifact(name: &str) -> (Vec<u8>, Option<String>) {
    let root = repo_root();
    let nef = fs::read(
        root.join("TestingArtifacts")
            .join(name)
            .with_extension("nef"),
    )
    .unwrap();
    let manifest = fs::read_to_string(
        root.join("TestingArtifacts")
            .join(name)
            .with_extension("manifest.json"),
    )
    .ok();
    (nef, manifest)
}

fn write_varint(buf: &mut Vec<u8>, value: u32) {
    match value {
        0x00..=0xFC => buf.push(value as u8),
        0xFD..=0xFFFF => {
            buf.push(0xFD);
            buf.extend_from_slice(&(value as u16).to_le_bytes());
        }
        _ => {
            buf.push(0xFE);
            buf.extend_from_slice(&value.to_le_bytes());
        }
    }
}

fn build_nef(script: &[u8]) -> Vec<u8> {
    let mut data = Vec::new();
    data.extend_from_slice(b"NEF3");
    let mut compiler = [0u8; 64];
    compiler[..4].copy_from_slice(b"test");
    data.extend_from_slice(&compiler);
    data.push(0); // source
    data.push(0); // reserved byte
    data.push(0); // method tokens
    data.extend_from_slice(&0u16.to_le_bytes()); // reserved word
    write_varint(&mut data, script.len() as u32);
    data.extend_from_slice(script);
    let checksum = neo_decompiler::nef::NefParser::calculate_checksum(&data);
    data.extend_from_slice(&checksum.to_le_bytes());
    data
}

fn decompile_csharp(nef: &[u8], manifest: Option<&str>, typed: bool) -> String {
    let m = manifest.and_then(|s| ContractManifest::from_json_str(s).ok());
    let decompiler = Decompiler::new().with_typed_declarations(typed);
    let dec = decompiler
        .decompile_bytes_with_manifest(nef, m, OutputFormat::CSharp)
        .unwrap();
    dec.csharp.unwrap_or_default()
}

fn decompile_high_level(nef: &[u8], manifest: Option<&str>, typed: bool) -> String {
    let m = manifest.and_then(|s| ContractManifest::from_json_str(s).ok());
    let decompiler = Decompiler::new().with_typed_declarations(typed);
    let dec = decompiler
        .decompile_bytes_with_manifest(nef, m, OutputFormat::HighLevel)
        .unwrap();
    dec.high_level.unwrap_or_default()
}

#[test]
fn typed_declarations_annotate_inferred_integer_locals() {
    // LoopIf: a counter `loc0` initialised from PUSH0 and used with PUSH3/LT
    // and INC — type inference should resolve it to Integer → `BigInteger`.
    let (nef, manifest) = artifact("edgecases/LoopIf");

    // Default (off): body locals render as `var loc0`, never typed.
    let untyped = decompile_csharp(&nef, manifest.as_deref(), false);
    assert!(
        !untyped.contains("BigInteger loc0"),
        "typed-off output must not declare loc0 as BigInteger:\n{untyped}"
    );

    // Opt-in (on): the same local is now declared with its inferred type.
    let typed = decompile_csharp(&nef, manifest.as_deref(), true);
    assert!(
        typed.contains("BigInteger loc0"),
        "typed output should declare loc0 as BigInteger; got:\n{typed}"
    );
}

#[test]
fn typed_declarations_annotate_high_level_inferred_integer_locals() {
    // Same inference path as C#: when opted in, the pseudo-language should
    // expose the recovered local type too.
    let (nef, manifest) = artifact("edgecases/LoopIf");

    let untyped = decompile_high_level(&nef, manifest.as_deref(), false);
    assert!(
        !untyped.contains("int loc0"),
        "typed-off high-level output must not declare loc0 as int:\n{untyped}"
    );

    let typed = decompile_high_level(&nef, manifest.as_deref(), true);
    assert!(
        typed.contains("int loc0"),
        "typed high-level output should declare loc0 as int; got:\n{typed}"
    );
}

#[test]
fn typed_declarations_annotate_inferred_static_slots() {
    // INITSSLOT 1; NEWMAP; STSFLD0; RET infers static0 as a Map.
    let nef = build_nef(&[
        OpCode::Initsslot.byte(),
        0x01,
        OpCode::Newmap.byte(),
        OpCode::Stsfld0.byte(),
        OpCode::Ret.byte(),
    ]);

    let high_level_untyped = decompile_high_level(&nef, None, false);
    assert!(
        !high_level_untyped.contains("map static0"),
        "typed-off high-level output must not declare static0 as map:\n{high_level_untyped}"
    );

    let high_level_typed = decompile_high_level(&nef, None, true);
    assert!(
        high_level_typed.contains("map static0 = Map();"),
        "typed high-level output should declare static0 as map; got:\n{high_level_typed}"
    );

    let csharp_untyped = decompile_csharp(&nef, None, false);
    assert!(
        !csharp_untyped.contains("Map static0"),
        "typed-off C# output must not declare static0 as Map:\n{csharp_untyped}"
    );

    let csharp_typed = decompile_csharp(&nef, None, true);
    assert!(
        csharp_typed.contains("Map static0 = new Map<object, object>();"),
        "typed C# output should declare static0 as Map; got:\n{csharp_typed}"
    );
}

#[test]
fn typed_declarations_annotate_csharp_for_loop_initializers() {
    // Script models: for (loc0 = 0; loc0 < 3; loc0++) {}
    let nef = build_nef(&[
        OpCode::Initslot.byte(),
        0x01,
        0x00,
        OpCode::Push0.byte(),
        OpCode::Stloc0.byte(),
        OpCode::Ldloc0.byte(),
        OpCode::Push3.byte(),
        OpCode::Lt.byte(),
        OpCode::Jmpifnot.byte(),
        0x09,
        OpCode::Nop.byte(),
        OpCode::Ldloc0.byte(),
        OpCode::Push1.byte(),
        OpCode::Add.byte(),
        OpCode::Stloc0.byte(),
        OpCode::Jmp.byte(),
        0xF6,
        OpCode::Ret.byte(),
    ]);

    let untyped = decompile_csharp(&nef, None, false);
    assert!(
        !untyped.contains("for (BigInteger loc0"),
        "typed-off C# output must keep for-loop declarations untyped:\n{untyped}"
    );

    let typed = decompile_csharp(&nef, None, true);
    assert!(
        typed.contains("for (BigInteger loc0"),
        "typed C# output should annotate for-loop loc0 declarations; got:\n{typed}"
    );
}

#[test]
fn typed_declarations_annotate_high_level_inferred_arguments() {
    // INITSLOT 0 locals, 1 arg; LDARG0; PUSH1; ADD; RET. The ADD operands
    // force arg0 to Integer, so typed high-level output should expose that in
    // the manifestless entry signature.
    let nef = build_nef(&[
        OpCode::Initslot.byte(),
        0x00,
        0x01,
        OpCode::Ldarg0.byte(),
        OpCode::Push1.byte(),
        OpCode::Add.byte(),
        OpCode::Ret.byte(),
    ]);

    let untyped = decompile_high_level(&nef, None, false);
    assert!(
        untyped.contains("fn script_entry(arg0)"),
        "typed-off high-level output should preserve the historical untyped argument signature:\n{untyped}"
    );

    let typed = decompile_high_level(&nef, None, true);
    assert!(
        typed.contains("fn script_entry(arg0: int)"),
        "typed high-level output should annotate inferred argument types; got:\n{typed}"
    );
}

#[test]
fn typed_declarations_annotate_csharp_inferred_arguments() {
    // Same script as the high-level test: arg0 participates in ADD and should
    // therefore render as BigInteger when typed declarations are enabled.
    let nef = build_nef(&[
        OpCode::Initslot.byte(),
        0x00,
        0x01,
        OpCode::Ldarg0.byte(),
        OpCode::Push1.byte(),
        OpCode::Add.byte(),
        OpCode::Ret.byte(),
    ]);

    let untyped = decompile_csharp(&nef, None, false);
    assert!(
        untyped.contains("public static object ScriptEntry(object arg0)"),
        "typed-off C# output should preserve the historical object argument signature:\n{untyped}"
    );

    let typed = decompile_csharp(&nef, None, true);
    assert!(
        typed.contains("public static object ScriptEntry(BigInteger arg0)"),
        "typed C# output should annotate inferred argument types; got:\n{typed}"
    );
}

#[test]
fn typed_declarations_backpropagate_argument_types_through_local_aliases() {
    // INITSLOT 1 local, 1 arg; LDARG0; STLOC0; LDLOC0; PUSH1; ADD; RET.
    // Optimizing compilers often copy arguments into local slots before use; a
    // numeric constraint on the local alias should still recover arg0's type.
    let nef = build_nef(&[
        OpCode::Initslot.byte(),
        0x01,
        0x01,
        OpCode::Ldarg0.byte(),
        OpCode::Stloc0.byte(),
        OpCode::Ldloc0.byte(),
        OpCode::Push1.byte(),
        OpCode::Add.byte(),
        OpCode::Ret.byte(),
    ]);

    let high_level = decompile_high_level(&nef, None, true);
    assert!(
        high_level.contains("fn script_entry(arg0: int)"),
        "typed high-level output should backpropagate local alias constraints to arg0; got:\n{high_level}"
    );
    assert!(
        high_level.contains("int loc0"),
        "typed high-level output should still annotate the local alias; got:\n{high_level}"
    );

    let csharp = decompile_csharp(&nef, None, true);
    assert!(
        csharp.contains("public static object ScriptEntry(BigInteger arg0)"),
        "typed C# output should backpropagate local alias constraints to arg0; got:\n{csharp}"
    );
    assert!(
        csharp.contains("BigInteger loc0"),
        "typed C# output should still annotate the local alias; got:\n{csharp}"
    );
}

#[test]
fn typed_declarations_annotate_collection_helper_results() {
    // INITSLOT 2 locals, 0 args; NEWMAP; DUP; KEYS; STLOC0; VALUES; STLOC1; RET.
    // KEYS and VALUES return arrays, not the consumed map.
    let nef = build_nef(&[
        OpCode::Initslot.byte(),
        0x02,
        0x00,
        OpCode::Newmap.byte(),
        OpCode::Dup.byte(),
        OpCode::Keys.byte(),
        OpCode::Stloc0.byte(),
        OpCode::Values.byte(),
        OpCode::Stloc1.byte(),
        OpCode::Ret.byte(),
    ]);

    let high_level = decompile_high_level(&nef, None, true);
    assert!(
        high_level.contains("object[] loc0"),
        "typed high-level output should annotate KEYS result as object[]; got:\n{high_level}"
    );
    assert!(
        high_level.contains("object[] loc1"),
        "typed high-level output should annotate VALUES result as object[]; got:\n{high_level}"
    );

    let csharp = decompile_csharp(&nef, None, true);
    assert!(
        csharp.contains("object[] loc0"),
        "typed C# output should annotate KEYS result as object[]; got:\n{csharp}"
    );
    assert!(
        csharp.contains("object[] loc1"),
        "typed C# output should annotate VALUES result as object[]; got:\n{csharp}"
    );
}

#[test]
fn typed_declarations_annotate_byte_slice_results() {
    // INITSLOT 3 locals, 0 args. SUBSTR/LEFT/RIGHT return ByteString-like
    // values; without explicit opcode modeling each store incorrectly sees the
    // integer count on top.
    let nef = build_nef(&[
        OpCode::Initslot.byte(),
        0x03,
        0x00,
        OpCode::Pushdata1.byte(),
        0x03,
        b'a',
        b'b',
        b'c',
        OpCode::Push0.byte(),
        OpCode::Push1.byte(),
        OpCode::Substr.byte(),
        OpCode::Stloc0.byte(),
        OpCode::Pushdata1.byte(),
        0x03,
        b'a',
        b'b',
        b'c',
        OpCode::Push1.byte(),
        OpCode::Left.byte(),
        OpCode::Stloc1.byte(),
        OpCode::Pushdata1.byte(),
        0x03,
        b'a',
        b'b',
        b'c',
        OpCode::Push1.byte(),
        OpCode::Right.byte(),
        OpCode::Stloc2.byte(),
        OpCode::Ret.byte(),
    ]);

    let high_level = decompile_high_level(&nef, None, true);
    assert!(
        high_level.contains("byte[] loc0"),
        "typed high-level output should annotate SUBSTR result as byte[]; got:\n{high_level}"
    );
    assert!(
        high_level.contains("byte[] loc1"),
        "typed high-level output should annotate LEFT result as byte[]; got:\n{high_level}"
    );
    assert!(
        high_level.contains("byte[] loc2"),
        "typed high-level output should annotate RIGHT result as byte[]; got:\n{high_level}"
    );

    let csharp = decompile_csharp(&nef, None, true);
    assert!(
        csharp.contains("ByteString loc0"),
        "typed C# output should annotate SUBSTR result as ByteString; got:\n{csharp}"
    );
    assert!(
        csharp.contains("ByteString loc1"),
        "typed C# output should annotate LEFT result as ByteString; got:\n{csharp}"
    );
    assert!(
        csharp.contains("ByteString loc2"),
        "typed C# output should annotate RIGHT result as ByteString; got:\n{csharp}"
    );
}

#[test]
fn typed_declarations_annotate_cat_arguments_and_result() {
    // INITSLOT 1 local, 2 args; LDARG0; LDARG1; CAT; STLOC0; RET.
    // CAT consumes ByteString-like operands and returns a ByteString-like value.
    let nef = build_nef(&[
        OpCode::Initslot.byte(),
        0x01,
        0x02,
        OpCode::Ldarg0.byte(),
        OpCode::Ldarg1.byte(),
        OpCode::Cat.byte(),
        OpCode::Stloc0.byte(),
        OpCode::Ret.byte(),
    ]);

    let high_level = decompile_high_level(&nef, None, true);
    assert!(
        high_level.contains("fn script_entry(arg0: byte[], arg1: byte[])"),
        "typed high-level output should annotate CAT argument constraints; got:\n{high_level}"
    );
    assert!(
        high_level.contains("byte[] loc0"),
        "typed high-level output should annotate CAT result as byte[]; got:\n{high_level}"
    );

    let csharp = decompile_csharp(&nef, None, true);
    assert!(
        csharp.contains("public static object ScriptEntry(ByteString arg0, ByteString arg1)"),
        "typed C# output should annotate CAT argument constraints; got:\n{csharp}"
    );
    assert!(
        csharp.contains("ByteString loc0"),
        "typed C# output should annotate CAT result as ByteString; got:\n{csharp}"
    );
}

#[test]
fn typed_declarations_produce_valid_empty_type_fallback() {
    // A typed declaration must never emit an empty type token (e.g. ` loc0 =`
    // with a leading double space) — unknowns fall back to `var`, not `""`.
    let (nef, manifest) = artifact("edgecases/LoopIf");
    let typed = decompile_csharp(&nef, manifest.as_deref(), true);
    assert!(
        !typed.contains("\n  loc0 =") && !typed.contains("var  loc0"),
        "typed output must not contain a malformed empty-type declaration"
    );
    // Temps (`tN`) are never in the slot map, so they must remain `var`.
    for line in typed.lines() {
        let t = line.trim();
        if t.starts_with("t0 ") || t.starts_with("t0=") {
            panic!("temp should not appear as a bare declaration: {t:?}");
        }
    }
}

#[test]
fn typed_declarations_off_matches_default() {
    // The flag-off path must be byte-identical to a Decompiler that never
    // touched the flag — guarantees the feature is purely additive.
    let (nef, manifest) = artifact("edgecases/LoopIf");
    let parsed_manifest =
        || ContractManifest::from_json_str(manifest.as_deref().unwrap_or("")).ok();
    let default_csharp = Decompiler::new()
        .decompile_bytes_with_manifest(&nef, parsed_manifest(), OutputFormat::CSharp)
        .unwrap()
        .csharp
        .unwrap_or_default();
    let csharp_off = decompile_csharp(&nef, manifest.as_deref(), false);
    assert_eq!(
        default_csharp, csharp_off,
        "with_typed_declarations(false) must equal default C# output"
    );

    let default_high_level = Decompiler::new()
        .decompile_bytes_with_manifest(&nef, parsed_manifest(), OutputFormat::HighLevel)
        .unwrap()
        .high_level
        .unwrap_or_default();
    let high_level_off = decompile_high_level(&nef, manifest.as_deref(), false);
    assert_eq!(
        default_high_level, high_level_off,
        "with_typed_declarations(false) must equal default high-level output"
    );
}