neo-decompiler 0.8.2

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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
use super::*;

#[test]
fn disassemble_bytes_returns_instruction_stream_without_rendering() {
    let nef_bytes = sample_nef();
    let output = Decompiler::new()
        .disassemble_bytes(&nef_bytes)
        .expect("disassembly succeeds");

    assert_eq!(output.instructions.len(), 4);
    assert!(output.warnings.is_empty());
    assert_eq!(output.instructions[0].offset, 0);
    assert_eq!(output.instructions[1].offset, 1);
}

#[test]
fn decompile_end_to_end() {
    let nef_bytes = sample_nef();
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    assert_eq!(decompilation.instructions.len(), 4);
    assert!(decompilation
        .pseudocode
        .as_deref()
        .expect("pseudocode output")
        .contains("ADD"));
    assert!(decompilation
        .high_level
        .as_deref()
        .expect("high-level output")
        .contains("contract NeoContract"));
    assert!(decompilation
        .high_level
        .as_deref()
        .expect("high-level output")
        .contains("fn script_entry()"));
}

#[test]
fn decompile_with_manifest_produces_contract_name() {
    let nef_bytes = sample_nef();
    let manifest = sample_manifest();
    let decompilation = Decompiler::new()
        .decompile_bytes_with_manifest(&nef_bytes, Some(manifest), OutputFormat::All)
        .expect("decompile succeeds with manifest");

    assert!(decompilation
        .high_level
        .as_deref()
        .expect("high-level output")
        .contains("contract ExampleContract"));
    assert!(decompilation
        .high_level
        .as_deref()
        .expect("high-level output")
        .contains("fn main() -> int {"));
}

#[test]
fn cfg_to_dot_includes_contract_name_and_script_hash_in_label() {
    // Multi-CFG dumps benefit from a graph-level label so each
    // canvas is self-identifying. Without manifest the title falls
    // back to script hash + instruction count; with manifest the
    // contract name is prepended.
    let nef_bytes = sample_nef();
    let manifest = sample_manifest();

    // With manifest: name + hash + count.
    let with = Decompiler::new()
        .decompile_bytes_with_manifest(&nef_bytes, Some(manifest), OutputFormat::Pseudocode)
        .expect("decompile with manifest");
    let dot_with = with.cfg_to_dot();
    assert!(dot_with.starts_with("digraph CFG {\n  label=\""));
    assert!(dot_with.contains("ExampleContract"), "{dot_with}");
    assert!(dot_with.contains("instr)"), "{dot_with}");
    assert!(dot_with.contains("labelloc=\"t\";"), "{dot_with}");

    // Without manifest: hash + count only (no contract name).
    let without = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile without manifest");
    let dot_without = without.cfg_to_dot();
    assert!(dot_without.contains("label=\""), "{dot_without}");
    assert!(!dot_without.contains("ExampleContract"), "{dot_without}");
    assert!(dot_without.contains("instr)"), "{dot_without}");
}

