neo-devpack-solidity 0.22.0

Production-focused Solidity-to-NeoVM compilation system
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
// Software 256-bit UNSIGNED routines emitted as NeoVM bytecode (#12).
//
// NeoVM integers are signed two's-complement, capped at 32 bytes
// (`[-2^255, 2^255-1]`). Solidity `uint256` values in `[2^255, 2^256-1]` are
// represented as their 32-byte two's-complement (value mod 2^256, which "looks
// negative"). These routines compute the correct UNSIGNED result using only
// <=32-byte operations, so they run on a real Neo node.
//
// Each routine is validated below against a FAITHFUL reference VM (signed
// two's-complement, 32-byte limit) — the production runtime simulator currently
// uses an unsigned-magnitude representation and cannot validate them (see
// `claudedocs/uint256-conformance-plan.md`). Wiring the routines into the binary
// lowering, flipping the simulator to two's-complement, and migrating the test
// suite is the remaining coordinated change.

/// PUSHINT256 of a 32-byte little-endian value.
#[allow(dead_code)]
fn emit_pushint256_le(out: &mut Vec<u8>, le: &[u8; 32]) {
    out.push(0x05);
    out.extend_from_slice(le);
}

/// 32-byte little-endian encoding of `2^255` (the sign bit). As a signed NeoVM
/// integer this is `INT256_MIN`; XOR-ing flips bit 255, mapping unsigned order to
/// signed order.
#[allow(dead_code)]
const SIGN_BIT_LE: [u8; 32] = {
    let mut b = [0u8; 32];
    b[31] = 0x80;
    b
};

/// Emit unsigned `a < b` for operands on the stack as `[.., a, b]`.
/// `a <u b  <=>  (a ^ 2^255) <s (b ^ 2^255)`. All operations stay <= 32 bytes.
#[allow(dead_code)]
fn emit_uint256_unsigned_lt(out: &mut Vec<u8>) {
    emit_pushint256_le(out, &SIGN_BIT_LE);
    out.push(0x93); // XOR  -> [a, b^SIGN]
    out.push(0x50); // SWAP -> [b^SIGN, a]
    emit_pushint256_le(out, &SIGN_BIT_LE);
    out.push(0x93); // XOR  -> [b^SIGN, a^SIGN]
    out.push(0x50); // SWAP -> [a^SIGN, b^SIGN]
    out.push(0xB5); // LT   -> a^SIGN <s b^SIGN  ==  a <u b
}

/// Emit unsigned `a > b` for operands `[.., a, b]`.
#[allow(dead_code)]
fn emit_uint256_unsigned_gt(out: &mut Vec<u8>) {
    emit_pushint256_le(out, &SIGN_BIT_LE);
    out.push(0x93); // XOR  -> [a, b^SIGN]
    out.push(0x50); // SWAP -> [b^SIGN, a]
    emit_pushint256_le(out, &SIGN_BIT_LE);
    out.push(0x93); // XOR  -> [b^SIGN, a^SIGN]
    out.push(0x50); // SWAP -> [a^SIGN, b^SIGN]
    out.push(0xB7); // GT   -> a^SIGN >s b^SIGN  ==  a >u b
}

/// Emit unsigned `a <= b` for operands `[.., a, b]`.
#[allow(dead_code)]
fn emit_uint256_unsigned_le(out: &mut Vec<u8>) {
    emit_pushint256_le(out, &SIGN_BIT_LE);
    out.push(0x93); // XOR
    out.push(0x50); // SWAP
    emit_pushint256_le(out, &SIGN_BIT_LE);
    out.push(0x93); // XOR
    out.push(0x50); // SWAP -> [a^SIGN, b^SIGN]
    out.push(0xB6); // LE   -> a^SIGN <=s b^SIGN  ==  a <=u b
}

/// Emit unsigned `a >= b` for operands `[.., a, b]`.
#[allow(dead_code)]
fn emit_uint256_unsigned_ge(out: &mut Vec<u8>) {
    emit_pushint256_le(out, &SIGN_BIT_LE);
    out.push(0x93); // XOR
    out.push(0x50); // SWAP
    emit_pushint256_le(out, &SIGN_BIT_LE);
    out.push(0x93); // XOR
    out.push(0x50); // SWAP -> [a^SIGN, b^SIGN]
    out.push(0xB8); // GE   -> a^SIGN >=s b^SIGN  ==  a >=u b
}

/// 32-byte LE of `2^128 - 1` (low 128 bits set) — a POSITIVE 256-bit mask
/// (pushed via PUSHINT256 so it is not the negative int128 `-1`).
#[allow(dead_code)]
const MASK128_LE: [u8; 32] = {
    let mut b = [0u8; 32];
    let mut i = 0;
    while i < 16 {
        b[i] = 0xFF;
        i += 1;
    }
    b
};

/// 32-byte LE of `2^127` (bit 127 set) — the int128 sign bias.
#[allow(dead_code)]
const BIAS127_LE: [u8; 32] = {
    let mut b = [0u8; 32];
    b[15] = 0x80;
    b
};

/// 32-byte LE of `2^255 - 1` (`INT256_MAX`, all bits set except the sign bit) —
/// AND-ing clears bit 255, turning an arithmetic right shift into a logical one.
#[allow(dead_code)]
const MAX_INT256_LE: [u8; 32] = {
    let mut b = [0xFFu8; 32];
    b[31] = 0x7F;
    b
};

/// Emit a LOGICAL `a >>u n` for uint256 operands `[.., a, n]` (`n` in [0, 256]).
/// Native NeoVM `SHR` is arithmetic (sign-extending), so for values >= 2^255 it
/// would propagate the high bit. Identity used:
///   `n == 0`        -> a
///   `n >= 1`        -> logical_shr_1(a) >>arith (n-1)
/// where `logical_shr_1(a) = (a >>arith 1) & (2^255-1)` is non-negative, so a
/// subsequent arithmetic shift behaves logically. Every value stays <= 32 bytes.
#[allow(dead_code)]
fn emit_uint256_logical_shr(out: &mut Vec<u8>) {
    out.push(0x57); // INITSLOT
    out.push(0x02);
    out.push(0x00);
    out.push(0x71); // STLOC1 (n)
    out.push(0x70); // STLOC0 (a)
    emit_ldloc(out, 1); // n
    out.push(0x26); // JMPIFNOT -> n == 0 path
    let jmpifnot_operand = out.len();
    out.push(0x00);
    // n >= 1: logical_shr_1(a) >> (n - 1)
    emit_ldloc(out, 0); // a
    out.push(0x11); // PUSH1
    out.push(0xA9); // SHR  (a >>arith 1)
    emit_pushint256_le(out, &MAX_INT256_LE);
    out.push(0x91); // AND  -> logical_shr_1(a)  (>= 0)
    emit_ldloc(out, 1); // n
    out.push(0x11); // PUSH1
    out.push(0x9F); // SUB  -> n - 1
    out.push(0xA9); // SHR  -> result
    out.push(0x22); // JMP -> end
    let jmp_operand = out.len();
    out.push(0x00);
    let zero_pos = out.len();
    emit_ldloc(out, 0); // a  (n == 0 -> result = a)
    let end_pos = out.len();
    out[jmpifnot_operand] = ((zero_pos as isize) - (jmpifnot_operand as isize - 1)) as i8 as u8;
    out[jmp_operand] = ((end_pos as isize) - (jmp_operand as isize - 1)) as i8 as u8;
}

/// Emit `a << n mod 2^256` for uint256 operands `[.., a, n]` (`n` in [0, 256]).
/// Native NeoVM `SHL` does not wrap, so `1 << 255` (= 2^255) would form a 33-byte
/// positive integer a real node rejects. Work on two 128-bit limbs, and mask
/// each limb to its low `128-k` bits *before* shifting (`m = M128 >>arith k`),
/// so no pre-mask intermediate exceeds 128 bits:
///   k < 128:  lo' = (lo & m) << k                       (m = 2^(128-k)-1)
///             hi' = ((hi & m) << k) | (lo >> (128-k))
///   k >= 128: lo' = 0 ; hi' = (lo & (M128 >> (k-128))) << (k-128)
///   result = sign_ext128(hi') << 128 + lo'
#[allow(dead_code)]
fn emit_uint256_shl(out: &mut Vec<u8>) {
    out.push(0x57); // INITSLOT
    out.push(0x05); // a(0), n(1), lo(2), hi(3), mask(4)
    out.push(0x00);
    out.push(0x71); // STLOC1 (n)
    out.push(0x70); // STLOC0 (a)
    // lo = a & M128
    emit_ldloc(out, 0);
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    emit_stloc(out, 2);
    // hi = (a >> 128) & M128
    emit_ldloc(out, 0);
    emit_push_u8(out, 128);
    out.push(0xA9); // SHR
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    emit_stloc(out, 3);
    // branch: n >= 128 ?
    emit_ldloc(out, 1);
    emit_push_u8(out, 128);
    out.push(0xB8); // GE
    out.push(0x24); // JMPIF -> big
    let jmpif_big = out.len();
    out.push(0x00);
    // --- n < 128 ---
    // mask = M128 >> n  (= 2^(128-n)-1)
    emit_pushint256_le(out, &MASK128_LE);
    emit_ldloc(out, 1);
    out.push(0xA9); // SHR
    emit_stloc(out, 4);
    // lo' = (lo & mask) << n
    emit_ldloc(out, 2);
    emit_ldloc(out, 4);
    out.push(0x91); // AND
    emit_ldloc(out, 1);
    out.push(0xA8); // SHL
    // hi' = ((hi & mask) << n) | (lo >> (128 - n))
    emit_ldloc(out, 3);
    emit_ldloc(out, 4);
    out.push(0x91); // AND
    emit_ldloc(out, 1);
    out.push(0xA8); // SHL
    emit_ldloc(out, 2);
    emit_push_u8(out, 128);
    emit_ldloc(out, 1);
    out.push(0x9F); // SUB -> 128 - n
    out.push(0xA9); // SHR -> lo >> (128 - n)
    out.push(0x92); // OR -> hi'
    out.push(0x22); // JMP -> build
    let jmp_build = out.len();
    out.push(0x00);
    // --- n >= 128 ---
    let big_pos = out.len();
    // mask = M128 >> (n - 128)
    emit_pushint256_le(out, &MASK128_LE);
    emit_ldloc(out, 1);
    emit_push_u8(out, 128);
    out.push(0x9F); // SUB -> n - 128
    out.push(0xA9); // SHR
    emit_stloc(out, 4);
    out.push(0x10); // PUSH0 -> lo' = 0
    // hi' = (lo & mask) << (n - 128)
    emit_ldloc(out, 2);
    emit_ldloc(out, 4);
    out.push(0x91); // AND
    emit_ldloc(out, 1);
    emit_push_u8(out, 128);
    out.push(0x9F); // SUB -> n - 128
    out.push(0xA8); // SHL
    // --- build: stack [lo', hi'] -> sign_ext128(hi') << 128 + lo' ---
    let build_pos = out.len();
    emit_pushint256_le(out, &BIAS127_LE);
    out.push(0x93); // XOR
    emit_pushint256_le(out, &BIAS127_LE);
    out.push(0x9F); // SUB
    emit_push_u8(out, 128);
    out.push(0xA8); // SHL
    out.push(0x9E); // ADD -> result
    out[jmpif_big] = ((big_pos as isize) - (jmpif_big as isize - 1)) as i8 as u8;
    out[jmp_build] = ((build_pos as isize) - (jmp_build as isize - 1)) as i8 as u8;
}

/// 32-byte LE of `2^64 - 1` (low 64 bits set) — a POSITIVE 256-bit mask used to
/// extract 64-bit limbs for the software multiply.
#[allow(dead_code)]
const MASK64_LE: [u8; 32] = {
    let mut b = [0u8; 32];
    let mut i = 0;
    while i < 8 {
        b[i] = 0xFF;
        i += 1;
    }
    b
};

/// Emit `LDLOC i` (short form for `i <= 6`, else the generic 1-byte-operand form).
#[allow(dead_code)]
fn emit_ldloc(out: &mut Vec<u8>, i: u8) {
    if i <= 6 {
        out.push(0x68 + i); // LDLOC0..LDLOC6
    } else {
        out.push(0x6F); // LDLOC
        out.push(i);
    }
}

/// Emit `STLOC i` (short form for `i <= 6`, else the generic 1-byte-operand form).
#[allow(dead_code)]
fn emit_stloc(out: &mut Vec<u8>, i: u8) {
    if i <= 6 {
        out.push(0x70 + i); // STLOC0..STLOC6
    } else {
        out.push(0x77); // STLOC
        out.push(i);
    }
}

/// Push a small non-negative integer (a shift count) as a POSITIVE NeoVM
/// integer. PUSHINT8 is signed, so values `>= 128` (e.g. a 128-bit shift) must
/// use PUSHINT16, otherwise `0x80` would decode to `-128`.
#[allow(dead_code)]
fn emit_push_u8(out: &mut Vec<u8>, n: u8) {
    if n <= 0x7F {
        out.push(0x00); // PUSHINT8
        out.push(n);
    } else {
        out.push(0x01); // PUSHINT16 (keeps the value positive)
        out.extend_from_slice(&i16::from(n).to_le_bytes());
    }
}

/// Emit `a + b mod 2^256` (UNCHECKED) for operands `[.., a, b]`, on the 32-byte
/// two's-complement representation, using 128-bit limbs so no intermediate ever
/// exceeds 32 bytes (a native `ADD` of two large uint256 values would otherwise
/// produce a 33-byte result that a real Neo node rejects).
///
///   lo = (a & M128) + (b & M128)                         // <= 2^129
///   hi = (a>>128 & M128) + (b>>128 & M128) + (lo>>128)   // <= 2^129
///   result = sign_ext128(hi & M128) << 128  +  (lo & M128)
/// where `sign_ext128(x) = (x ^ 2^127) - 2^127` keeps the high limb in
/// `[-2^127, 2^127)` so the final value lands in `[-2^255, 2^255-1]` (<= 32 bytes).
#[allow(dead_code)]
fn emit_uint256_unchecked_add(out: &mut Vec<u8>) {
    out.push(0x57); // INITSLOT
    out.push(0x03); // 3 locals
    out.push(0x00); // 0 params
    emit_add_limb_prologue(out); // lo = (a&M128)+(b&M128) -> local 2
    emit_add_full_hi(out); // hi = ah + bh + carry  (full, on stack)
    emit_add_result_epilogue(out); // sign_ext128(hi & M128) << 128 + (lo & M128)
}

/// Emit `a - b mod 2^256` (UNCHECKED) for operands `[.., a, b]`. Mirrors the add
/// routine with a borrow: the low-limb difference can go negative, and its
/// arithmetic right shift by 128 yields `-1` (borrow) or `0`, which is folded
/// straight into the high limb.
///
///   lo = (a & M128) - (b & M128)                         // in (-2^128, 2^128)
///   hi = (a>>128 & M128) - (b>>128 & M128) + (lo>>128)   // (lo>>128) = -borrow
///   result = sign_ext128(hi & M128) << 128  +  (lo & M128)
#[allow(dead_code)]
fn emit_uint256_unchecked_sub(out: &mut Vec<u8>) {
    out.push(0x57); // INITSLOT
    out.push(0x03); // 3 locals
    out.push(0x00); // 0 params
    out.push(0x71); // STLOC1  (b)
    out.push(0x70); // STLOC0  (a)
    // lo = (a & M128) - (b & M128)
    out.push(0x68); // LDLOC0
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x69); // LDLOC1
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x9F); // SUB
    out.push(0x72); // STLOC2  (lo)
    // hi = (a>>128 & M128) - (b>>128 & M128) + (lo>>128)
    out.push(0x68); // LDLOC0
    emit_push_u8(out, 128);
    out.push(0xA9); // SHR
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x69); // LDLOC1
    emit_push_u8(out, 128);
    out.push(0xA9); // SHR
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x9F); // SUB
    out.push(0x6A); // LDLOC2 (lo)
    emit_push_u8(out, 128);
    out.push(0xA9); // SHR  (lo>>128 = -borrow, in {-1, 0})
    out.push(0x9E); // ADD  -> hi
    // hi_signed = sign_ext128(hi & M128)
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    emit_pushint256_le(out, &BIAS127_LE);
    out.push(0x93); // XOR
    emit_pushint256_le(out, &BIAS127_LE);
    out.push(0x9F); // SUB  -> hi_signed
    // result = (hi_signed << 128) + (lo & M128)
    emit_push_u8(out, 128);
    out.push(0xA8); // SHL
    out.push(0x6A); // LDLOC2 (lo)
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x9E); // ADD  -> result
}