#[test]
fn decompile_lifts_indirect_calls_without_not_yet_translated_warning() {
    // Script: CALLA (no operand), CALLT 0x0001, RET
    let nef_bytes = build_nef(&[0x36, 0x37, 0x01, 0x00, 0x40]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");

    assert!(
        high_level.contains("calla("),
        "CALLA should be lifted to an indirect-call statement: {high_level}"
    );
    assert!(
        high_level.contains("callt(0x0001)"),
        "CALLT should be lifted to an indirect-call statement: {high_level}"
    );
    assert!(
        !high_level.contains("not yet translated"),
        "indirect calls should no longer emit not-yet-translated placeholders: {high_level}"
    );
}

#[test]
fn decompile_uses_method_token_signature_for_callt_arguments_and_returns() {
    // Script: PUSH1; CALLT 0x0000; RET
    // Token: foo(param_count=1, returns=false)
    let nef_bytes = build_nef_with_single_token(
        &[0x11, 0x37, 0x00, 0x00, 0x40],
        [0u8; 20],
        "foo",
        1,
        false,
        0x0F,
    );
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");
    assert!(
        high_level.contains("foo(t0);"),
        "CALLT should consume declared token argument and emit call expression: {high_level}"
    );
    assert!(
        !high_level.contains("let t1 = foo("),
        "CALLT token marked non-returning should not push a synthetic return temp: {high_level}"
    );
    assert!(
        high_level.contains("return;"),
        "script entry should end with a bare return after non-returning CALLT: {high_level}"
    );
}

#[test]
fn decompile_lifts_relative_calls_without_control_flow_warning() {
    // Script: CALL +2, CALL_L +5, RET
    let nef_bytes = build_nef(&[0x34, 0x02, 0x35, 0x05, 0x00, 0x00, 0x00, 0x40]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");

    assert!(
        high_level.contains("sub_0x0002()"),
        "CALL should resolve to inferred method name: {high_level}"
    );
    assert!(
        high_level.contains("sub_0x0007()"),
        "CALL_L should resolve to inferred method name: {high_level}"
    );
    assert!(
        !high_level.contains("control flow not yet lifted"),
        "relative calls should no longer use control-flow-not-lifted warnings: {high_level}"
    );
}

#[test]
fn decompile_resolves_relative_call_target_to_inferred_method_name() {
    // Script layout:
    // 0x0000: CALL +5  (target = 0x0005)
    // 0x0002: RET
    // 0x0003..0x0004: NOP padding
    // 0x0005: INITSLOT 0,0
    // 0x0008: RET
    let nef_bytes = build_nef(&[
        0x34, 0x05, // CALL +5
        0x40, // RET
        0x21, 0x21, // NOP x2
        0x57, 0x00, 0x00, // INITSLOT 0,0
        0x40, // RET
    ]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");

    assert!(
        high_level.contains("sub_0x0005()"),
        "relative CALL should use inferred callee name when target matches method start: {high_level}"
    );
}

#[test]
fn decompile_relative_call_passes_known_method_arguments() {
    // Script layout:
    // 0x0000: PUSH1
    // 0x0001: CALL +7  (target = 0x0008)
    // 0x0003: RET
    // 0x0004..0x0007: NOP padding
    // 0x0008: INITSLOT 0,1
    // 0x000B: LDARG0
    // 0x000C: RET
    let nef_bytes = build_nef(&[
        0x11, // PUSH1
        0x34, 0x07, // CALL +7
        0x40, // RET
        0x21, 0x21, 0x21, 0x21, // NOP x4
        0x57, 0x00, 0x01, // INITSLOT 0,1
        0x78, // LDARG0
        0x40, // RET
    ]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");
    assert!(
        high_level.contains("sub_0x0008("),
        "relative CALL should target inferred method call syntax: {high_level}"
    );
    assert!(
        !high_level.contains("sub_0x0008()"),
        "relative CALL into one-arg method should pass argument expression: {high_level}"
    );
}

#[test]
fn decompile_infers_entry_stack_argument_for_syscall_only_helper() {
    // Script layout:
    // 0x0000: PUSHDATA1 "x"
    // 0x0003: CALL +3 (target = 0x0006)
    // 0x0005: RET
    // 0x0006: SYSCALL System.Runtime.Log
    // 0x000B: RET
    let nef_bytes = build_nef(&[
        0x0C, 0x01, b'x', // PUSHDATA1 "x"
        0x34, 0x03, // CALL +3
        0x40, // RET
        0x41, 0xCF, 0xE7, 0x47, 0x96, // SYSCALL System.Runtime.Log
        0x40, // RET
    ]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");
    assert!(
        high_level.contains("fn sub_0x0006(arg0)"),
        "syscall-only helper should infer one entry-stack argument: {high_level}"
    );
    assert!(
        high_level.contains("syscall(\"System.Runtime.Log\", arg0)"),
        "syscall-only helper should consume inferred argument instead of ???: {high_level}"
    );
    assert!(
        !decompilation
            .warnings
            .iter()
            .any(|warning| warning
                .contains("missing syscall argument values for System.Runtime.Log")),
        "syscall-only helper should not emit missing-argument warnings: {:?}",
        decompilation.warnings
    );
}

#[test]
fn decompile_lifts_unconditional_jumps_without_control_flow_warning() {
    // Script: JMP +2 (to JMP_L), JMP_L +5 (to RET), RET
    let nef_bytes = build_nef(&[0x22, 0x02, 0x23, 0x05, 0x00, 0x00, 0x00, 0x40]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");

    // Fallthrough gotos (JMP to next instruction) are optimised away, and
    // the orphaned-label-removal pass strips the now-unreferenced label
    // anchors. The key guarantee is the absence of control-flow warnings.
    assert!(
        !high_level.contains("control flow not yet lifted"),
        "unconditional jumps should no longer emit control-flow-not-lifted warnings: {high_level}"
    );
    assert!(
        !high_level.contains("label_0x0002:"),
        "fallthrough JMP target should be removed as orphan: {high_level}"
    );
    assert!(
        !high_level.contains("label_0x0007:"),
        "fallthrough JMP_L target should be removed as orphan: {high_level}"
    );
}

#[test]
fn decompile_manifestless_entry_surfaces_initslot_args() {
    // INITSLOT 2 locals, 1 arg; LDARG0; STLOC0; LDLOC0; RET. Without a
    // manifest the entry method's signature should still surface the
    // INITSLOT-declared argument (`arg0`), so the body's `let loc0 =
    // arg0;` references a parameter that actually appears in the
    // signature — instead of the bare `fn script_entry()` Rust used to
    // emit. Stack-depth-only inference (no INITSLOT) still produces a
    // bare `fn script_entry()` so the missing-syscall-argument warning
    // remains visible.
    let script = [0x57, 0x02, 0x01, 0x78, 0x70, 0x68, 0x40];
    let nef_bytes = build_nef(&script);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");
    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");
    assert!(
        high_level.contains("fn script_entry(arg0)"),
        "manifest-less script_entry should expose INITSLOT-declared args: {high_level}"
    );
    assert!(
        high_level.contains("let loc0 = arg0;"),
        "body should reference the same arg label as the signature: {high_level}"
    );
}

#[test]
fn decompile_known_syscall_drops_redundant_hash_comment_in_clean_mode() {
    // Script: SYSCALL System.Runtime.GetTime, DROP, RET. The known syscall
    // is fully identified by its name in the call expression, so the
    // trailing `// 0x0388C3B7` comment is just noise — clean mode should
    // strip it. Trace mode keeps it as a debug aid.
    let script = [0x41, 0xB7, 0xC3, 0x88, 0x03, 0x75, 0x40];
    let nef_bytes = build_nef(&script);

    let trace = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds (trace)");
    let trace_high = trace
        .high_level
        .as_deref()
        .expect("high-level output (trace)");
    assert!(
        trace_high.contains("// 0x0388C3B7"),
        "trace mode should keep the syscall hash comment: {trace_high}"
    );

    let clean = Decompiler::new()
        .with_trace_comments(false)
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds (clean)");
    let clean_high = clean
        .high_level
        .as_deref()
        .expect("high-level output (clean)");
    assert!(
        !clean_high.contains("// 0x0388C3B7"),
        "clean mode should drop the redundant syscall hash comment: {clean_high}"
    );
    assert!(
        clean_high.contains("System.Runtime.GetTime"),
        "syscall name must still appear in the call expression: {clean_high}"
    );
}

#[test]
fn decompile_unknown_syscall_keeps_unknown_annotation() {
    // SYSCALL with an unrecognised hash — the `// warning: unknown
    // syscall 0xHASH` annotation is the only signal of the situation,
    // so it stays in every mode (cross-port parity with JS leading-
    // comment style; iteration 97 unified all warn() callers on this
    // prefix).
    let script = [0x41, 0xEF, 0xBE, 0xAD, 0xDE, 0x75, 0x40]; // 0xDEADBEEF
    let nef_bytes = build_nef(&script);

    for emit_trace in [true, false] {
        let decompilation = Decompiler::new()
            .with_trace_comments(emit_trace)
            .decompile_bytes(&nef_bytes)
            .expect("decompile succeeds");
        let high = decompilation
            .high_level
            .as_deref()
            .expect("high-level output");
        assert!(
            high.contains("// warning: unknown syscall 0xDEADBEEF"),
            "unknown-syscall annotation must always be emitted with the JS-style \
             `// warning:` prefix (trace={emit_trace}): {high}"
        );
        assert!(
            high.contains("0xDEADBEEF"),
            "unknown-syscall hash must appear in the call expression itself: {high}"
        );
        // The structured warnings array carries the same hazard so a
        // programmatic caller (CI, IDE integration) doesn't have to
        // grep the rendered source. Parity with the JS port.
        assert!(
            decompilation
                .warnings
                .iter()
                .any(|w| w.contains("unknown syscall 0xDEADBEEF")),
            "unknown-syscall warning must be surfaced via the warnings array (trace={emit_trace}): {:?}",
            decompilation.warnings,
        );
    }
}

#[test]
fn decompile_lifts_endtry_transfers_without_control_flow_warning() {
    // Script: ENDTRY +2 (to ENDTRY_L), ENDTRY_L +5 (to RET), RET
    let nef_bytes = build_nef(&[0x3D, 0x02, 0x3E, 0x05, 0x00, 0x00, 0x00, 0x40]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");

    // Both ENDTRYs target the immediately following instruction, so
    // `eliminate_fallthrough_gotos` collapses the `leave label_X;` lines
    // and `remove_orphaned_labels` strips the now-unreferenced anchors.
    // The key guarantee is the absence of control-flow warnings — and the
    // output should be clean, idiomatic high-level code with no dead
    // transfer plumbing.
    assert!(
        !high_level.contains("control flow not yet lifted"),
        "ENDTRY opcodes should no longer emit control-flow-not-lifted warnings: {high_level}"
    );
    assert!(
        !high_level.contains("leave label_"),
        "fallthrough ENDTRY transfers should be eliminated: {high_level}"
    );
    assert!(
        !high_level.contains("label_0x0002:"),
        "fallthrough ENDTRY target should be removed as orphan: {high_level}"
    );
    assert!(
        !high_level.contains("label_0x0007:"),
        "fallthrough ENDTRY_L target should be removed as orphan: {high_level}"
    );
    assert!(
        high_level.contains("return;"),
        "method body should still emit the trailing return: {high_level}"
    );
}

#[test]
fn decompile_uses_label_style_for_unresolved_jump_targets() {
    // Script: JMP +5 (to 0x0005, no decoded instruction there), RET
    let nef_bytes = build_nef(&[0x22, 0x05, 0x40]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");

    assert!(
        high_level.contains("goto label_0x0005;"),
        "unresolved jump target should still use label-style transfer naming: {high_level}"
    );
    assert!(
        !high_level.contains("goto_0x0005();"),
        "legacy function-style jump placeholder should not be emitted: {high_level}"
    );
}

#[test]
fn decompile_uses_label_style_for_unresolved_endtry_targets() {
    // Script: ENDTRY +5 (to 0x0005, no decoded instruction there), RET
    let nef_bytes = build_nef(&[0x3D, 0x05, 0x40]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");

    assert!(
        high_level.contains("leave label_0x0005;"),
        "unresolved endtry target should still use label-style transfer naming: {high_level}"
    );
    assert!(
        !high_level.contains("leave_0x0005();"),
        "legacy function-style endtry placeholder should not be emitted: {high_level}"
    );
}

#[test]
fn decompile_calla_with_stack_setup() {
    // Script: PUSH1 (push a value), PUSH0 (push pointer placeholder), CALLA, RET
    // Tests that CALLA consumes a pointer from the stack and emits an indirect call.
    let nef_bytes = build_nef(&[0x11, 0x10, 0x36, 0x40]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");
    assert!(
        high_level.contains("calla("),
        "CALLA should produce an indirect call expression: {high_level}"
    );
}

#[test]
fn decompile_resolves_pusha_calla_to_internal_call_placeholder() {
    // Script layout:
    // 0x0000: PUSHA +10  (target = 0x000A)
    // 0x0005: CALLA
    // 0x0006: RET
    // 0x0007..0x0009: NOP padding
    // 0x000A: INITSLOT 0,0
    // 0x000D: RET
    let nef_bytes = build_nef(&[
        0x0A, 0x0A, 0x00, 0x00, 0x00, // PUSHA +10
        0x36, // CALLA
        0x40, // RET
        0x21, 0x21, 0x21, // NOP x3
        0x57, 0x00, 0x00, // INITSLOT 0,0
        0x40, // RET
    ]);

    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");
    assert!(
        high_level.contains("sub_0x000A()"),
        "PUSHA+CALLA should resolve to the inferred method name when available: {high_level}"
    );
    assert!(
        !high_level.contains("calla("),
        "resolved PUSHA+CALLA should not remain as generic indirect call: {high_level}"
    );
}

#[test]
fn decompile_resolves_local_pointer_flow_into_calla() {
    // Script layout:
    // 0x0000: PUSHA +9  (target = 0x0009)
    // 0x0005: STLOC0
    // 0x0006: LDLOC0
    // 0x0007: CALLA
    // 0x0008: RET
    // 0x0009: INITSLOT 0,0
    // 0x000C: RET
    let nef_bytes = build_nef(&[
        0x0A, 0x09, 0x00, 0x00, 0x00, // PUSHA +9
        0x70, // STLOC0
        0x68, // LDLOC0
        0x36, // CALLA
        0x40, // RET
        0x57, 0x00, 0x00, // INITSLOT 0,0
        0x40, // RET
    ]);

    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");
    assert!(
        high_level.contains("sub_0x0009()"),
        "local pointer flow should resolve CALLA to inferred method name: {high_level}"
    );
    assert!(
        !high_level.contains("calla(loc0)"),
        "resolved local pointer flow should not remain generic CALLA: {high_level}"
    );
}

#[test]
fn decompile_resolves_static_pointer_flow_into_calla() {
    // Script layout:
    // 0x0000: PUSHA +9  (target = 0x0009)
    // 0x0005: STSFLD0
    // 0x0006: LDSFLD0
    // 0x0007: CALLA
    // 0x0008: RET
    // 0x0009: INITSLOT 0,0
    // 0x000C: RET
    let nef_bytes = build_nef(&[
        0x0A, 0x09, 0x00, 0x00, 0x00, // PUSHA +9
        0x60, // STSFLD0
        0x58, // LDSFLD0
        0x36, // CALLA
        0x40, // RET
        0x57, 0x00, 0x00, // INITSLOT 0,0
        0x40, // RET
    ]);

    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");
    assert!(
        high_level.contains("sub_0x0009()"),
        "static pointer flow should resolve CALLA to inferred method name: {high_level}"
    );
    assert!(
        !high_level.contains("calla(static0)"),
        "resolved static pointer flow should not remain generic CALLA: {high_level}"
    );
}

#[test]
fn decompile_multiple_sequential_calls() {
    // Script: CALL +2, CALL +0, RET, RET
    // Two sequential CALL instructions targeting different offsets.
    let nef_bytes = build_nef(&[0x34, 0x02, 0x34, 0x00, 0x40, 0x40]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");
    assert!(
        high_level.contains("sub_0x") || high_level.contains("call_"),
        "sequential CALL instructions should each produce a call expression: {high_level}"
    );
}

#[test]
fn decompile_nested_loop_in_if() {
    // Script layout (offsets in brackets):
    //   [0] PUSH0          -- condition for outer if
    //   [1] JMPIFNOT +8    -- target = 9 (RET), outer if
    //   [3] PUSH0          -- condition for while loop
    //   [4] JMPIFNOT +5    -- target = 9 (RET), loop exit
    //   [6] NOP            -- loop body
    //   [7] JMP -4         -- back-edge to [3]
    //   [9] RET
    let nef_bytes = build_nef(&[
        0x10, // PUSH0
        0x26, 0x08, // JMPIFNOT +8
        0x10, // PUSH0
        0x26, 0x05, // JMPIFNOT +5
        0x21, // NOP
        0x22, 0xFC, // JMP -4
        0x40, // RET
    ]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");

    assert!(
        high_level.contains("if"),
        "outer branch should produce an if block: {high_level}"
    );
    assert!(
        high_level.contains("while"),
        "inner loop should produce a while block: {high_level}"
    );
    assert!(
        !high_level.contains("not yet translated"),
        "nested loop-in-if should not emit not-yet-translated placeholders: {high_level}"
    );
}

#[test]
fn decompile_try_in_loop() {
    // Script layout (offsets in brackets):
    //   [0]  PUSH0            -- condition for while loop
    //   [1]  JMPIFNOT +12     -- target = 13 (RET), loop exit
    //   [3]  TRY (catch=+7, finally=0) -- catch at 10, no finally
    //   [6]  NOP              -- try body
    //   [7]  ENDTRY +6        -- leave to 13 (RET)
    //   [9]  NOP              -- padding
    //   [10] ENDFINALLY       -- catch handler
    //   [11] JMP -11          -- back-edge to [0]
    //   [13] RET
    let nef_bytes = build_nef(&[
        0x10, // PUSH0
        0x26, 0x0C, // JMPIFNOT +12
        0x3B, 0x07, 0x00, // TRY catch=+7, finally=0
        0x21, // NOP
        0x3D, 0x06, // ENDTRY +6
        0x21, // NOP
        0x3F, // ENDFINALLY
        0x22, 0xF5, // JMP -11
        0x40, // RET
    ]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");

    assert!(
        high_level.contains("try"),
        "try block should be emitted inside the loop: {high_level}"
    );
    assert!(
        high_level.contains("while") || high_level.contains("loop"),
        "enclosing loop should be recognized: {high_level}"
    );
}

#[test]
fn decompile_nested_if_else() {
    // Script layout (offsets in brackets):
    //   [0]  PUSH0          -- condition for outer if
    //   [1]  JMPIFNOT +10   -- target = 11 (RET), outer if
    //   [3]  PUSH0          -- condition for inner if
    //   [4]  JMPIFNOT +5    -- target = 9 (inner else body)
    //   [6]  NOP            -- inner if-true body
    //   [7]  JMP +4         -- skip inner else, target = 11 (RET)
    //   [9]  NOP            -- inner else body
    //   [10] NOP            -- padding
    //   [11] RET
    let nef_bytes = build_nef(&[
        0x10, // PUSH0
        0x26, 0x0A, // JMPIFNOT +10
        0x10, // PUSH0
        0x26, 0x05, // JMPIFNOT +5
        0x21, // NOP
        0x22, 0x04, // JMP +4
        0x21, // NOP
        0x21, // NOP
        0x40, // RET
    ]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");

    assert!(
        high_level.contains("if"),
        "nested if structure should be present: {high_level}"
    );
    assert!(
        high_level.contains("let t1"),
        "inner variable should still be present after empty-if removal: {high_level}"
    );
}

#[test]
fn decompile_all_comparison_jumps() {
    // Script layout: six comparison jumps (JMPEQ, JMPNE, JMPGT, JMPGE, JMPLT, JMPLE),
    // each preceded by PUSH0+PUSH1 to supply two stack operands, with a NOP filler
    // between each block. Each jump targets the next PUSH0 (or RET for the last).
    //
    //   [0]  PUSH0           [1]  PUSH1
    //   [2]  JMPEQ +1        target = 5
    //   [4]  NOP
    //   [5]  PUSH0           [6]  PUSH1
    //   [7]  JMPNE +1        target = 10
    //   [9]  NOP
    //   [10] PUSH0           [11] PUSH1
    //   [12] JMPGT +1        target = 15
    //   [14] NOP
    //   [15] PUSH0           [16] PUSH1
    //   [17] JMPGE +1        target = 20
    //   [19] NOP
    //   [20] PUSH0           [21] PUSH1
    //   [22] JMPLT +1        target = 25
    //   [24] NOP
    //   [25] PUSH0           [26] PUSH1
    //   [27] JMPLE +1        target = 30
    //   [29] NOP
    //   [30] RET
    let nef_bytes = build_nef(&[
        0x10, 0x11, 0x28, 0x01, 0x21, // PUSH0, PUSH1, JMPEQ +1, NOP
        0x10, 0x11, 0x2A, 0x01, 0x21, // PUSH0, PUSH1, JMPNE +1, NOP
        0x10, 0x11, 0x2C, 0x01, 0x21, // PUSH0, PUSH1, JMPGT +1, NOP
        0x10, 0x11, 0x2E, 0x01, 0x21, // PUSH0, PUSH1, JMPGE +1, NOP
        0x10, 0x11, 0x30, 0x01, 0x21, // PUSH0, PUSH1, JMPLT +1, NOP
        0x10, 0x11, 0x32, 0x01, 0x21, // PUSH0, PUSH1, JMPLE +1, NOP
        0x40, // RET
    ]);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");

    for op in ["==", "!=", ">", ">=", "<", "<="] {
        assert!(
            high_level.contains(op),
            "comparison operator {op} should appear in output: {high_level}"
        );
    }
    assert!(
        !high_level.contains("not yet translated"),
        "comparison jumps should not emit not-yet-translated placeholders: {high_level}"
    );
}

#[test]
fn packmap_pops_key_value_pairs_and_renders_entries() {
    // Script: PUSH4 ; PUSH3 ; PUSH2 ; PUSH1 ; PUSH2 (count) ; PACKMAP ; RET
    // PACKMAP pops 2n+1 items (OpCode.cs): count=2, then key=1, value=2,
    // key=3, value=4. The old code popped only n items, dropping half the
    // map and leaving stale entries on the simulated stack.
    let nef_bytes = build_nef(&[0x14, 0x13, 0x12, 0x11, 0x12, 0xBE, 0x40]);
    let decompilation = Decompiler::new()
        .with_inline_single_use_temps(true)
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");
    assert!(
        high_level.contains("Map(1: 2, 3: 4)"),
        "PACKMAP should render key/value pairs in pop order: {high_level}"
    );
}

#[test]
fn huge_pack_count_terminates_quickly() {
    // Script: PUSHINT64 i64::MAX ; PACK ; RET
    // The count literal is attacker-controlled; both the high-level
    // emitter and the type-inference pass must clamp their drain loops
    // (this hung at 100% CPU before the clamp in analysis/types.rs).
    let mut script = vec![0x03];
    script.extend_from_slice(&i64::MAX.to_le_bytes());
    script.extend_from_slice(&[0xC0, 0x40]); // PACK ; RET
    let nef_bytes = build_nef(&script);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds despite the pathological count");
    assert!(decompilation.high_level.is_some());
}

#[test]
fn huge_packmap_count_terminates_quickly() {
    let mut script = vec![0x03];
    script.extend_from_slice(&i64::MAX.to_le_bytes());
    script.extend_from_slice(&[0xBE, 0x40]); // PACKMAP ; RET
    let nef_bytes = build_nef(&script);
    let decompilation = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds despite the pathological count");
    assert!(decompilation.high_level.is_some());
}

#[test]
fn invalid_type_bytes_render_as_raw_hex() {
    // Script: PUSH1 ; NEWARRAY_T 0x99 ; DROP ; PUSH1 ; ISTYPE 0x99 ; RET
    // 0x99 is not a valid StackItemType: both fallbacks surface the raw
    // byte (uppercase hex) instead of dropping it or emitting an
    // unquoted `unknown` placeholder.
    let nef_bytes = build_nef(&[0x11, 0xC4, 0x99, 0x45, 0x11, 0xD9, 0x99, 0x40]);
    let decompilation = Decompiler::new()
        .with_inline_single_use_temps(true)
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");

    let high_level = decompilation
        .high_level
        .as_deref()
        .expect("high-level output");
    assert!(
        high_level.contains("new_array_t(1, 0x99)"),
        "NEWARRAY_T fallback should keep the raw type byte: {high_level}"
    );
    assert!(
        high_level.contains("is_type(1, 0x99)"),
        "ISTYPE fallback should keep the raw type byte: {high_level}"
    );
}

#[test]
fn oversized_method_hits_high_level_lifting_cap() {
    // A method with more instructions than the high-level lifting cap must fall
    // back to a note instead of running the worst-case O(n²) lift passes — a
    // crafted in-cap NEF (many crossing jumps) would otherwise hang the
    // decompiler. The disassembly remains available separately.
    let mut script = Vec::new();
    for _ in 0..20_000 {
        script.extend_from_slice(&[0x11, 0x24, 0x05]); // PUSH1 ; JMPIF +5 (crossing)
    }
    script.push(0x40); // RET
    let nef_bytes = build_nef(&script);
    let result = Decompiler::new()
        .decompile_bytes(&nef_bytes)
        .expect("decompile succeeds");
    let high_level = result.high_level.as_deref().expect("high-level output");
    assert!(
        high_level.contains("too large for high-level lifting"),
        "oversized method should fall back to the cap note: {high_level}"
    );
    assert!(
        result
            .warnings
            .iter()
            .any(|warning| warning.contains("exceeds the high-level lifting limit")),
        "should surface a skip warning: {:?}",
        result.warnings
    );
}