/// Emit the limb prologue shared by the add routines: store `b`,`a` into
/// locals 1,0 and compute `lo = (a&M128)+(b&M128)` into local 2, leaving the
/// stack empty. Assumes the caller has already emitted `INITSLOT 3 0`.
#[allow(dead_code)]
fn emit_add_limb_prologue(out: &mut Vec<u8>) {
    out.push(0x71); // STLOC1 (b)
    out.push(0x70); // STLOC0 (a)
    out.push(0x68); // LDLOC0
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x69); // LDLOC1
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x9E); // ADD
    out.push(0x72); // STLOC2 (lo)
}

/// Emit, onto the stack, the FULL (unmasked) high limb
/// `hi = (a>>128 & M128) + (b>>128 & M128) + (lo>>128)` in `[0, 2^129-1]`.
/// `hi >> 128` is the carry-out of bit 256 (0 or 1).
#[allow(dead_code)]
fn emit_add_full_hi(out: &mut Vec<u8>) {
    out.push(0x68); // LDLOC0
    emit_push_u8(out, 128);
    out.push(0xA9); // SHR
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x69); // LDLOC1
    emit_push_u8(out, 128);
    out.push(0xA9); // SHR
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x9E); // ADD
    out.push(0x6A); // LDLOC2 (lo)
    emit_push_u8(out, 128);
    out.push(0xA9); // SHR  (carry from lo)
    out.push(0x9E); // ADD  -> hi (full)
}

/// Emit the epilogue that turns a FULL high limb `hi` (top of stack) plus the
/// stored `lo` (local 2) into the 32-byte two's-complement result:
/// `result = sign_ext128(hi & M128) << 128 + (lo & M128)`.
#[allow(dead_code)]
fn emit_add_result_epilogue(out: &mut Vec<u8>) {
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    emit_pushint256_le(out, &BIAS127_LE);
    out.push(0x93); // XOR
    emit_pushint256_le(out, &BIAS127_LE);
    out.push(0x9F); // SUB  -> sign_ext128(hi & M128)
    emit_push_u8(out, 128);
    out.push(0xA8); // SHL
    out.push(0x6A); // LDLOC2 (lo)
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x9E); // ADD  -> result
}

/// Emit `a + b` with an UNSIGNED overflow check: if `a + b >= 2^256` (carry out
/// of bit 256), THROW (Solidity Panic 0x11). Operands `[.., a, b]`.
#[allow(dead_code)]
fn emit_uint256_checked_add(out: &mut Vec<u8>) {
    out.push(0x57); // INITSLOT
    out.push(0x03);
    out.push(0x00);
    emit_add_limb_prologue(out);
    emit_add_full_hi(out); // [hi]
    out.push(0x4A); // DUP -> [hi, hi]
    emit_push_u8(out, 128);
    out.push(0xA9); // SHR -> [hi, carry_out]  (0 or 1)
    out.push(0x24); // JMPIF -> throw if carry_out != 0
    let jmpif_operand = out.len();
    out.push(0x00); // placeholder offset
                    // no-overflow path: [hi]
    emit_add_result_epilogue(out);
    out.push(0x22); // JMP -> end (over the THROW)
    let jmp_operand = out.len();
    out.push(0x00); // placeholder
    let throw_pos = out.len();
    out.push(0x3A); // THROW (Panic 0x11 when wired in)
    let end_pos = out.len();
    // backpatch (offsets are relative to the jump opcode = operand_index - 1)
    out[jmpif_operand] = ((throw_pos as isize) - (jmpif_operand as isize - 1)) as i8 as u8;
    out[jmp_operand] = ((end_pos as isize) - (jmp_operand as isize - 1)) as i8 as u8;
}

/// Emit `a - b` with an UNSIGNED underflow check: if `a < b` (final borrow),
/// THROW (Solidity Panic 0x11). Operands `[.., a, b]`.
#[allow(dead_code)]
fn emit_uint256_checked_sub(out: &mut Vec<u8>) {
    out.push(0x57); // INITSLOT
    out.push(0x03);
    out.push(0x00);
    out.push(0x71); // STLOC1 (b)
    out.push(0x70); // STLOC0 (a)
    // lo = (a&M128) - (b&M128)
    out.push(0x68); // LDLOC0
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x69); // LDLOC1
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x9F); // SUB
    out.push(0x72); // STLOC2 (lo)
    // hi (full) = (a>>128 & M128) - (b>>128 & M128) + (lo>>128) ; in (-2^128, 2^128)
    out.push(0x68); // LDLOC0
    emit_push_u8(out, 128);
    out.push(0xA9); // SHR
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x69); // LDLOC1
    emit_push_u8(out, 128);
    out.push(0xA9); // SHR
    emit_pushint256_le(out, &MASK128_LE);
    out.push(0x91); // AND
    out.push(0x9F); // SUB
    out.push(0x6A); // LDLOC2 (lo)
    emit_push_u8(out, 128);
    out.push(0xA9); // SHR  (-borrow)
    out.push(0x9E); // ADD  -> hi (full)
    // underflow  <=>  hi < 0
    out.push(0x4A); // DUP -> [hi, hi]
    out.push(0x10); // PUSH0 -> [hi, hi, 0]
    out.push(0xB5); // LT -> [hi, (hi < 0)]
    out.push(0x24); // JMPIF -> throw if hi < 0
    let jmpif_operand = out.len();
    out.push(0x00);
    // no-underflow path: [hi]
    emit_add_result_epilogue(out);
    out.push(0x22); // JMP -> end
    let jmp_operand = out.len();
    out.push(0x00);
    let throw_pos = out.len();
    out.push(0x3A); // THROW
    let end_pos = out.len();
    out[jmpif_operand] = ((throw_pos as isize) - (jmpif_operand as isize - 1)) as i8 as u8;
    out[jmp_operand] = ((end_pos as isize) - (jmp_operand as isize - 1)) as i8 as u8;
}

/// Emit the shared multiply core. Consumes `[.., a, b]`, and using locals
/// (INITSLOT 15 0 must already be emitted) computes the 64-bit-limb schoolbook
/// low half: limbs `a0..a3` -> locals 0..3, `b0..b3` -> locals 4..7, result
/// limbs `r0..r3` -> locals 9..12, and the carry into column 4 -> local 8.
/// 64-bit limbs keep every partial product `< 2^128` and every column sum
/// `< 2^131`, so no intermediate exceeds NeoVM's 32-byte integer limit.
#[allow(dead_code)]
fn emit_mul_columns(out: &mut Vec<u8>) {
    const A: u8 = 13; // temp: a
    const B: u8 = 14; // temp: b
    emit_stloc(out, B);
    emit_stloc(out, A);
    // a_i = (a >> 64*i) & M64  -> local i
    for i in 0..4u8 {
        emit_ldloc(out, A);
        if i > 0 {
            emit_push_u8(out, 64 * i);
            out.push(0xA9); // SHR
        }
        emit_pushint256_le(out, &MASK64_LE);
        out.push(0x91); // AND
        emit_stloc(out, i);
    }
    // b_j = (b >> 64*j) & M64  -> local 4+j
    for j in 0..4u8 {
        emit_ldloc(out, B);
        if j > 0 {
            emit_push_u8(out, 64 * j);
            out.push(0xA9); // SHR
        }
        emit_pushint256_le(out, &MASK64_LE);
        out.push(0x91); // AND
        emit_stloc(out, 4 + j);
    }
    // acc = 0
    out.push(0x10); // PUSH0
    emit_stloc(out, 8);
    // columns 0..3: colsum = acc + sum_{i+j=k} a_i*b_j ; r_k = colsum&M64 ; acc = colsum>>64
    for k in 0..4u8 {
        emit_ldloc(out, 8); // acc
        for i in 0..=k {
            let j = k - i;
            emit_ldloc(out, i); // a_i
            emit_ldloc(out, 4 + j); // b_j
            out.push(0xA0); // MUL
            out.push(0x9E); // ADD
        }
        out.push(0x4A); // DUP colsum
        emit_pushint256_le(out, &MASK64_LE);
        out.push(0x91); // AND
        emit_stloc(out, 9 + k); // r_k
        emit_push_u8(out, 64);
        out.push(0xA9); // SHR
        emit_stloc(out, 8); // acc
    }
}

/// Emit, from `r0..r3` (locals 9..12), the 32-byte two's-complement result
/// `sign_ext128(r2 + (r3<<64)) << 128 + (r0 + (r1<<64))`. Reuses local 13.
#[allow(dead_code)]
fn emit_mul_build_result(out: &mut Vec<u8>) {
    // lo128 = r0 + (r1 << 64)  -> local 13
    emit_ldloc(out, 9);
    emit_ldloc(out, 10);
    emit_push_u8(out, 64);
    out.push(0xA8); // SHL
    out.push(0x9E); // ADD
    emit_stloc(out, 13);
    // hi128 = r2 + (r3 << 64)
    emit_ldloc(out, 11);
    emit_ldloc(out, 12);
    emit_push_u8(out, 64);
    out.push(0xA8); // SHL
    out.push(0x9E); // ADD
    // result = sign_ext128(hi128) << 128 + lo128
    emit_pushint256_le(out, &BIAS127_LE);
    out.push(0x93); // XOR
    emit_pushint256_le(out, &BIAS127_LE);
    out.push(0x9F); // SUB
    emit_push_u8(out, 128);
    out.push(0xA8); // SHL
    emit_ldloc(out, 13); // lo128
    out.push(0x9E); // ADD -> result
}

/// Emit `a * b mod 2^256` (UNCHECKED) for operands `[.., a, b]`.
#[allow(dead_code)]
fn emit_uint256_unchecked_mul(out: &mut Vec<u8>) {
    out.push(0x57); // INITSLOT
    out.push(15);
    out.push(0x00);
    emit_mul_columns(out);
    emit_mul_build_result(out);
}

/// Emit `a * b` with an UNSIGNED overflow check: if the product needs more than
/// 256 bits (any high-column term or the column-3 carry is non-zero), THROW.
/// All high terms are non-negative, so their sum is zero iff every one is zero.
#[allow(dead_code)]
fn emit_uint256_checked_mul(out: &mut Vec<u8>) {
    out.push(0x57); // INITSLOT
    out.push(15);
    out.push(0x00);
    emit_mul_columns(out);
    // high = acc + a1*b3 + a2*b2 + a3*b1 + a2*b3 + a3*b2 + a3*b3
    emit_ldloc(out, 8); // acc (carry into column 4)
    for (i, j) in [(1u8, 3u8), (2, 2), (3, 1), (2, 3), (3, 2), (3, 3)] {
        emit_ldloc(out, i);
        emit_ldloc(out, 4 + j);
        out.push(0xA0); // MUL
        out.push(0x9E); // ADD
    }
    out.push(0x24); // JMPIF -> throw if high != 0
    let jmpif_operand = out.len();
    out.push(0x00);
    emit_mul_build_result(out);
    out.push(0x22); // JMP -> end
    let jmp_operand = out.len();
    out.push(0x00);
    let throw_pos = out.len();
    out.push(0x3A); // THROW
    let end_pos = out.len();
    out[jmpif_operand] = ((throw_pos as isize) - (jmpif_operand as isize - 1)) as i8 as u8;
    out[jmp_operand] = ((end_pos as isize) - (jmp_operand as isize - 1)) as i8 as u8;
}

/// Patch a 4-byte relative operand (for CALL_L/JMP_L/etc.) at `operand_pos` so
/// the instruction (opcode at `operand_pos - 1`) targets absolute `target`.
#[allow(dead_code)]
fn patch_rel32(out: &mut [u8], operand_pos: usize, target: usize) {
    let opcode_pos = operand_pos as isize - 1;
    let off = (target as isize - opcode_pos) as i32;
    out[operand_pos..operand_pos + 4].copy_from_slice(&off.to_le_bytes());
}

/// Emit `JMP_L`/`JMPIF_L`/`JMPIFNOT_L`/`CALL_L` (opcode `op`) with a placeholder
/// 4-byte operand; returns the operand position for later [`patch_rel32`].
#[allow(dead_code)]
fn emit_branch_l_placeholder(out: &mut Vec<u8>, op: u8) -> usize {
    out.push(op);
    let pos = out.len();
    out.extend_from_slice(&[0u8; 4]);
    pos
}

/// Emit the body of unsigned `divmod`: consumes `[.., a, b]` and leaves
/// `[.., q, r]` with `q = a / b` and `r = a % b` (unsigned), THROWing a Solidity
/// panic when `b == 0`. Composes the limb-safe add/sub helpers via `CALL_L`
/// (native NeoVM DIV/MOD are signed, so they are only used on the reduced,
/// provably-non-negative operands). Algorithm (Hacker's Delight 9-3, adapted):
///   b >= 2^255:  q = (a >=u b) ? 1 : 0 ;  r = a - q*b
///   else:        m = a >>L 1 ;  t = m / b ;  rem = m % b
///                q0 = 2t ;  r = 2*rem + (a & 1)        (r in [0, 2b))
///                if r >=u b { q = q0 + 1 ; r = r - b } else q = q0
/// `2t`, `2*rem` and `r - b` use the helpers so no 33-byte intermediate forms.
/// Returns the operand positions of the `CALL_L add` and `CALL_L sub` sites so
/// a linker can point them at the helper functions.
#[allow(dead_code)]
fn emit_uint256_divmod_body(out: &mut Vec<u8>) -> (Vec<usize>, Vec<usize>) {
    let mut add_sites: Vec<usize> = Vec::new();
    let mut sub_sites: Vec<usize> = Vec::new();
    // locals: 0=a 1=b 2=q 3=r 4=m 5=t 6=rem
    out.push(0x57); // INITSLOT
    out.push(0x07);
    out.push(0x00);
    out.push(0x71); // STLOC1 (b)
    out.push(0x70); // STLOC0 (a)
    // b == 0 -> THROW (Panic 0x12, division by zero)
    emit_ldloc(out, 1);
    let jz = emit_branch_l_placeholder(out, 0x27); // JMPIFNOT_L -> divzero
                                                    // b >= 2^255  (signed b < 0) -> big-divisor branch
    emit_ldloc(out, 1);
    out.push(0x10); // PUSH0
    out.push(0xB5); // LT  -> (b < 0 signed) == (b >= 2^255 unsigned)
    let jbig = emit_branch_l_placeholder(out, 0x25); // JMPIF_L -> big_b

    // ---- small divisor: b < 2^255 ----
    // m = (a >>arith 1) & (2^255-1)   [logical shift right by 1]
    emit_ldloc(out, 0);
    out.push(0x11); // PUSH1
    out.push(0xA9); // SHR
    emit_pushint256_le(out, &MAX_INT256_LE);
    out.push(0x91); // AND
    emit_stloc(out, 4); // m
    // t = m / b ; rem = m % b   (m, b in [0, 2^255): signed == unsigned)
    emit_ldloc(out, 4);
    emit_ldloc(out, 1);
    out.push(0xA1); // DIV
    emit_stloc(out, 5); // t
    emit_ldloc(out, 4);
    emit_ldloc(out, 1);
    out.push(0xA2); // MOD
    emit_stloc(out, 6); // rem
    // q0 = 2t = add(t, t)
    emit_ldloc(out, 5);
    emit_ldloc(out, 5);
    add_sites.push(emit_branch_l_placeholder(out, 0x35)); // CALL_L add
    emit_stloc(out, 2); // q = q0
    // r = 2*rem + (a & 1) = add(rem, rem) then native ADD (safe: 2*rem is even)
    emit_ldloc(out, 6);
    emit_ldloc(out, 6);
    add_sites.push(emit_branch_l_placeholder(out, 0x35)); // CALL_L add
    emit_ldloc(out, 0);
    out.push(0x11); // PUSH1
    out.push(0x91); // AND -> a & 1
    out.push(0x9E); // ADD
    emit_stloc(out, 3); // r
    // if r >=u b: q = q+1 ; r = r - b
    emit_ldloc(out, 3);
    emit_ldloc(out, 1);
    emit_uint256_unsigned_ge(out); // inline (stack-only) -> (r >=u b)
    let jdone = emit_branch_l_placeholder(out, 0x27); // JMPIFNOT_L -> done
    emit_ldloc(out, 2);
    out.push(0x11); // PUSH1
    out.push(0x9E); // ADD  (q+1; safe: q0 even)
    emit_stloc(out, 2);
    emit_ldloc(out, 3);
    emit_ldloc(out, 1);
    sub_sites.push(emit_branch_l_placeholder(out, 0x35)); // CALL_L sub
    emit_stloc(out, 3);
    // done:
    let done_pos = out.len();
    patch_rel32(out, jdone, done_pos);
    emit_ldloc(out, 2); // q
    emit_ldloc(out, 3); // r
    out.push(0x40); // RET
    let end_small = out.len();

    // ---- big divisor: b >= 2^255 ----
    let big_pos = out.len();
    patch_rel32(out, jbig, big_pos);
    // q = (a >=u b) ? 1 : 0
    emit_ldloc(out, 0);
    emit_ldloc(out, 1);
    emit_uint256_unsigned_ge(out);
    emit_stloc(out, 2); // q (0 or 1)
    // r = q == 1 ? a - b : a
    emit_ldloc(out, 2);
    let jq0 = emit_branch_l_placeholder(out, 0x27); // JMPIFNOT_L -> q == 0
    emit_ldloc(out, 0);
    emit_ldloc(out, 1);
    sub_sites.push(emit_branch_l_placeholder(out, 0x35)); // CALL_L sub
    emit_stloc(out, 3); // r = a - b
    let jbdone = emit_branch_l_placeholder(out, 0x23); // JMP_L -> big_done
    let q0_pos = out.len();
    patch_rel32(out, jq0, q0_pos);
    emit_ldloc(out, 0);
    emit_stloc(out, 3); // r = a
    let big_done = out.len();
    patch_rel32(out, jbdone, big_done);
    emit_ldloc(out, 2); // q
    emit_ldloc(out, 3); // r
    out.push(0x40); // RET

    // divzero:
    let divzero = out.len();
    patch_rel32(out, jz, divzero);
    out.push(0x3A); // THROW
    let _ = end_small;
    (add_sites, sub_sites)
}

#[cfg(test)]
mod uint256_ops_tests {
    use super::*;
    use num_bigint::BigInt;

    fn modulus() -> BigInt {
        BigInt::from(1) << 256u32
    }

    /// 32-byte little-endian two's-complement encoding of a uint256 in [0, 2^256).
    fn u256_le(value: &BigInt) -> [u8; 32] {
        let m = modulus();
        let v: BigInt = ((value % &m) + &m) % &m;
        let signed: BigInt = if v >= (BigInt::from(1) << 255u32) { &v - &m } else { v };
        let bytes = signed.to_signed_bytes_le();
        let fill: u8 = if signed.sign() == num_bigint::Sign::Minus { 0xFF } else { 0x00 };
        let mut out = [fill; 32];
        out[..bytes.len()].copy_from_slice(&bytes);
        out
    }

    // ---- Faithful reference VM: signed two's-complement, 32-byte integer limit.
    // Models the subset of NeoVM opcodes the routines use, EXACTLY as a real node
    // would (no unsigned-magnitude masking). Returns Err on a >32-byte integer
    // result (the real VM's MaxIntegerSize fault).
    fn faithful_run(code: &[u8]) -> Result<Vec<BigInt>, String> {
        let mut stack: Vec<BigInt> = Vec::new();
        // Local-variable slots are per call frame; the evaluation `stack` is
        // shared across frames (NeoVM semantics). `frames` always holds the
        // current (top-level) frame; CALL pushes a new one, RET pops it.
        let mut frames: Vec<Vec<BigInt>> = vec![Vec::new()];
        let mut ret_stack: Vec<usize> = Vec::new();
        let mut ip = 0usize;
        let check = |v: BigInt| -> Result<BigInt, String> {
            if v.to_signed_bytes_le().len() > 32 {
                Err("integer exceeds 32 bytes".into())
            } else {
                Ok(v)
            }
        };
        while ip < code.len() {
            let op = code[ip];
            match op {
                0x05 => {
                    // PUSHINT256: 32-byte signed LE
                    let bytes = &code[ip + 1..ip + 33];
                    stack.push(BigInt::from_signed_bytes_le(bytes));
                    ip += 33;
                }
                0x93 => {
                    // XOR (bitwise two's-complement)
                    let b = stack.pop().ok_or("xor underflow")?;
                    let a = stack.pop().ok_or("xor underflow")?;
                    stack.push(check(a ^ b)?);
                    ip += 1;
                }
                0x50 => {
                    // SWAP
                    let n = stack.len();
                    if n < 2 {
                        return Err("swap underflow".into());
                    }
                    stack.swap(n - 1, n - 2);
                    ip += 1;
                }
                0xB5 => {
                    // LT: x1 < x2 (x2 popped first)
                    let x2 = stack.pop().ok_or("lt underflow")?;
                    let x1 = stack.pop().ok_or("lt underflow")?;
                    stack.push(BigInt::from(i32::from(x1 < x2)));
                    ip += 1;
                }
                0xB7 => {
                    // GT: x1 > x2
                    let x2 = stack.pop().ok_or("gt underflow")?;
                    let x1 = stack.pop().ok_or("gt underflow")?;
                    stack.push(BigInt::from(i32::from(x1 > x2)));
                    ip += 1;
                }
                0xB6 => {
                    // LE: x1 <= x2
                    let x2 = stack.pop().ok_or("le underflow")?;
                    let x1 = stack.pop().ok_or("le underflow")?;
                    stack.push(BigInt::from(i32::from(x1 <= x2)));
                    ip += 1;
                }
                0xB8 => {
                    // GE: x1 >= x2
                    let x2 = stack.pop().ok_or("ge underflow")?;
                    let x1 = stack.pop().ok_or("ge underflow")?;
                    stack.push(BigInt::from(i32::from(x1 >= x2)));
                    ip += 1;
                }
                0x00 => {
                    // PUSHINT8 (signed)
                    stack.push(BigInt::from(code[ip + 1] as i8));
                    ip += 2;
                }
                0x01 => {
                    // PUSHINT16 (signed LE)
                    let v = i16::from_le_bytes([code[ip + 1], code[ip + 2]]);
                    stack.push(BigInt::from(v));
                    ip += 3;
                }
                0x57 => {
                    // INITSLOT nlocals nparams
                    let nlocals = code[ip + 1] as usize;
                    *frames.last_mut().ok_or("no frame")? = vec![BigInt::from(0); nlocals];
                    ip += 3;
                }
                0x70..=0x76 => {
                    // STLOC0..STLOC6
                    let i = (op - 0x70) as usize;
                    let v = stack.pop().ok_or("stloc underflow")?;
                    frames.last_mut().ok_or("no frame")?[i] = v;
                    ip += 1;
                }
                0x77 => {
                    // STLOC (1-byte index)
                    let i = code[ip + 1] as usize;
                    let v = stack.pop().ok_or("stloc underflow")?;
                    frames.last_mut().ok_or("no frame")?[i] = v;
                    ip += 2;
                }
                0x68..=0x6E => {
                    // LDLOC0..LDLOC6
                    let i = (op - 0x68) as usize;
                    stack.push(frames.last().ok_or("no frame")?[i].clone());
                    ip += 1;
                }
                0x6F => {
                    // LDLOC (1-byte index)
                    let i = code[ip + 1] as usize;
                    stack.push(frames.last().ok_or("no frame")?[i].clone());
                    ip += 2;
                }
                0x91 => {
                    // AND
                    let b = stack.pop().ok_or("and underflow")?;
                    let a = stack.pop().ok_or("and underflow")?;
                    stack.push(check(a & b)?);
                    ip += 1;
                }
                0x92 => {
                    // OR
                    let b = stack.pop().ok_or("or underflow")?;
                    let a = stack.pop().ok_or("or underflow")?;
                    stack.push(check(a | b)?);
                    ip += 1;
                }
                0x9E => {
                    // ADD
                    let b = stack.pop().ok_or("add underflow")?;
                    let a = stack.pop().ok_or("add underflow")?;
                    stack.push(check(a + b)?);
                    ip += 1;
                }
                0x9F => {
                    // SUB
                    let b = stack.pop().ok_or("sub underflow")?;
                    let a = stack.pop().ok_or("sub underflow")?;
                    stack.push(check(a - b)?);
                    ip += 1;
                }
                0xA0 => {
                    // MUL
                    let b = stack.pop().ok_or("mul underflow")?;
                    let a = stack.pop().ok_or("mul underflow")?;
                    stack.push(check(a * b)?);
                    ip += 1;
                }
                0xA1 => {
                    // DIV (signed, truncating toward zero — Rust BigInt `/` matches)
                    let b = stack.pop().ok_or("div underflow")?;
                    let a = stack.pop().ok_or("div underflow")?;
                    if b == BigInt::from(0) {
                        return Err("DIV by zero".into());
                    }
                    stack.push(check(a / b)?);
                    ip += 1;
                }
                0xA2 => {
                    // MOD (signed, truncating — Rust BigInt `%` matches)
                    let b = stack.pop().ok_or("mod underflow")?;
                    let a = stack.pop().ok_or("mod underflow")?;
                    if b == BigInt::from(0) {
                        return Err("MOD by zero".into());
                    }
                    stack.push(check(a % b)?);
                    ip += 1;
                }
                0xA8 => {
                    // SHL: value << shift (shift popped first)
                    let shift = stack.pop().ok_or("shl underflow")?;
                    let value = stack.pop().ok_or("shl underflow")?;
                    let s: u64 = u64::try_from(shift).map_err(|_| "bad shift")?;
                    stack.push(check(value << s as usize)?);
                    ip += 1;
                }
                0xA9 => {
                    // SHR: value >> shift (arithmetic, two's-complement)
                    let shift = stack.pop().ok_or("shr underflow")?;
                    let value = stack.pop().ok_or("shr underflow")?;
                    let s: u64 = u64::try_from(shift).map_err(|_| "bad shift")?;
                    stack.push(check(value >> s as usize)?);
                    ip += 1;
                }
                0x10..=0x20 => {
                    // PUSH0..PUSH16
                    stack.push(BigInt::from(op - 0x10));
                    ip += 1;
                }
                0x4A => {
                    // DUP
                    let top = stack.last().cloned().ok_or("dup underflow")?;
                    stack.push(top);
                    ip += 1;
                }
                0x22 => {
                    // JMP rel8 (relative to the opcode position)
                    let off = code[ip + 1] as i8 as isize;
                    ip = (ip as isize + off) as usize;
                }
                0x23 => {
                    // JMP_L rel32
                    let off = i32::from_le_bytes(code[ip + 1..ip + 5].try_into().unwrap()) as isize;
                    ip = (ip as isize + off) as usize;
                }
                0x24 => {
                    // JMPIF rel8
                    let off = code[ip + 1] as i8 as isize;
                    let c = stack.pop().ok_or("jmpif underflow")?;
                    if c != BigInt::from(0) {
                        ip = (ip as isize + off) as usize;
                    } else {
                        ip += 2;
                    }
                }
                0x25 => {
                    // JMPIF_L rel32
                    let off = i32::from_le_bytes(code[ip + 1..ip + 5].try_into().unwrap()) as isize;
                    let c = stack.pop().ok_or("jmpif underflow")?;
                    if c != BigInt::from(0) {
                        ip = (ip as isize + off) as usize;
                    } else {
                        ip += 5;
                    }
                }
                0x26 => {
                    // JMPIFNOT rel8
                    let off = code[ip + 1] as i8 as isize;
                    let c = stack.pop().ok_or("jmpifnot underflow")?;
                    if c == BigInt::from(0) {
                        ip = (ip as isize + off) as usize;
                    } else {
                        ip += 2;
                    }
                }
                0x27 => {
                    // JMPIFNOT_L rel32
                    let off = i32::from_le_bytes(code[ip + 1..ip + 5].try_into().unwrap()) as isize;
                    let c = stack.pop().ok_or("jmpifnot underflow")?;
                    if c == BigInt::from(0) {
                        ip = (ip as isize + off) as usize;
                    } else {
                        ip += 5;
                    }
                }
                0x34 => {
                    // CALL rel8 (push return address + a fresh local frame)
                    let off = code[ip + 1] as i8 as isize;
                    ret_stack.push(ip + 2);
                    frames.push(Vec::new());
                    ip = (ip as isize + off) as usize;
                }
                0x35 => {
                    // CALL_L rel32
                    let off = i32::from_le_bytes(code[ip + 1..ip + 5].try_into().unwrap()) as isize;
                    ret_stack.push(ip + 5);
                    frames.push(Vec::new());
                    ip = (ip as isize + off) as usize;
                }
                0x3A => {
                    // THROW (used here to signal a Solidity Panic, e.g. overflow)
                    return Err("THROW".into());
                }
                0x40 => {
                    // RET: return to caller, or end the program at the top frame.
                    match ret_stack.pop() {
                        Some(r) => {
                            frames.pop();
                            ip = r;
                        }
                        None => break,
                    }
                }
                other => return Err(format!("faithful VM: unhandled opcode 0x{other:02x}")),
            }
        }
        Ok(stack)
    }

    fn run_lt(a: &BigInt, b: &BigInt) -> bool {
        let mut code = Vec::new();
        emit_pushint256_le(&mut code, &u256_le(a));
        emit_pushint256_le(&mut code, &u256_le(b));
        emit_uint256_unsigned_lt(&mut code);
        code.push(0x40);
        let st = faithful_run(&code).expect("faithful run");
        st.last().cloned().unwrap_or_else(|| BigInt::from(0)) != BigInt::from(0)
    }

    fn run_gt(a: &BigInt, b: &BigInt) -> bool {
        let mut code = Vec::new();
        emit_pushint256_le(&mut code, &u256_le(a));
        emit_pushint256_le(&mut code, &u256_le(b));
        emit_uint256_unsigned_gt(&mut code);
        code.push(0x40);
        let st = faithful_run(&code).expect("faithful run");
        st.last().cloned().unwrap_or_else(|| BigInt::from(0)) != BigInt::from(0)
    }

    fn big(s: &str) -> BigInt {
        BigInt::parse_bytes(s.as_bytes(), 10).unwrap()
    }
    fn pow2(n: u32) -> BigInt {
        BigInt::from(1) << n
    }
    fn umax() -> BigInt {
        modulus() - 1
    }

    #[test]
    fn faithful_vm_rejects_oversize_integers() {
        // Sanity: the reference VM faults on a >32-byte integer, like a real node.
        // (2^255-1) XOR (-(2^255)) stays <=32 bytes; but pushing then XOR of two
        // values whose result needs 33 bytes must error. Build 0x7F*32 (=2^255-1)
        // and verify no false fault, then confirm the checker rejects 33 bytes.
        let v = BigInt::from(1) << 256u32; // 2^256 needs 33 signed bytes
        assert!(v.to_signed_bytes_le().len() > 32);
    }

    #[test]
    fn unsigned_lt_small_values() {
        assert!(run_lt(&BigInt::from(5), &BigInt::from(10)));
        assert!(!run_lt(&BigInt::from(10), &BigInt::from(5)));
        assert!(!run_lt(&BigInt::from(7), &BigInt::from(7)));
        assert!(run_lt(&BigInt::from(0), &BigInt::from(1)));
    }

    #[test]
    fn unsigned_lt_large_values_above_2_255() {
        // The cases native signed comparison gets WRONG.
        assert!(run_lt(&BigInt::from(5), &umax()), "5 < uint256.max");
        assert!(!run_lt(&umax(), &BigInt::from(5)), "max not < 5");
        assert!(run_lt(&BigInt::from(0), &umax()), "0 < max");
        assert!(!run_lt(&umax(), &umax()), "max not < max");
        assert!(run_lt(&pow2(255), &(pow2(255) + 1)), "2^255 < 2^255+1");
        assert!(!run_lt(&(pow2(255) + 1), &pow2(255)));
        assert!(run_lt(&(pow2(255) - 1), &pow2(255)), "2^255-1 < 2^255 (straddle)");
        assert!(!run_lt(&pow2(255), &(pow2(255) - 1)));
        assert!(run_lt(
            &big("100"),
            &big("115792089237316195423570985008687907853269984665640564039457584007913129639000")
        ));
    }

    #[test]
    fn unsigned_gt_matches_lt() {
        assert!(run_gt(&umax(), &BigInt::from(5)), "max > 5");
        assert!(!run_gt(&BigInt::from(5), &umax()));
        assert!(run_gt(&pow2(255), &(pow2(255) - 1)));
        assert!(!run_gt(&BigInt::from(7), &BigInt::from(7)));
    }

    fn run_cmp(emit: fn(&mut Vec<u8>), a: &BigInt, b: &BigInt) -> bool {
        let mut code = Vec::new();
        emit_pushint256_le(&mut code, &u256_le(a));
        emit_pushint256_le(&mut code, &u256_le(b));
        emit(&mut code);
        code.push(0x40);
        let st = faithful_run(&code).expect("faithful run");
        st.last().cloned().unwrap_or_else(|| BigInt::from(0)) != BigInt::from(0)
    }

    /// Run the unchecked-add routine and return the result as an unsigned
    /// uint256 in [0, 2^256).
    fn run_add(a: &BigInt, b: &BigInt) -> BigInt {
        let mut code = Vec::new();
        emit_pushint256_le(&mut code, &u256_le(a));
        emit_pushint256_le(&mut code, &u256_le(b));
        emit_uint256_unchecked_add(&mut code);
        code.push(0x40);
        let st = faithful_run(&code).expect("faithful run");
        let signed = st.last().cloned().expect("result");
        let m = modulus();
        ((signed % &m) + &m) % &m
    }

    /// Run the unchecked-sub routine and return the result as an unsigned
    /// uint256 in [0, 2^256).
    fn run_sub(a: &BigInt, b: &BigInt) -> BigInt {
        let mut code = Vec::new();
        emit_pushint256_le(&mut code, &u256_le(a));
        emit_pushint256_le(&mut code, &u256_le(b));
        emit_uint256_unchecked_sub(&mut code);
        code.push(0x40);
        let st = faithful_run(&code).expect("faithful run");
        let signed = st.last().cloned().expect("result");
        let m = modulus();
        ((signed % &m) + &m) % &m
    }

    #[test]
    fn unchecked_sub_wraps_mod_2_256_including_large() {
        let m = modulus();
        let cases = [
            (BigInt::from(5), BigInt::from(3)),
            (BigInt::from(3), BigInt::from(5)),   // wraps to 2^256-2
            (BigInt::from(0), BigInt::from(1)),   // wraps to 2^256-1
            (umax(), umax()),                     // 0
            (umax(), BigInt::from(1)),            // 2^256-2
            (pow2(255), BigInt::from(1)),         // 2^255-1 (crosses sign)
            (pow2(255), pow2(255)),               // 0
            (pow2(128), BigInt::from(1)),         // borrow across limb boundary
            (BigInt::from(0), umax()),            // 1
            (pow2(200), pow2(199)),               // 2^199
        ];
        for (a, b) in cases {
            let expect = ((&a - &b) % &m + &m) % &m;
            assert_eq!(run_sub(&a, &b), expect, "sub({a}, {b})");
        }
    }

    #[test]
    fn unchecked_add_wraps_mod_2_256_including_large() {
        let m = modulus();
        let cases = [
            (BigInt::from(2), BigInt::from(3)),
            (BigInt::from(100), BigInt::from(200)),
            (umax(), BigInt::from(1)),            // wraps to 0
            (umax(), BigInt::from(2)),            // wraps to 1
            (pow2(255), pow2(255)),               // 2^256 -> 0
            (pow2(255) - 1, pow2(255) - 1),       // 2^256 - 2 (result >= 2^255)
            (pow2(128), pow2(128)),               // crosses the limb boundary
            (pow2(200) + 5, pow2(200) + 7),
            (umax(), umax()),                     // 2^257-2 mod 2^256 = 2^256-2
        ];
        for (a, b) in cases {
            let expect = ((&a + &b) % &m + &m) % &m;
            assert_eq!(run_add(&a, &b), expect, "add({a}, {b})");
        }
    }

    /// Run a checked routine; `Ok(value)` on success, `Err` if it threw (panic).
    fn run_checked(emit: fn(&mut Vec<u8>), a: &BigInt, b: &BigInt) -> Result<BigInt, String> {
        let mut code = Vec::new();
        emit_pushint256_le(&mut code, &u256_le(a));
        emit_pushint256_le(&mut code, &u256_le(b));
        emit(&mut code);
        code.push(0x40);
        let st = faithful_run(&code)?;
        let signed = st.last().cloned().ok_or("no result")?;
        let m = modulus();
        Ok(((signed % &m) + &m) % &m)
    }

    #[test]
    fn checked_add_detects_overflow() {
        // In range: matches the true sum.
        assert_eq!(run_checked(emit_uint256_checked_add, &big("2"), &big("3")), Ok(big("5")));
        assert_eq!(
            run_checked(emit_uint256_checked_add, &(pow2(255) - 1), &BigInt::from(1)),
            Ok(pow2(255)),
            "2^255-1 + 1 = 2^255 (still < 2^256)"
        );
        assert_eq!(
            run_checked(emit_uint256_checked_add, &(umax() - 1), &BigInt::from(1)),
            Ok(umax()),
            "max-1 + 1 = max"
        );
        // Overflow: a + b >= 2^256 must throw.
        assert!(run_checked(emit_uint256_checked_add, &umax(), &BigInt::from(1)).is_err());
        assert!(run_checked(emit_uint256_checked_add, &pow2(255), &pow2(255)).is_err());
        assert!(run_checked(emit_uint256_checked_add, &umax(), &umax()).is_err());
        assert!(run_checked(emit_uint256_checked_add, &(pow2(255) + 7), &pow2(255)).is_err());
    }

    #[test]
    fn checked_sub_detects_underflow() {
        // In range: a >= b.
        assert_eq!(run_checked(emit_uint256_checked_sub, &big("5"), &big("3")), Ok(big("2")));
        assert_eq!(run_checked(emit_uint256_checked_sub, &umax(), &umax()), Ok(big("0")));
        assert_eq!(
            run_checked(emit_uint256_checked_sub, &pow2(255), &BigInt::from(1)),
            Ok(pow2(255) - 1),
            "2^255 - 1 crosses the sign boundary"
        );
        assert_eq!(run_checked(emit_uint256_checked_sub, &umax(), &big("1")), Ok(umax() - 1));
        // Underflow: a < b must throw.
        assert!(run_checked(emit_uint256_checked_sub, &big("3"), &big("5")).is_err());
        assert!(run_checked(emit_uint256_checked_sub, &big("0"), &big("1")).is_err());
        assert!(run_checked(emit_uint256_checked_sub, &big("0"), &umax()).is_err());
        assert!(run_checked(emit_uint256_checked_sub, &(pow2(255) - 1), &pow2(255)).is_err());
    }

    /// Run the unchecked-mul routine; result as unsigned uint256 in [0, 2^256).
    fn run_mul(a: &BigInt, b: &BigInt) -> BigInt {
        let mut code = Vec::new();
        emit_pushint256_le(&mut code, &u256_le(a));
        emit_pushint256_le(&mut code, &u256_le(b));
        emit_uint256_unchecked_mul(&mut code);
        code.push(0x40);
        let st = faithful_run(&code).expect("faithful run");
        let signed = st.last().cloned().expect("result");
        let m = modulus();
        ((signed % &m) + &m) % &m
    }

    #[test]
    fn unchecked_mul_wraps_mod_2_256_including_large() {
        let m = modulus();
        let cases = [
            (BigInt::from(0), umax()),
            (BigInt::from(1), umax()),
            (BigInt::from(6), BigInt::from(7)),
            (pow2(64), pow2(64)),                 // 2^128 (limb boundary)
            (pow2(128), pow2(128)),               // 2^256 -> 0
            (pow2(200), pow2(100)),               // 2^300 mod 2^256 = 2^44
            (umax(), BigInt::from(2)),            // 2^257-2 mod 2^256 = 2^256-2
            (umax(), umax()),                     // (2^256-1)^2 mod 2^256 = 1
            (pow2(255), BigInt::from(3)),         // 3*2^255 mod 2^256 = 2^255
            (big("123456789012345678901234567890"), big("987654321098765432109876543210")),
            (pow2(130) + 7, pow2(130) + 9),
        ];
        for (a, b) in cases {
            let expect = (&a * &b) % &m;
            assert_eq!(run_mul(&a, &b), expect, "mul({a}, {b})");
        }
    }

    #[test]
    fn checked_mul_detects_overflow() {
        // In range (product < 2^256): exact value.
        assert_eq!(run_checked(emit_uint256_checked_mul, &big("6"), &big("7")), Ok(big("42")));
        assert_eq!(run_checked(emit_uint256_checked_mul, &umax(), &big("1")), Ok(umax()));
        assert_eq!(run_checked(emit_uint256_checked_mul, &big("0"), &umax()), Ok(big("0")));
        assert_eq!(
            run_checked(emit_uint256_checked_mul, &(pow2(255) - 1), &big("2")),
            Ok(pow2(256) - 2),
            "(2^255-1)*2 = 2^256-2 (still fits)"
        );
        assert_eq!(
            run_checked(emit_uint256_checked_mul, &pow2(128), &(pow2(128) - 1)),
            Ok(pow2(256) - pow2(128)),
            "2^128 * (2^128-1) = 2^256-2^128 (fits)"
        );
        // Overflow: product >= 2^256 must throw.
        assert!(run_checked(emit_uint256_checked_mul, &pow2(128), &pow2(128)).is_err());
        assert!(run_checked(emit_uint256_checked_mul, &pow2(255), &big("2")).is_err());
        assert!(run_checked(emit_uint256_checked_mul, &umax(), &big("2")).is_err());
        assert!(run_checked(emit_uint256_checked_mul, &umax(), &umax()).is_err());
        assert!(run_checked(emit_uint256_checked_mul, &(pow2(200)), &(pow2(100))).is_err());
    }

    /// Run the logical-shr routine; result as unsigned uint256 in [0, 2^256).
    fn run_shr(a: &BigInt, n: u32) -> BigInt {
        let mut code = Vec::new();
        emit_pushint256_le(&mut code, &u256_le(a));
        emit_pushint256_le(&mut code, &u256_le(&BigInt::from(n)));
        emit_uint256_logical_shr(&mut code);
        code.push(0x40);
        let st = faithful_run(&code).expect("faithful run");
        let signed = st.last().cloned().expect("result");
        let m = modulus();
        ((signed % &m) + &m) % &m
    }

    /// Run the shl routine; result as unsigned uint256 in [0, 2^256).
    fn run_shl(a: &BigInt, n: u32) -> BigInt {
        let mut code = Vec::new();
        emit_pushint256_le(&mut code, &u256_le(a));
        emit_pushint256_le(&mut code, &u256_le(&BigInt::from(n)));
        emit_uint256_shl(&mut code);
        code.push(0x40);
        let st = faithful_run(&code).expect("faithful run");
        let signed = st.last().cloned().expect("result");
        let m = modulus();
        ((signed % &m) + &m) % &m
    }

    #[test]
    fn shl_wraps_mod_2_256_including_large() {
        let m = modulus();
        let cases: [(BigInt, u32); 13] = [
            (BigInt::from(1), 0),
            (BigInt::from(1), 1),
            (BigInt::from(1), 127),
            (BigInt::from(1), 128),
            (BigInt::from(1), 255),        // 2^255 — faults under native SHL today
            (BigInt::from(3), 255),        // (3<<255) mod 2^256 = 2^255
            (umax(), 1),                   // 2^256-2
            (umax(), 128),
            (umax(), 255),                 // 2^255
            (pow2(100), 100),              // 2^200
            (pow2(100), 200),              // 2^300 mod 2^256 = 2^44
            (big("123456789012345678901234567890"), 64),
            (pow2(200) + BigInt::from(7), 60),
        ];
        for (a, n) in cases {
            let expect = ((&a << n) % &m + &m) % &m;
            assert_eq!(run_shl(&a, n), expect, "shl({a}, {n})");
        }
    }

    #[test]
    fn logical_shr_is_unsigned_including_large() {
        // Reference: unsigned shift = floor(a / 2^n).
        let cases: [(BigInt, u32); 12] = [
            (umax(), 0),
            (umax(), 1),
            (umax(), 128),
            (umax(), 255),
            (umax(), 256),                 // shifts everything out -> 0
            (pow2(255), 1),                // 2^254 (native arith SHR would keep sign)
            (pow2(255), 255),              // 1
            (pow2(255) + BigInt::from(1), 255), // 1 (low bit dropped)
            (pow2(200), 100),              // 2^100
            (pow2(128), 64),               // 2^64
            (big("115792089237316195423570985008687907853269984665640564039457584007913129639000"), 8),
            (BigInt::from(0), 5),
        ];
        for (a, n) in cases {
            let expect = &a >> n; // a is in [0, 2^256), so this is the unsigned shift
            assert_eq!(run_shr(&a, n), expect, "shr({a}, {n})");
        }
    }

    /// Assemble a standalone program [main -> divmod -> {add, sub}] and run it.
    /// Returns `(q, r)` as unsigned uint256, or `Err` on a thrown panic
    /// (division by zero).
    fn run_divmod(a: &BigInt, b: &BigInt) -> Result<(BigInt, BigInt), String> {
        let mut code = Vec::new();
        emit_pushint256_le(&mut code, &u256_le(a));
        emit_pushint256_le(&mut code, &u256_le(b));
        let call_divmod = emit_branch_l_placeholder(&mut code, 0x35); // CALL_L divmod
        code.push(0x40); // RET (program end) -> leaves [q, r]
        let divmod_off = code.len();
        let (add_sites, sub_sites) = emit_uint256_divmod_body(&mut code);
        let add_off = code.len();
        emit_uint256_unchecked_add(&mut code);
        code.push(0x40); // RET
        let sub_off = code.len();
        emit_uint256_unchecked_sub(&mut code);
        code.push(0x40); // RET
        patch_rel32(&mut code, call_divmod, divmod_off);
        for s in add_sites {
            patch_rel32(&mut code, s, add_off);
        }
        for s in sub_sites {
            patch_rel32(&mut code, s, sub_off);
        }
        let st = faithful_run(&code)?;
        if st.len() < 2 {
            return Err("expected [q, r]".into());
        }
        let r = st[st.len() - 1].clone();
        let q = st[st.len() - 2].clone();
        let m = modulus();
        let norm = |v: BigInt| ((v % &m) + &m) % &m;
        Ok((norm(q), norm(r)))
    }

    #[test]
    fn unsigned_divmod_including_large() {
        let cases = [
            (big("100"), big("7")),
            (big("5"), big("7")),                 // a < b -> q=0, r=a
            (umax(), big("1")),                   // /1
            (umax(), big("2")),
            (umax(), big("3")),
            (umax(), big("1000000000000000000")), // large / 1e18 (DeFi)
            (pow2(255), big("2")),                // 2^254, r 0
            (pow2(255) + BigInt::from(1), big("2")),
            (pow2(200), big("13")),
            (umax(), umax()),                     // 1, 0
            (umax(), pow2(255)),                  // big divisor: q=1, r=2^255-1
            (pow2(255), pow2(255)),               // q=1, r=0
            (pow2(255) - BigInt::from(1), pow2(255)), // a<b: q=0, r=2^255-1
            (pow2(200), pow2(255) + BigInt::from(99)), // big divisor, a<b
            (big("0"), umax()),                   // 0 / x = 0
        ];
        for (a, b) in cases {
            let (q, r) = run_divmod(&a, &b).expect("no panic");
            assert_eq!(q, &a / &b, "div({a}, {b})");
            assert_eq!(r, &a % &b, "mod({a}, {b})");
            // Invariant: a == q*b + r and r < b.
            assert_eq!(&q * &b + &r, a, "q*b+r == a for ({a},{b})");
            assert!(r < b, "r < b for ({a},{b})");
        }
    }

    #[test]
    fn divmod_by_zero_panics() {
        assert!(run_divmod(&big("5"), &big("0")).is_err());
        assert!(run_divmod(&umax(), &big("0")).is_err());
        assert!(run_divmod(&big("0"), &big("0")).is_err());
    }

    #[test]
    fn unsigned_le_ge_including_large() {
        // <=
        assert!(run_cmp(emit_uint256_unsigned_le, &BigInt::from(7), &BigInt::from(7)));
        assert!(run_cmp(emit_uint256_unsigned_le, &BigInt::from(5), &umax()));
        assert!(!run_cmp(emit_uint256_unsigned_le, &umax(), &BigInt::from(5)));
        assert!(run_cmp(emit_uint256_unsigned_le, &umax(), &umax()));
        // >=
        assert!(run_cmp(emit_uint256_unsigned_ge, &BigInt::from(7), &BigInt::from(7)));
        assert!(run_cmp(emit_uint256_unsigned_ge, &umax(), &BigInt::from(5)));
        assert!(!run_cmp(emit_uint256_unsigned_ge, &BigInt::from(5), &umax()));
        assert!(run_cmp(emit_uint256_unsigned_ge, &pow2(255), &(pow2(255) - 1)));
    }
}