bsv-rs 0.3.28

BSV SDK for Rust: primitives, the script interpreter, transactions and BEEF/SPV, BRC-42 wallets, BRC-103 auth, the overlay network. Reference parity with the TypeScript SDK, native and wasm32.
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
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
//! Bitcoin Script interpreter for spend validation.
//!
// Allow large error type - ScriptEvaluationError intentionally captures full
// execution state for debugging failed script executions.
#![allow(clippy::result_large_err)]
//!
//! This module implements the full Bitcoin Script interpreter for BSV, enabling
//! validation of transaction spends by executing unlocking and locking scripts.
//!
//! # Two ways to run it
//!
//! Without a flag word, [`Spend`] runs the TypeScript SDK's default evaluation
//! mode: strict for a transaction of version 1 or lower (minimal pushes and
//! numbers, low-S, a clean stack, an empty CHECKMULTISIG dummy), relaxed for
//! version 2 and above, push-only unlocking scripts at every version, and no
//! NULLFAIL rule. That mode is neither of the words a node validates under.
//!
//! With [`Spend::set_flags`], every rule is derived from a
//! [`ScriptFlags`] word and the transaction version
//! exactly as bitcoin-sv v1.2.2 derives it at each site: the block word
//! ([`ScriptFlags::block`]) is what a mining
//! node applies, the standard word
//! ([`ScriptFlags::standard`]) is what a
//! relaying node with default policy applies. A consensus oracle selects the
//! block word. The `flags` module documents every rule, its gate and its site.
//!
//! # Example
//!
//! ```rust,ignore
//! use bsv_rs::script::{Spend, LockingScript, UnlockingScript};
//!
//! let spend = Spend::new(SpendParams {
//!     source_txid: [0u8; 32],
//!     source_output_index: 0,
//!     source_satoshis: 100_000,
//!     locking_script: LockingScript::from_asm("OP_DUP OP_HASH160 ... OP_CHECKSIG")?,
//!     transaction_version: 1,
//!     other_inputs: vec![],
//!     outputs: vec![],
//!     input_index: 0,
//!     unlocking_script: UnlockingScript::from_asm("<sig> <pubkey>")?,
//!     input_sequence: 0xffffffff,
//!     lock_time: 0,
//!     memory_limit: None,
//! });
//!
//! let valid = spend.validate()?;
//! ```

use super::evaluation_error::{
    ExecutionContext, ScriptEvaluationError, ScriptResource, ScriptResourceLimit,
};
use super::flags::{Gates, ScriptFlags, DEFAULT_SCRIPT_NUM_LENGTH_POLICY};
use super::op::*;
use super::script_num::ScriptNum;
use super::{LockingScript, Script, ScriptChunk, UnlockingScript};
use crate::primitives::bsv::sighash::{
    compute_sighash_for_signing, SighashParams, TxInput, TxOutput, SIGHASH_FORKID,
};
use crate::primitives::bsv::tx_signature::TransactionSignature;
use crate::primitives::ec::PublicKey;
use crate::primitives::{hash160, ripemd160, sha1, sha256, sha256d, to_hex, BigNumber};

// ============================================================================
// Configuration Constants
// ============================================================================

/// Maximum size of a single script element (1GB for BSV unlimited)
const MAX_SCRIPT_ELEMENT_SIZE: usize = 1024 * 1024 * 1024;

/// Default memory limit for stack usage (32MB)
const DEFAULT_MEMORY_LIMIT: usize = 32_000_000;

/// Maximum number of keys in a multisig (i32::MAX for BSV)
const MAX_MULTISIG_KEY_COUNT: i64 = i32::MAX as i64;

/// Require minimal push encoding
const REQUIRE_MINIMAL_PUSH: bool = true;

/// Require push-only unlocking scripts
const REQUIRE_PUSH_ONLY_UNLOCKING: bool = true;

/// Require low-S signatures
const REQUIRE_LOW_S_SIGNATURES: bool = true;

/// Require clean stack after execution
const REQUIRE_CLEAN_STACK: bool = true;

// ============================================================================
// Pre-computed Script Numbers
// ============================================================================

lazy_static::lazy_static! {
    /// Pre-computed script number for -1
    static ref SCRIPTNUM_NEG_1: Vec<u8> = ScriptNum::to_bytes(&BigNumber::from_i64(-1));

    /// Pre-computed script numbers for 0-16
    static ref SCRIPTNUMS_0_TO_16: Vec<Vec<u8>> = (0..=16)
        .map(|i| ScriptNum::to_bytes(&BigNumber::from_i64(i)))
        .collect();
}

// ============================================================================
// Spend Parameters
// ============================================================================

/// Parameters for constructing a Spend validator.
pub struct SpendParams {
    /// The transaction ID of the source UTXO (32 bytes, internal byte order).
    pub source_txid: [u8; 32],
    /// The index of the output in the source transaction.
    pub source_output_index: u32,
    /// The satoshi value of the source UTXO.
    pub source_satoshis: u64,
    /// The locking script of the source UTXO.
    pub locking_script: LockingScript,
    /// The version of the spending transaction.
    pub transaction_version: i32,
    /// Other inputs in the spending transaction (excluding this one).
    pub other_inputs: Vec<TxInput>,
    /// Outputs of the spending transaction.
    pub outputs: Vec<TxOutput>,
    /// The index of this input in the spending transaction.
    pub input_index: usize,
    /// The unlocking script for this spend.
    pub unlocking_script: UnlockingScript,
    /// The sequence number of this input.
    pub input_sequence: u32,
    /// The lock time of the spending transaction.
    pub lock_time: u32,
    /// Optional memory limit in bytes (default: 32MB).
    pub memory_limit: Option<usize>,
}

// ============================================================================
// Spend Struct
// ============================================================================

/// The Spend struct represents a spend action and validates it by executing
/// the unlocking and locking scripts.
pub struct Spend {
    // Transaction context
    source_txid: [u8; 32],
    source_output_index: u32,
    source_satoshis: u64,
    locking_script: LockingScript,
    transaction_version: i32,
    other_inputs: Vec<TxInput>,
    outputs: Vec<TxOutput>,
    input_index: usize,
    unlocking_script: UnlockingScript,
    input_sequence: u32,
    lock_time: u32,

    // Execution state
    context: ExecutionContext,
    program_counter: usize,
    last_code_separator: Option<usize>,
    stack: Vec<Vec<u8>>,
    alt_stack: Vec<Vec<u8>>,
    if_stack: Vec<bool>,
    memory_limit: usize,
    stack_mem: usize,
    alt_stack_mem: usize,
    require_push_only: bool,
    require_minimal: bool,
    require_low_s: bool,
    require_clean_stack: bool,
    require_null_dummy: bool,
    require_null_fail: bool,
    require_minimal_if: bool,
    require_compressed_pubkey: bool,
    discourage_upgradable_nops: bool,
    /// The flag word the rules above were derived from, if `set_flags` was
    /// called; `None` in the TypeScript default mode.
    flags: Option<ScriptFlags>,
    /// The UTXO being spent is taken as created after Chronicle: `OP_2MUL`,
    /// `OP_2DIV`, `OP_VER`, `OP_VERIF`, `OP_VERNOTIF` and the Chronicle
    /// meanings of `0xb3`-`0xb7` follow it (`interpreter.cpp:360-375`,
    /// `598-812`). Default: the TypeScript SDK's `isAfterChronicle()`, which
    /// is `isRelaxed()`, version > 1; under a word, its `UTXO_AFTER_CHRONICLE`.
    utxo_after_chronicle: bool,
    /// The node's `-maxscriptnumlengthpolicy`, the script-number length limit
    /// of the mempool path (`src/policy/policy.h:156`, default 10,000; 0
    /// selects the consensus limit); read under a word carrying the mempool
    /// word's bits, see [`Spend::max_script_num_length`].
    script_num_length_policy: usize,
    /// Whether an `OP_ELSE` was seen at each conditional depth (the
    /// reference's `conditional_tracker`: a second `OP_ELSE` for one `OP_IF`
    /// is unbalanced after Genesis, `interpreter.cpp:829-831`).
    else_stack: Vec<bool>,
    /// A non-top-level `OP_RETURN` executed after Genesis: execution stops,
    /// the walk continues for the conditional balance and the parse
    /// (`interpreter.cpp:856-871` with `482`).
    returning: bool,
    /// The chunk index of a push that declares more bytes than the script
    /// holds, per script (`Script::truncated_push`): reaching it is
    /// `SCRIPT_ERR_BAD_OPCODE` on the reference.
    unlocking_truncated: Option<usize>,
    locking_truncated: Option<usize>,

    // Parsed-chunk caches. `Script::chunks()` deep-clones the whole chunk
    // vector; calling it from `step()` made execution O(N²) in script size,
    // which is prohibitive for large covenant scripts (a ~500 KB script
    // would take hours). Cached once here; `step()` indexes the cache.
    unlocking_chunks: Vec<crate::script::chunk::ScriptChunk>,
    locking_chunks: Vec<crate::script::chunk::ScriptChunk>,
}

impl Spend {
    /// Creates a new Spend validator from the given parameters.
    pub fn new(params: SpendParams) -> Self {
        let mut spend = Self {
            source_txid: params.source_txid,
            source_output_index: params.source_output_index,
            source_satoshis: params.source_satoshis,
            locking_script: params.locking_script,
            transaction_version: params.transaction_version,
            other_inputs: params.other_inputs,
            outputs: params.outputs,
            input_index: params.input_index,
            unlocking_script: params.unlocking_script,
            input_sequence: params.input_sequence,
            lock_time: params.lock_time,
            context: ExecutionContext::UnlockingScript,
            program_counter: 0,
            unlocking_chunks: Vec::new(),
            locking_chunks: Vec::new(),
            last_code_separator: None,
            stack: Vec::new(),
            alt_stack: Vec::new(),
            if_stack: Vec::new(),
            memory_limit: params.memory_limit.unwrap_or(DEFAULT_MEMORY_LIMIT),
            stack_mem: 0,
            alt_stack_mem: 0,
            require_push_only: REQUIRE_PUSH_ONLY_UNLOCKING,
            // ts-sdk parity: transactions with version > 1 run "relaxed"
            // (post-Genesis semantics) — MINIMALDATA, LOW_S, CLEANSTACK and
            // NULLDUMMY are not enforced (mirrors ts-sdk Spend.isRelaxed() and
            // its shouldEnforceNullDummy()). The reference gates the same four
            // on the version at Chronicle (`interpreter.cpp:40-44`).
            require_minimal: REQUIRE_MINIMAL_PUSH && params.transaction_version <= 1,
            require_low_s: REQUIRE_LOW_S_SIGNATURES && params.transaction_version <= 1,
            require_clean_stack: REQUIRE_CLEAN_STACK && params.transaction_version <= 1,
            require_null_dummy: params.transaction_version <= 1,
            // Not in the ts-sdk default mode (its NULLFAIL, MINIMALIF and
            // DISCOURAGE_UPGRADABLE_NOPS exist only under explicit verifyFlags);
            // derived from a word by `set_flags`.
            require_null_fail: false,
            require_minimal_if: false,
            require_compressed_pubkey: false,
            discourage_upgradable_nops: false,
            flags: None,
            // ts-sdk parity: isAfterChronicle() is isRelaxed() without explicit flags.
            utxo_after_chronicle: params.transaction_version > 1,
            script_num_length_policy: DEFAULT_SCRIPT_NUM_LENGTH_POLICY,
            else_stack: Vec::new(),
            returning: false,
            unlocking_truncated: None,
            locking_truncated: None,
        };
        spend.unlocking_chunks = spend.unlocking_script.chunks();
        spend.locking_chunks = spend.locking_script.chunks();
        spend.unlocking_truncated = spend.unlocking_script.as_script().truncated_push();
        spend.locking_truncated = spend.locking_script.as_script().truncated_push();
        spend.reset();
        spend
    }

    /// Overrides MINIMALDATA enforcement (script-number and push minimality).
    ///
    /// Default follows ts-sdk: enforced for version <= 1 transactions, relaxed
    /// for version > 1 (post-Genesis semantics). Called after [`set_flags`](Self::set_flags),
    /// it overrides the rule the word derived.
    pub fn set_require_minimal(&mut self, require: bool) {
        self.require_minimal = require;
    }

    /// Allows opting out of the push-only unlocking-script check.
    ///
    /// The TypeScript `@bsv/sdk` Spend engine does not enforce push-only
    /// unlocking scripts; some OP_PUSH_TX-style covenant designs place
    /// executable code in the unlocking script and verify under that engine.
    /// Default remains `true` (enforced). Called after [`set_flags`](Self::set_flags),
    /// it overrides the rule the word derived (the reference requires push-only
    /// unlocking scripts post-Chronicle only for version <= 1).
    pub fn set_require_push_only(&mut self, require: bool) {
        self.require_push_only = require;
    }

    /// Applies a verification flag word: every rule this interpreter enforces
    /// is re-derived from `flags` and the transaction version exactly as
    /// bitcoin-sv v1.2.2 derives it at the rule's site, including its version
    /// gate `EnforceNonMalleability` (`interpreter.cpp:40-44`; the table on
    /// [`ScriptFlags`]). The TypeScript default mode's switches are replaced,
    /// not merged; `set_require_minimal` and `set_require_push_only` override
    /// a derived rule when called afterwards.
    ///
    /// A consensus oracle selects the block word:
    ///
    /// ```rust,ignore
    /// spend.set_flags(ScriptFlags::block(ProtocolEra::PostChronicle));
    /// ```
    ///
    /// A word this interpreter cannot honor ([`ScriptFlags::check`]) is
    /// accepted here and refused by [`validate`](Self::validate), as the
    /// reference refuses an invalid word at `VerifyScript`
    /// (`interpreter.cpp:2312-2313`).
    pub fn set_flags(&mut self, flags: ScriptFlags) {
        let Gates {
            push_only,
            minimal,
            low_s,
            clean_stack,
            null_dummy,
            null_fail,
            minimal_if,
            discourage_upgradable_nops,
            compressed_pubkey,
            utxo_after_chronicle,
        } = flags.gates(self.transaction_version);
        self.require_push_only = push_only;
        self.require_minimal = minimal;
        self.require_low_s = low_s;
        self.require_clean_stack = clean_stack;
        self.require_null_dummy = null_dummy;
        self.require_null_fail = null_fail;
        self.require_minimal_if = minimal_if;
        self.discourage_upgradable_nops = discourage_upgradable_nops;
        self.require_compressed_pubkey = compressed_pubkey;
        self.utxo_after_chronicle = utxo_after_chronicle;
        self.flags = Some(flags);
    }

    /// Overrides the UTXO's era for the re-enabled opcodes: `true` runs
    /// `OP_2MUL`, `OP_2DIV`, `OP_VER`, `OP_VERIF`, `OP_VERNOTIF` and the
    /// Chronicle meanings of `0xb3`-`0xb7` (a coin created after Chronicle),
    /// `false` keeps them disabled, `BAD_OPCODE` or NOPs as before it. Default:
    /// version > 1 (the TypeScript SDK's `isAfterChronicle()`); under a word,
    /// its `UTXO_AFTER_CHRONICLE` bit. Called after [`set_flags`](Self::set_flags),
    /// it overrides the bit.
    pub fn set_utxo_after_chronicle(&mut self, after: bool) {
        self.utxo_after_chronicle = after;
    }

    /// The flag word applied by [`set_flags`](Self::set_flags), or `None` in
    /// the TypeScript default mode.
    pub fn flags(&self) -> Option<ScriptFlags> {
        self.flags
    }

    /// The script-number length limit in force: `None` in the TypeScript
    /// default mode (the SDK reads a number of any length); under a word the
    /// reference's limit ([`ScriptFlags::max_script_num_length`]) for the
    /// coin's era, following
    /// [`set_utxo_after_chronicle`](Self::set_utxo_after_chronicle), and on
    /// the mempool path the policy of
    /// [`set_script_num_length_policy`](Self::set_script_num_length_policy).
    /// Applied before the decode at every read (`script_num.cpp:62-68`), on
    /// every arithmetic result before it is pushed (`164`, `194`, `214`,
    /// `301-315`), at `OP_BIN2NUM`'s result (`interpreter.cpp:1789-1790`), and
    /// as 4 bytes on `OP_CHECKMULTISIG`'s counts (`1519-1525`, `1550-1552`).
    pub fn max_script_num_length(&self) -> Option<usize> {
        self.flags.map(|word| {
            word.max_script_num_length(self.utxo_after_chronicle, self.script_num_length_policy)
        })
    }

    /// The node's `-maxscriptnumlengthpolicy` for a word on the mempool path
    /// (`src/policy/policy.h:156`, 10,000 bytes by default; 0 selects the
    /// consensus limit of the coin's era). A block word and the default mode
    /// ignore it.
    pub fn set_script_num_length_policy(&mut self, bytes: usize) {
        self.script_num_length_policy = bytes;
    }

    /// Resets the interpreter state for re-execution.
    pub fn reset(&mut self) {
        self.context = ExecutionContext::UnlockingScript;
        self.program_counter = 0;
        self.last_code_separator = None;
        self.stack.clear();
        self.alt_stack.clear();
        self.if_stack.clear();
        self.else_stack.clear();
        self.returning = false;
        self.stack_mem = 0;
        self.alt_stack_mem = 0;
    }

    /// Validates the spend by executing both scripts.
    ///
    /// # Returns
    ///
    /// `Ok(true)` if the spend is valid, or an error describing why validation failed.
    pub fn validate(&mut self) -> Result<bool, ScriptEvaluationError> {
        // A word this interpreter cannot honor, or one the reference refuses
        // (`SCRIPT_ERR_INVALID_FLAGS`, interpreter.cpp:2312-2313, 2436-2437).
        if let Some(flags) = self.flags {
            if let Err(e) = flags.check() {
                return Err(self.error(&format!("Invalid verification flags: {e}.")));
            }
        }

        // Check that unlocking script is push-only
        if self.require_push_only && !self.unlocking_script.is_push_only() {
            return Err(self.error(
                "Unlocking scripts can only contain push operations, and no other opcodes.",
            ));
        }

        // Execute both scripts
        while self.step()? {
            // Continue until script ends
            if self.context == ExecutionContext::LockingScript
                && self.program_counter >= self.locking_chunks.len()
            {
                break;
            }
        }

        // Verify if_stack is empty (all conditionals closed)
        if !self.if_stack.is_empty() {
            return Err(self.error(
                "Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the script.",
            ));
        }

        // Clean stack rule
        if self.require_clean_stack && self.stack.len() != 1 {
            return Err(self.error(&format!(
                "The clean stack rule requires exactly one item to be on the stack after script execution, found {}.",
                self.stack.len()
            )));
        }

        // Top value must be truthy
        if self.stack.is_empty() {
            return Err(self.error(
                "The top stack element must be truthy after script evaluation (stack is empty).",
            ));
        }

        if !ScriptNum::cast_to_bool(&self.stack[self.stack.len() - 1]) {
            return Err(self.error("The top stack element must be truthy after script evaluation."));
        }

        Ok(true)
    }

    /// Executes a single instruction (step).
    ///
    /// # Returns
    ///
    /// `Ok(true)` if execution should continue, `Ok(false)` if the script is complete.
    pub fn step(&mut self) -> Result<bool, ScriptEvaluationError> {
        // Check memory limits — a LOCAL budget, reported as a resource limit
        // (the reference's `ScriptResourceLimitError`), never as a verdict on
        // the script.
        if self.stack_mem > self.memory_limit {
            return Err(self.resource_error(ScriptResource::Stack, self.stack_mem));
        }
        if self.alt_stack_mem > self.memory_limit {
            return Err(self.resource_error(ScriptResource::AltStack, self.alt_stack_mem));
        }

        // Switch from unlocking to locking script when unlocking is complete.
        // ts-sdk parity: conditionals must be terminated, the alt stack is
        // cleared, and the last code separator does not carry across scripts.
        if self.context == ExecutionContext::UnlockingScript
            && self.program_counter >= self.unlocking_chunks.len()
        {
            if !self.if_stack.is_empty() {
                return Err(self.error(
                    "Every OP_IF, OP_NOTIF, or OP_ELSE must be terminated with OP_ENDIF prior to the end of the unlocking script.",
                ));
            }
            self.alt_stack.clear();
            self.alt_stack_mem = 0;
            self.last_code_separator = None;
            self.else_stack.clear();
            self.returning = false;
            self.context = ExecutionContext::LockingScript;
            self.program_counter = 0;
        }

        // Get current script and check if we're done (cached chunks: the
        // per-step deep clone of the whole script was O(N²) — see field docs)
        let current_len = match self.context {
            ExecutionContext::UnlockingScript => self.unlocking_chunks.len(),
            ExecutionContext::LockingScript => self.locking_chunks.len(),
        };

        if self.program_counter >= current_len {
            return Ok(false);
        }

        let op_owned = match self.context {
            ExecutionContext::UnlockingScript => {
                self.unlocking_chunks[self.program_counter].clone()
            }
            ExecutionContext::LockingScript => self.locking_chunks[self.program_counter].clone(),
        };
        let operation = &op_owned;
        let current_opcode = operation.op;

        // A push that declares more bytes than the script holds: the reference's
        // GetOp fails and the script is SCRIPT_ERR_BAD_OPCODE when the walk
        // reaches it, executed or not (script.h:190-191, interpreter.cpp:450-451).
        let truncated = match self.context {
            ExecutionContext::UnlockingScript => self.unlocking_truncated,
            ExecutionContext::LockingScript => self.locking_truncated,
        };
        if truncated == Some(self.program_counter) {
            return Err(self.error(&format!(
                "A push declares more bytes than the script holds; the script cannot be parsed past it (pc={}).",
                self.program_counter
            )));
        }

        // Check for oversized data push
        if let Some(ref data) = operation.data {
            if data.len() > MAX_SCRIPT_ELEMENT_SIZE {
                return Err(self.error(&format!(
                    "Data push > {} bytes (pc={})",
                    MAX_SCRIPT_ELEMENT_SIZE, self.program_counter
                )));
            }
        }

        // Determine if we're currently executing (not in a false conditional branch)
        let is_executing = !self.returning && !self.if_stack.contains(&false);

        // Check for disabled opcodes when executing
        if is_executing && is_opcode_disabled(current_opcode, self.utxo_after_chronicle) {
            return Err(self.error(&format!(
                "This opcode is currently disabled. (Opcode: {}, PC: {})",
                opcode_to_name(current_opcode).unwrap_or("UNKNOWN"),
                self.program_counter
            )));
        }

        // Execute opcode
        if is_executing && current_opcode <= OP_PUSHDATA4 {
            // Push data operations
            if self.require_minimal && !is_chunk_minimal_push(operation) {
                return Err(self.error(&format!(
                    "This data is not minimally-encoded. (PC: {})",
                    self.program_counter
                )));
            }
            let data = operation.data.clone().unwrap_or_default();
            self.push_stack(data)?;
        } else if is_executing || (OP_IF..=OP_ENDIF).contains(&current_opcode) {
            // Execute the opcode
            self.execute_opcode(current_opcode, operation)?;
        }

        self.program_counter += 1;
        Ok(true)
    }

    // ========================================================================
    // Opcode Execution
    // ========================================================================

    fn execute_opcode(
        &mut self,
        opcode: u8,
        chunk: &ScriptChunk,
    ) -> Result<(), ScriptEvaluationError> {
        let is_executing = !self.returning && !self.if_stack.contains(&false);

        match opcode {
            // ================================================================
            // Push Operations (0x00-0x60)
            // ================================================================
            OP_1NEGATE => {
                self.push_stack_copy(&SCRIPTNUM_NEG_1)?;
            }
            OP_0 => {
                self.push_stack_copy(&SCRIPTNUMS_0_TO_16[0])?;
            }
            OP_1..=OP_16 => {
                let n = (opcode - OP_1 + 1) as usize;
                self.push_stack_copy(&SCRIPTNUMS_0_TO_16[n])?;
            }

            // ================================================================
            // NOPs (do nothing)
            // ================================================================
            OP_NOP => {}
            // The upgradable NOPs 0xb0-0xb9. Under DISCOURAGE_UPGRADABLE_NOPS an
            // executed one fails the script (interpreter.cpp:765-771 for NOP1,
            // NOP9, NOP10; 520-523 and 563-566 for CHECKLOCKTIMEVERIFY and
            // CHECKSEQUENCEVERIFY, NOPs for a post-Genesis UTXO; 606-700 for
            // NOP4-NOP8 before their Chronicle meanings). ts-sdk: "is
            // discouraged by verification flags".
            OP_NOP1 | OP_NOP2 | OP_NOP3 | OP_NOP9 | OP_NOP10 => {
                if self.discourage_upgradable_nops {
                    return Err(self.error(&format!(
                        "{} is discouraged by verification flags.",
                        opcode_to_name(opcode).unwrap_or("OP_NOP")
                    )));
                }
            }
            // 0xb3-0xb7: NOP4-NOP8 before Chronicle; OP_SUBSTR, OP_LEFT, OP_RIGHT,
            // OP_LSHIFTNUM, OP_RSHIFTNUM for a UTXO created after it
            // (interpreter.cpp:609-764; the NOP branch with the discouragement at
            // each arm's head).
            OP_NOP4 | OP_NOP5 | OP_NOP6 | OP_NOP7 | OP_NOP8 => {
                if !self.utxo_after_chronicle {
                    if self.discourage_upgradable_nops {
                        return Err(self.error(&format!(
                            "{} is discouraged by verification flags.",
                            opcode_to_name(opcode).unwrap_or("OP_NOP")
                        )));
                    }
                } else {
                    self.op_chronicle_splice(opcode)?;
                }
            }
            // 0xba-0xff are undefined: the reference's `default:` is
            // SCRIPT_ERR_BAD_OPCODE when one is executed (interpreter.cpp:1795),
            // and this arm is only reached when executing: they fall to the
            // invalid-opcode arm below.
            // OP_VER: the transaction version as 4 little-endian bytes for a UTXO
            // created after Chronicle (interpreter.cpp:598-608); BAD_OPCODE before.
            OP_VER => {
                if !self.utxo_after_chronicle {
                    return Err(self.error("OP_VER is disabled until Chronicle."));
                }
                self.push_stack(self.transaction_version.to_le_bytes().to_vec())?;
            }

            // ================================================================
            // Flow Control (0x63-0x6a)
            // ================================================================
            OP_IF | OP_NOTIF => {
                let mut f_value = false;
                if is_executing {
                    if self.stack.is_empty() {
                        return Err(self.error(
                            "OP_IF and OP_NOTIF require at least one item on the stack when they are used!",
                        ));
                    }
                    let buf = self.pop_stack()?;
                    // MINIMALIF (interpreter.cpp:795-803, under the version
                    // gate): the argument must be empty or exactly 0x01.
                    if self.require_minimal_if && !(buf.is_empty() || buf == [1]) {
                        return Err(self.error("OP_IF and OP_NOTIF require minimal truth values."));
                    }
                    f_value = ScriptNum::cast_to_bool(&buf);
                    if opcode == OP_NOTIF {
                        f_value = !f_value;
                    }
                }
                self.if_stack.push(f_value);
                self.else_stack.push(false);
            }
            // OP_VERIF / OP_VERNOTIF (interpreter.cpp:773-812): for a UTXO created
            // after Chronicle, a conditional on "the top element is exactly the
            // transaction version as 4 little-endian bytes"; before Chronicle,
            // skipped when not executing (post-Genesis) and BAD_OPCODE when
            // executed. This arm runs whether or not the branch executes (the
            // opcodes sit in the OP_IF..OP_ENDIF range).
            OP_VERIF | OP_VERNOTIF => {
                if !self.utxo_after_chronicle {
                    if !is_executing {
                        return Ok(());
                    }
                    return Err(self.error(&format!(
                        "{} is disabled until Chronicle.",
                        opcode_to_name(opcode).unwrap_or("OP_VERIF")
                    )));
                }
                let mut f_value = false;
                if is_executing {
                    if self.stack.is_empty() {
                        return Err(self.error(
                            "OP_VERIF and OP_VERNOTIF require at least one item on the stack when they are used!",
                        ));
                    }
                    let buf = self.pop_stack()?;
                    if buf.len() == 4 {
                        f_value = buf == self.transaction_version.to_le_bytes();
                    }
                    if opcode == OP_VERNOTIF {
                        f_value = !f_value;
                    }
                }
                self.if_stack.push(f_value);
                self.else_stack.push(false);
            }
            OP_ELSE => {
                if self.if_stack.is_empty() {
                    return Err(self.error("OP_ELSE requires a preceeding OP_IF."));
                }
                // One OP_ELSE per OP_IF after Genesis (conditional_tracker.cpp:51-55,
                // interpreter.cpp:829-831); every UTXO here is post-Genesis.
                if self.else_stack.last() == Some(&true) {
                    return Err(self.error(
                        "OP_ELSE may only be used once for each OP_IF or OP_NOTIF after Genesis.",
                    ));
                }
                if let Some(seen) = self.else_stack.last_mut() {
                    *seen = true;
                }
                let last = self.if_stack.len() - 1;
                self.if_stack[last] = !self.if_stack[last];
            }
            OP_ENDIF => {
                if self.if_stack.is_empty() {
                    return Err(self.error("OP_ENDIF requires a preceeding OP_IF."));
                }
                self.if_stack.pop();
                self.else_stack.pop();
            }
            OP_VERIFY => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_VERIFY requires at least one item to be on the stack.")
                    );
                }
                let f_value = ScriptNum::cast_to_bool(self.stack_top()?);
                if !f_value {
                    return Err(self.error("OP_VERIFY requires the top stack value to be truthy."));
                }
                self.pop_stack()?;
            }
            OP_RETURN => {
                // After Genesis (interpreter.cpp:856-871): at the top level the
                // script ends successfully, whatever follows; inside a conditional,
                // execution stops but the walk continues, so the conditionals must
                // still balance and every later opcode must still parse (`482`).
                if self.if_stack.is_empty() {
                    let end = match self.context {
                        ExecutionContext::UnlockingScript => self.unlocking_chunks.len(),
                        ExecutionContext::LockingScript => self.locking_chunks.len(),
                    };
                    self.program_counter = end;
                    // Counteract the final increment
                    if self.program_counter > 0 {
                        self.program_counter -= 1;
                    }
                } else {
                    self.returning = true;
                }
            }

            // ================================================================
            // Stack Operations (0x6b-0x7d)
            // ================================================================
            OP_TOALTSTACK => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_TOALTSTACK requires at least one item to be on the stack.")
                    );
                }
                let item = self.pop_stack()?;
                self.push_alt_stack(item)?;
            }
            OP_FROMALTSTACK => {
                if self.alt_stack.is_empty() {
                    return Err(self.error(
                        "OP_FROMALTSTACK requires at least one item to be on the alt stack.",
                    ));
                }
                let item = self.pop_alt_stack()?;
                self.push_stack(item)?;
            }
            OP_2DROP => {
                if self.stack.len() < 2 {
                    return Err(
                        self.error("OP_2DROP requires at least two items to be on the stack.")
                    );
                }
                self.pop_stack()?;
                self.pop_stack()?;
            }
            OP_2DUP => {
                if self.stack.len() < 2 {
                    return Err(
                        self.error("OP_2DUP requires at least two items to be on the stack.")
                    );
                }
                let buf1 = self.stack_top_n(2)?.to_vec();
                let buf2 = self.stack_top()?.to_vec();
                self.push_stack(buf1)?;
                self.push_stack(buf2)?;
            }
            OP_3DUP => {
                if self.stack.len() < 3 {
                    return Err(
                        self.error("OP_3DUP requires at least three items to be on the stack.")
                    );
                }
                let buf1 = self.stack_top_n(3)?.to_vec();
                let buf2 = self.stack_top_n(2)?.to_vec();
                let buf3 = self.stack_top()?.to_vec();
                self.push_stack(buf1)?;
                self.push_stack(buf2)?;
                self.push_stack(buf3)?;
            }
            OP_2OVER => {
                if self.stack.len() < 4 {
                    return Err(
                        self.error("OP_2OVER requires at least four items to be on the stack.")
                    );
                }
                let buf1 = self.stack_top_n(4)?.to_vec();
                let buf2 = self.stack_top_n(3)?.to_vec();
                self.push_stack(buf1)?;
                self.push_stack(buf2)?;
            }
            OP_2ROT => {
                if self.stack.len() < 6 {
                    return Err(
                        self.error("OP_2ROT requires at least six items to be on the stack.")
                    );
                }
                let x6 = self.pop_stack()?;
                let x5 = self.pop_stack()?;
                let x4 = self.pop_stack()?;
                let x3 = self.pop_stack()?;
                let x2 = self.pop_stack()?;
                let x1 = self.pop_stack()?;
                self.push_stack(x3)?;
                self.push_stack(x4)?;
                self.push_stack(x5)?;
                self.push_stack(x6)?;
                self.push_stack(x1)?;
                self.push_stack(x2)?;
            }
            OP_2SWAP => {
                if self.stack.len() < 4 {
                    return Err(
                        self.error("OP_2SWAP requires at least four items to be on the stack.")
                    );
                }
                let x4 = self.pop_stack()?;
                let x3 = self.pop_stack()?;
                let x2 = self.pop_stack()?;
                let x1 = self.pop_stack()?;
                self.push_stack(x3)?;
                self.push_stack(x4)?;
                self.push_stack(x1)?;
                self.push_stack(x2)?;
            }
            OP_IFDUP => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_IFDUP requires at least one item to be on the stack.")
                    );
                }
                let top = self.stack_top()?.to_vec();
                if ScriptNum::cast_to_bool(&top) {
                    self.push_stack(top)?;
                }
            }
            OP_DEPTH => {
                let depth = BigNumber::from_u64(self.stack.len() as u64);
                self.push_stack(ScriptNum::to_bytes(&depth))?;
            }
            OP_DROP => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_DROP requires at least one item to be on the stack.")
                    );
                }
                self.pop_stack()?;
            }
            OP_DUP => {
                if self.stack.is_empty() {
                    return Err(self.error("OP_DUP requires at least one item to be on the stack."));
                }
                let top = self.stack_top()?.to_vec();
                self.push_stack(top)?;
            }
            OP_NIP => {
                if self.stack.len() < 2 {
                    return Err(
                        self.error("OP_NIP requires at least two items to be on the stack.")
                    );
                }
                let top = self.pop_stack()?;
                self.pop_stack()?;
                self.push_stack(top)?;
            }
            OP_OVER => {
                if self.stack.len() < 2 {
                    return Err(
                        self.error("OP_OVER requires at least two items to be on the stack.")
                    );
                }
                let second = self.stack_top_n(2)?.to_vec();
                self.push_stack(second)?;
            }
            OP_PICK | OP_ROLL => {
                if self.stack.len() < 2 {
                    return Err(self.error(&format!(
                        "{} requires at least two items to be on the stack.",
                        opcode_to_name(opcode).unwrap_or("OP_PICK/ROLL")
                    )));
                }
                let n_bytes = self.pop_stack()?;
                let bn = self.read_number(&n_bytes)?;

                let n = bn.to_i64().unwrap_or(i64::MAX);
                if n < 0 || n >= self.stack.len() as i64 {
                    return Err(self.error(&format!(
                        "{} requires the top stack element to be 0 or a positive number less than the current size of the stack.",
                        opcode_to_name(opcode).unwrap_or("OP_PICK/ROLL")
                    )));
                }

                let n_idx = n as usize;
                let item = self.stack[self.stack.len() - 1 - n_idx].clone();

                if opcode == OP_ROLL {
                    let remove_idx = self.stack.len() - 1 - n_idx;
                    let removed = self.stack.remove(remove_idx);
                    self.stack_mem -= removed.len();
                    self.push_stack(item)?;
                } else {
                    // OP_PICK
                    self.push_stack(item)?;
                }
            }
            OP_ROT => {
                if self.stack.len() < 3 {
                    return Err(
                        self.error("OP_ROT requires at least three items to be on the stack.")
                    );
                }
                let x3 = self.pop_stack()?;
                let x2 = self.pop_stack()?;
                let x1 = self.pop_stack()?;
                self.push_stack(x2)?;
                self.push_stack(x3)?;
                self.push_stack(x1)?;
            }
            OP_SWAP => {
                if self.stack.len() < 2 {
                    return Err(
                        self.error("OP_SWAP requires at least two items to be on the stack.")
                    );
                }
                let x2 = self.pop_stack()?;
                let x1 = self.pop_stack()?;
                self.push_stack(x2)?;
                self.push_stack(x1)?;
            }
            OP_TUCK => {
                if self.stack.len() < 2 {
                    return Err(
                        self.error("OP_TUCK requires at least two items to be on the stack.")
                    );
                }
                let top = self.stack_top()?.to_vec();
                self.ensure_stack_mem(top.len())?;
                let insert_idx = self.stack.len() - 2;
                self.stack.insert(insert_idx, top.clone());
                self.stack_mem += top.len();
            }
            OP_SIZE => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_SIZE requires at least one item to be on the stack.")
                    );
                }
                let size = self.stack_top()?.len();
                let bn = BigNumber::from_u64(size as u64);
                self.push_stack(ScriptNum::to_bytes(&bn))?;
            }

            // ================================================================
            // Splice Operations (BSV re-enabled)
            // ================================================================
            OP_CAT => {
                if self.stack.len() < 2 {
                    return Err(
                        self.error("OP_CAT requires at least two items to be on the stack.")
                    );
                }
                let buf2 = self.pop_stack()?;
                let buf1 = self.pop_stack()?;
                let mut result = buf1;
                result.extend(buf2);
                if result.len() > MAX_SCRIPT_ELEMENT_SIZE {
                    return Err(self.error(&format!(
                        "It's not currently possible to push data larger than {} bytes.",
                        MAX_SCRIPT_ELEMENT_SIZE
                    )));
                }
                self.push_stack(result)?;
            }
            OP_SPLIT => {
                if self.stack.len() < 2 {
                    return Err(
                        self.error("OP_SPLIT requires at least two items to be on the stack.")
                    );
                }
                let pos_bytes = self.pop_stack()?;
                let data = self.pop_stack()?;

                let pos_bn = self.read_number(&pos_bytes)?;
                let pos = pos_bn.to_i64().unwrap_or(-1);

                if pos < 0 || pos > data.len() as i64 {
                    return Err(self.error(
                        "OP_SPLIT requires the first stack item to be a non-negative number less than or equal to the size of the second-from-top stack item.",
                    ));
                }

                let split_idx = pos as usize;
                let left = data[..split_idx].to_vec();
                let right = data[split_idx..].to_vec();
                self.push_stack(left)?;
                self.push_stack(right)?;
            }
            OP_NUM2BIN => {
                if self.stack.len() < 2 {
                    return Err(
                        self.error("OP_NUM2BIN requires at least two items to be on the stack.")
                    );
                }
                let size_bytes = self.pop_stack()?;
                let size_bn = self.read_number(&size_bytes)?;
                let size = size_bn.to_i64().unwrap_or(-1);

                if size < 0 || size > MAX_SCRIPT_ELEMENT_SIZE as i64 {
                    return Err(self.error(&format!(
                        "It's not currently possible to push data larger than {} bytes or negative size.",
                        MAX_SCRIPT_ELEMENT_SIZE
                    )));
                }
                let size = size as usize;
                // Reference parity (0.3.23): the element the script asks for is
                // refused BEFORE it is allocated when it alone exceeds the
                // local memory budget — the TypeScript SDK's `element-size`
                // resource check. Without this a 9-byte script could make the
                // evaluator allocate up to MAX_SCRIPT_ELEMENT_SIZE (1 GB) and
                // only then trip the stack budget on the push.
                if size > self.memory_limit {
                    return Err(self.resource_error(ScriptResource::ElementSize, size));
                }

                let rawnum = self.pop_stack()?;
                let minimal = ScriptNum::minimally_encode(&rawnum);

                if minimal.len() > size {
                    return Err(self.error(
                        "OP_NUM2BIN requires that the size expressed in the top stack item is large enough to hold the value expressed in the second-from-top stack item.",
                    ));
                }

                if minimal.len() == size {
                    self.push_stack(minimal)?;
                } else {
                    // Pad to size, preserving sign
                    let mut result = vec![0u8; size];
                    let mut signbit = 0u8;

                    if !minimal.is_empty() {
                        signbit = minimal[minimal.len() - 1] & 0x80;
                        let mut minimal_copy = minimal.clone();
                        if let Some(last) = minimal_copy.last_mut() {
                            *last &= 0x7f;
                        }
                        result[..minimal_copy.len()].copy_from_slice(&minimal_copy);
                    }

                    if signbit != 0 {
                        result[size - 1] |= 0x80;
                    }
                    self.push_stack(result)?;
                }
            }
            OP_BIN2NUM => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_BIN2NUM requires at least one item to be on the stack.")
                    );
                }
                let buf = self.pop_stack()?;
                let result = ScriptNum::minimally_encode(&buf);
                // A result longer than the limit in force is refused as the
                // reference refuses it (`IsMinimallyEncoded(max)`,
                // `interpreter.cpp:1789-1790`: `SCRIPT_ERR_INVALID_NUMBER_RANGE`).
                let over = matches!(self.max_script_num_length(), Some(max) if result.len() > max);
                if over || !ScriptNum::is_minimally_encoded(&result) {
                    return Err(
                        self.error("OP_BIN2NUM requires that the resulting number is valid.")
                    );
                }
                self.push_stack(result)?;
            }

            // ================================================================
            // Bitwise Operations
            // ================================================================
            OP_INVERT => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_INVERT requires at least one item to be on the stack.")
                    );
                }
                let buf = self.pop_stack()?;
                let result: Vec<u8> = buf.iter().map(|&b| !b).collect();
                self.push_stack(result)?;
            }
            OP_AND | OP_OR | OP_XOR => {
                if self.stack.len() < 2 {
                    return Err(self.error(&format!(
                        "{} requires at least two items on the stack.",
                        opcode_to_name(opcode).unwrap_or("OP")
                    )));
                }
                let buf2 = self.pop_stack()?;
                let buf1 = self.pop_stack()?;
                if buf1.len() != buf2.len() {
                    return Err(self.error(&format!(
                        "{} requires the top two stack items to be the same size.",
                        opcode_to_name(opcode).unwrap_or("OP")
                    )));
                }
                let result: Vec<u8> = buf1
                    .iter()
                    .zip(buf2.iter())
                    .map(|(&a, &b)| match opcode {
                        OP_AND => a & b,
                        OP_OR => a | b,
                        _ => a ^ b, // OP_XOR
                    })
                    .collect();
                self.push_stack(result)?;
            }
            OP_EQUAL | OP_EQUALVERIFY => {
                if self.stack.len() < 2 {
                    return Err(self.error(&format!(
                        "{} requires at least two items to be on the stack.",
                        opcode_to_name(opcode).unwrap_or("OP_EQUAL")
                    )));
                }
                let buf2 = self.pop_stack()?;
                let buf1 = self.pop_stack()?;
                let equal = buf1 == buf2;
                self.push_stack(if equal { vec![1] } else { vec![] })?;

                if opcode == OP_EQUALVERIFY {
                    if !equal {
                        return Err(self.error(
                            "OP_EQUALVERIFY requires the top two stack items to be equal.",
                        ));
                    }
                    self.pop_stack()?;
                }
            }
            OP_LSHIFT | OP_RSHIFT => {
                if self.stack.len() < 2 {
                    return Err(self.error(&format!(
                        "{} requires at least two items to be on the stack.",
                        opcode_to_name(opcode).unwrap_or("OP")
                    )));
                }
                let n_bytes = self.pop_stack()?;
                let buf = self.pop_stack()?;

                let n_bn = self.read_number(&n_bytes)?;
                let n = n_bn.to_i64().unwrap_or(-1);

                if n < 0 {
                    return Err(self.error(&format!(
                        "{} requires the top item on the stack not to be negative.",
                        opcode_to_name(opcode).unwrap_or("OP")
                    )));
                }

                if buf.is_empty() {
                    self.push_stack(vec![])?;
                } else {
                    // Node semantics (and ts-sdk post-#493): LSHIFT/RSHIFT are
                    // WIDTH-PRESERVING bitwise shifts on the raw byte buffer —
                    // bits shifted past the end are discarded, the result is
                    // exactly buf.len() bytes. The previous BigNumber
                    // mul/to_bytes_be(buf.len()) implementation PANICKED on
                    // overflow ("BigNumber requires N bytes") and clamped the
                    // shift count to 63 bits (conformance vectors
                    // lshift-truncation.0001/.0003).
                    let len = buf.len();
                    let result: Vec<u8> = if (n as u128) >= (len as u128) * 8 {
                        vec![0u8; len]
                    } else {
                        let byte_shift = (n as usize) / 8;
                        let bit_shift = (n as usize) % 8;
                        let mut out = vec![0u8; len];
                        #[allow(clippy::needless_range_loop)]
                        for i in 0..len {
                            if opcode == OP_LSHIFT {
                                let src = i + byte_shift;
                                let hi = if src < len { buf[src] } else { 0 };
                                let lo = if bit_shift > 0 && src + 1 < len {
                                    buf[src + 1]
                                } else {
                                    0
                                };
                                out[i] = if bit_shift == 0 {
                                    hi
                                } else {
                                    (hi << bit_shift) | (lo >> (8 - bit_shift))
                                };
                            } else {
                                // OP_RSHIFT
                                if i >= byte_shift {
                                    let src = i - byte_shift;
                                    let hi = buf[src];
                                    let carry = if bit_shift > 0 && src >= 1 {
                                        buf[src - 1]
                                    } else {
                                        0
                                    };
                                    out[i] = if bit_shift == 0 {
                                        hi
                                    } else {
                                        (hi >> bit_shift) | (carry << (8 - bit_shift))
                                    };
                                }
                            }
                        }
                        out
                    };
                    self.push_stack(result)?;
                }
            }

            // ================================================================
            // Arithmetic Operations
            // ================================================================
            // OP_2MUL / OP_2DIV run only for a UTXO created after Chronicle
            // (interpreter.cpp:1247-1254; disabled before it, `360-375`, refused
            // above in `step`).
            OP_1ADD | OP_1SUB | OP_2MUL | OP_2DIV | OP_NEGATE | OP_ABS | OP_NOT | OP_0NOTEQUAL => {
                if self.stack.is_empty() {
                    return Err(self.error(&format!(
                        "{} requires at least one item to be on the stack.",
                        opcode_to_name(opcode).unwrap_or("OP")
                    )));
                }
                let buf = self.pop_stack()?;
                let mut bn = self.read_number(&buf)?;

                bn = match opcode {
                    OP_1ADD => bn.add(&BigNumber::one()),
                    OP_1SUB => bn.sub(&BigNumber::one()),
                    OP_2MUL => bn.add(&bn),
                    OP_2DIV => bn.div(&BigNumber::from_i64(2)),
                    OP_NEGATE => bn.neg(),
                    OP_ABS => bn.abs(),
                    OP_NOT => {
                        if bn.is_zero() {
                            BigNumber::one()
                        } else {
                            BigNumber::zero()
                        }
                    }
                    OP_0NOTEQUAL => {
                        if bn.is_zero() {
                            BigNumber::zero()
                        } else {
                            BigNumber::one()
                        }
                    }
                    _ => bn,
                };
                self.push_number(&bn)?;
            }
            OP_ADD
            | OP_SUB
            | OP_MUL
            | OP_DIV
            | OP_MOD
            | OP_BOOLAND
            | OP_BOOLOR
            | OP_NUMEQUAL
            | OP_NUMEQUALVERIFY
            | OP_NUMNOTEQUAL
            | OP_LESSTHAN
            | OP_GREATERTHAN
            | OP_LESSTHANOREQUAL
            | OP_GREATERTHANOREQUAL
            | OP_MIN
            | OP_MAX => {
                if self.stack.len() < 2 {
                    return Err(self.error(&format!(
                        "{} requires at least two items to be on the stack.",
                        opcode_to_name(opcode).unwrap_or("OP")
                    )));
                }
                let buf2 = self.pop_stack()?;
                let buf1 = self.pop_stack()?;
                let bn1 = self.read_number(&buf1)?;
                let bn2 = self.read_number(&buf2)?;

                let result = match opcode {
                    OP_ADD => bn1.add(&bn2),
                    OP_SUB => bn1.sub(&bn2),
                    OP_MUL => bn1.mul(&bn2),
                    OP_DIV => {
                        if bn2.is_zero() {
                            return Err(self.error("OP_DIV cannot divide by zero!"));
                        }
                        bn1.div(&bn2)
                    }
                    OP_MOD => {
                        if bn2.is_zero() {
                            return Err(self.error("OP_MOD cannot divide by zero!"));
                        }
                        bn1.mod_floor(&bn2)
                    }
                    OP_BOOLAND => {
                        if !bn1.is_zero() && !bn2.is_zero() {
                            BigNumber::one()
                        } else {
                            BigNumber::zero()
                        }
                    }
                    OP_BOOLOR => {
                        if !bn1.is_zero() || !bn2.is_zero() {
                            BigNumber::one()
                        } else {
                            BigNumber::zero()
                        }
                    }
                    OP_NUMEQUAL | OP_NUMEQUALVERIFY => {
                        if bn1 == bn2 {
                            BigNumber::one()
                        } else {
                            BigNumber::zero()
                        }
                    }
                    OP_NUMNOTEQUAL => {
                        if bn1 != bn2 {
                            BigNumber::one()
                        } else {
                            BigNumber::zero()
                        }
                    }
                    OP_LESSTHAN => {
                        if bn1 < bn2 {
                            BigNumber::one()
                        } else {
                            BigNumber::zero()
                        }
                    }
                    OP_GREATERTHAN => {
                        if bn1 > bn2 {
                            BigNumber::one()
                        } else {
                            BigNumber::zero()
                        }
                    }
                    OP_LESSTHANOREQUAL => {
                        if bn1 <= bn2 {
                            BigNumber::one()
                        } else {
                            BigNumber::zero()
                        }
                    }
                    OP_GREATERTHANOREQUAL => {
                        if bn1 >= bn2 {
                            BigNumber::one()
                        } else {
                            BigNumber::zero()
                        }
                    }
                    OP_MIN => {
                        if bn1 < bn2 {
                            bn1
                        } else {
                            bn2
                        }
                    }
                    OP_MAX => {
                        if bn1 > bn2 {
                            bn1
                        } else {
                            bn2
                        }
                    }
                    _ => BigNumber::zero(),
                };

                self.push_number(&result)?;

                if opcode == OP_NUMEQUALVERIFY {
                    if !ScriptNum::cast_to_bool(self.stack_top()?) {
                        return Err(self
                            .error("OP_NUMEQUALVERIFY requires the top stack item to be truthy."));
                    }
                    self.pop_stack()?;
                }
            }
            OP_WITHIN => {
                if self.stack.len() < 3 {
                    return Err(
                        self.error("OP_WITHIN requires at least three items to be on the stack.")
                    );
                }
                let max_bytes = self.pop_stack()?;
                let min_bytes = self.pop_stack()?;
                let x_bytes = self.pop_stack()?;
                let max_bn = self.read_number(&max_bytes)?;
                let min_bn = self.read_number(&min_bytes)?;
                let x_bn = self.read_number(&x_bytes)?;

                let in_range = x_bn >= min_bn && x_bn < max_bn;
                self.push_stack(if in_range { vec![1] } else { vec![] })?;
            }

            // ================================================================
            // Crypto Operations
            // ================================================================
            OP_RIPEMD160 => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_RIPEMD160 requires at least one item to be on the stack.")
                    );
                }
                let buf = self.pop_stack()?;
                let hash = ripemd160(&buf);
                self.push_stack(hash.to_vec())?;
            }
            OP_SHA1 => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_SHA1 requires at least one item to be on the stack.")
                    );
                }
                let buf = self.pop_stack()?;
                let hash = sha1(&buf);
                self.push_stack(hash.to_vec())?;
            }
            OP_SHA256 => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_SHA256 requires at least one item to be on the stack.")
                    );
                }
                let buf = self.pop_stack()?;
                let hash = sha256(&buf);
                self.push_stack(hash.to_vec())?;
            }
            OP_HASH160 => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_HASH160 requires at least one item to be on the stack.")
                    );
                }
                let buf = self.pop_stack()?;
                let hash = hash160(&buf);
                self.push_stack(hash.to_vec())?;
            }
            OP_HASH256 => {
                if self.stack.is_empty() {
                    return Err(
                        self.error("OP_HASH256 requires at least one item to be on the stack.")
                    );
                }
                let buf = self.pop_stack()?;
                let hash = sha256d(&buf);
                self.push_stack(hash.to_vec())?;
            }
            OP_CODESEPARATOR => {
                self.last_code_separator = Some(self.program_counter);
            }
            OP_CHECKSIG | OP_CHECKSIGVERIFY => {
                if self.stack.len() < 2 {
                    return Err(self.error(&format!(
                        "{} requires at least two items to be on the stack.",
                        opcode_to_name(opcode).unwrap_or("OP_CHECKSIG")
                    )));
                }
                let pubkey_bytes = self.pop_stack()?;
                let sig_bytes = self.pop_stack()?;

                // Validate encodings
                self.check_signature_encoding(&sig_bytes)?;
                self.check_public_key_encoding(&pubkey_bytes)?;

                // Build subscript
                let subscript = self.build_subscript(&sig_bytes)?;

                // Verify signature
                let success = if sig_bytes.is_empty() {
                    false
                } else {
                    self.verify_signature(&sig_bytes, &pubkey_bytes, &subscript)?
                };

                // NULLFAIL (interpreter.cpp:1491-1497, under the version gate):
                // a signature that fails must be the empty vector.
                if !success && self.require_null_fail && !sig_bytes.is_empty() {
                    return Err(self.error(&format!(
                        "{} requires failing signatures to be empty.",
                        opcode_to_name(opcode).unwrap_or("OP_CHECKSIG")
                    )));
                }

                self.push_stack(if success { vec![1] } else { vec![] })?;

                if opcode == OP_CHECKSIGVERIFY {
                    if !success {
                        return Err(self.error(
                            "OP_CHECKSIGVERIFY requires that a valid signature is provided.",
                        ));
                    }
                    self.pop_stack()?;
                }
            }
            OP_CHECKMULTISIG | OP_CHECKMULTISIGVERIFY => {
                self.op_checkmultisig(opcode)?;
            }

            // ================================================================
            // Data Push (handled above, but catch any missed)
            // ================================================================
            0x01..=0x4b => {
                // Direct push opcodes - should have data
                let data = chunk.data.clone().unwrap_or_default();
                self.push_stack(data)?;
            }
            OP_PUSHDATA1 | OP_PUSHDATA2 | OP_PUSHDATA4 => {
                let data = chunk.data.clone().unwrap_or_default();
                self.push_stack(data)?;
            }

            // ================================================================
            // Unknown/Invalid Opcode
            // ================================================================
            _ => {
                return Err(self.error(&format!(
                    "Invalid opcode {} (pc={}).",
                    opcode, self.program_counter
                )));
            }
        }

        Ok(())
    }

    // ========================================================================
    // OP_CHECKMULTISIG Implementation
    // ========================================================================

    fn op_checkmultisig(&mut self, opcode: u8) -> Result<(), ScriptEvaluationError> {
        // Get number of public keys
        if self.stack.is_empty() {
            return Err(self.error(&format!(
                "{} requires at least 1 item for nKeys.",
                opcode_to_name(opcode).unwrap_or("OP_CHECKMULTISIG")
            )));
        }

        let n_keys_bytes = self.pop_stack()?;
        let n_keys_bn = self.read_count(&n_keys_bytes)?;
        let n_keys = n_keys_bn.to_i64().unwrap_or(-1);

        if !(0..=MAX_MULTISIG_KEY_COUNT).contains(&n_keys) {
            return Err(self.error(&format!(
                "{} requires a key count between 0 and {}.",
                opcode_to_name(opcode).unwrap_or("OP_CHECKMULTISIG"),
                MAX_MULTISIG_KEY_COUNT
            )));
        }
        let n_keys = n_keys as usize;

        // Get public keys
        if self.stack.len() < n_keys {
            return Err(self.error(&format!(
                "{} stack too small for keys. Need {}, have {}.",
                opcode_to_name(opcode).unwrap_or("OP_CHECKMULTISIG"),
                n_keys,
                self.stack.len()
            )));
        }

        let mut pubkeys = Vec::with_capacity(n_keys);
        for _ in 0..n_keys {
            pubkeys.push(self.pop_stack()?);
        }

        // Get number of signatures
        if self.stack.is_empty() {
            return Err(self.error(&format!(
                "{} requires item for nSigs.",
                opcode_to_name(opcode).unwrap_or("OP_CHECKMULTISIG")
            )));
        }

        let n_sigs_bytes = self.pop_stack()?;
        let n_sigs_bn = self.read_count(&n_sigs_bytes)?;
        let n_sigs = n_sigs_bn.to_i64().unwrap_or(-1);

        if n_sigs < 0 || n_sigs as usize > n_keys {
            return Err(self.error(&format!(
                "{} requires the number of signatures to be no greater than the number of keys.",
                opcode_to_name(opcode).unwrap_or("OP_CHECKMULTISIG")
            )));
        }
        let n_sigs = n_sigs as usize;

        // Get signatures
        if self.stack.len() < n_sigs {
            return Err(self.error(&format!(
                "{} stack too small for sigs. Need {}, have {}.",
                opcode_to_name(opcode).unwrap_or("OP_CHECKMULTISIG"),
                n_sigs,
                self.stack.len()
            )));
        }

        let mut sigs = Vec::with_capacity(n_sigs);
        for _ in 0..n_sigs {
            sigs.push(self.pop_stack()?);
        }

        // Build subscript and remove all signatures
        let base_script = match self.context {
            ExecutionContext::UnlockingScript => self.unlocking_script.as_script().clone(),
            ExecutionContext::LockingScript => self.locking_script.as_script().clone(),
        };
        let start_idx = self.last_code_separator.map(|i| i + 1).unwrap_or(0);
        let chunks = base_script.chunks();
        let mut subscript_chunks: Vec<ScriptChunk> = chunks.into_iter().skip(start_idx).collect();
        // See build_subscript: unlock-context subscripts continue into the
        // full locking script (combined-script semantics, ts-sdk parity).
        if self.context == ExecutionContext::UnlockingScript {
            subscript_chunks.extend(self.locking_script.as_script().chunks());
        }
        let mut subscript = Script::from_chunks(subscript_chunks);

        // CleanupScriptCode (interpreter.cpp:255-263, applied per signature at
        // 1573-1578): a signature's push is deleted from the scriptCode only when
        // it does not carry SIGHASH_FORKID; FORKID is always enabled here, so
        // only an empty signature (no hash type) is deleted, as an OP_0 push.
        for sig in &sigs {
            if !has_forkid_bit(sig) {
                let mut sig_script = Script::new();
                sig_script.write_bin(sig);
                subscript.find_and_delete(&sig_script);
            }
        }

        // Verify signatures
        let mut success = true;
        let mut sig_idx = 0;
        let mut key_idx = 0;

        while success && sig_idx < n_sigs {
            if key_idx >= n_keys {
                success = false;
                break;
            }

            let sig_bytes = &sigs[sig_idx];
            let pubkey_bytes = &pubkeys[key_idx];

            // Validate encodings
            if self.check_signature_encoding(sig_bytes).is_err()
                || self.check_public_key_encoding(pubkey_bytes).is_err()
            {
                return Err(self.error(&format!(
                    "{} requires correct encoding for the public key and signature.",
                    opcode_to_name(opcode).unwrap_or("OP_CHECKMULTISIG")
                )));
            }

            let sig_valid = if sig_bytes.is_empty() {
                false
            } else {
                self.verify_signature(sig_bytes, pubkey_bytes, &subscript)
                    .unwrap_or(false)
            };

            if sig_valid {
                sig_idx += 1;
            }
            key_idx += 1;

            if n_sigs - sig_idx > n_keys - key_idx {
                success = false;
            }
        }

        // NULLFAIL (interpreter.cpp:1640-1646, under the version gate): when
        // the operation fails, every signature must be the empty vector.
        if !success && self.require_null_fail && sigs.iter().any(|s| !s.is_empty()) {
            return Err(self.error(&format!(
                "{} requires failing signatures to be empty.",
                opcode_to_name(opcode).unwrap_or("OP_CHECKMULTISIG")
            )));
        }

        // Pop the dummy element. NULLDUMMY (interpreter.cpp:1664-1670, under
        // the version gate) requires it to be empty.
        if self.stack.is_empty() {
            return Err(self.error(&format!(
                "{} requires an extra item (dummy) to be on the stack.",
                opcode_to_name(opcode).unwrap_or("OP_CHECKMULTISIG")
            )));
        }
        let dummy = self.pop_stack()?;
        if self.require_null_dummy && !dummy.is_empty() {
            return Err(self.error(&format!(
                "{} requires the extra stack item (dummy) to be empty.",
                opcode_to_name(opcode).unwrap_or("OP_CHECKMULTISIG")
            )));
        }

        self.push_stack(if success { vec![1] } else { vec![] })?;

        if opcode == OP_CHECKMULTISIGVERIFY {
            if !success {
                return Err(self.error(
                    "OP_CHECKMULTISIGVERIFY requires that a sufficient number of valid signatures are provided.",
                ));
            }
            self.pop_stack()?;
        }

        Ok(())
    }

    // ========================================================================
    // Signature Verification Helpers
    // ========================================================================

    fn check_signature_encoding(&self, sig: &[u8]) -> Result<(), ScriptEvaluationError> {
        if sig.is_empty() {
            return Ok(());
        }

        // Check basic DER format
        if !is_valid_signature_encoding(sig) {
            return Err(self.error("The signature format is invalid."));
        }

        // Parse and check additional requirements
        let tx_sig = TransactionSignature::from_checksig_format(sig)
            .map_err(|_| self.error("The signature format is invalid."))?;

        // LOW_S as the reference checks it (`CPubKey::CheckLowS`, pubkey.cpp:356-365):
        // the lax parser (146-173) turns an `r` or `s` at or above the curve order
        // into the zero signature, which is low, so the check passes and the
        // signature fails to verify afterwards (NULLFAIL under the flag, else a
        // false top). Only n/2 < s < n is a high-S refusal.
        if self.require_low_s && !tx_sig.has_low_s() && !signature_overflows_the_order(&tx_sig) {
            return Err(self.error("The signature must have a low S value."));
        }

        if (tx_sig.scope() & SIGHASH_FORKID) == 0 {
            return Err(self.error("The signature must use SIGHASH_FORKID."));
        }

        Ok(())
    }

    fn check_public_key_encoding(&self, pubkey: &[u8]) -> Result<(), ScriptEvaluationError> {
        if pubkey.is_empty() {
            return Err(self.error("Public key is empty."));
        }

        if pubkey.len() < 33 {
            return Err(self.error("The public key is too short, it must be at least 33 bytes."));
        }

        if pubkey[0] == 0x04 {
            if pubkey.len() != 65 {
                return Err(self.error("The non-compressed public key must be 65 bytes."));
            }
        } else if pubkey[0] == 0x02 || pubkey[0] == 0x03 {
            if pubkey.len() != 33 {
                return Err(self.error("The compressed public key must be 33 bytes."));
            }
        } else {
            return Err(self.error("The public key is in an unknown format."));
        }

        // COMPRESSED_PUBKEYTYPE (interpreter.cpp:322-327): only compressed
        // keys are accepted under the flag.
        if self.require_compressed_pubkey && pubkey[0] == 0x04 {
            return Err(self.error("The public key must be compressed."));
        }

        // Try to parse it
        PublicKey::from_bytes(pubkey)
            .map_err(|_| self.error("The public key is in an unknown format."))?;

        Ok(())
    }

    fn build_subscript(&self, sig_bytes: &[u8]) -> Result<Script, ScriptEvaluationError> {
        let base_script = match self.context {
            ExecutionContext::UnlockingScript => self.unlocking_script.as_script().clone(),
            ExecutionContext::LockingScript => self.locking_script.as_script().clone(),
        };

        let start_idx = self.last_code_separator.map(|i| i + 1).unwrap_or(0);
        let chunks = base_script.chunks();
        let mut subscript_chunks: Vec<ScriptChunk> = chunks.into_iter().skip(start_idx).collect();
        // When a CHECKSIG executes in the unlocking script, the subscript
        // continues across the unlock/lock boundary into the full locking
        // script (legacy combined-script semantics; matches BSV node consensus
        // and ts-sdk). Without this, signatures taken over such a subscript
        // (e.g. OP_PUSH_TX-style contracts) are wrongly rejected.
        if self.context == ExecutionContext::UnlockingScript {
            subscript_chunks.extend(self.locking_script.as_script().chunks());
        }
        let mut subscript = Script::from_chunks(subscript_chunks);

        // CleanupScriptCode (interpreter.cpp:255-263, applied at 1484): the
        // signature's push is deleted from the scriptCode only when the
        // signature does not carry SIGHASH_FORKID (FORKID is always enabled
        // here). A signature that does is hashed with its own push in place, so
        // a signature whose push appears in the scriptCode cannot verify, as on
        // the reference. An empty signature carries no hash type and is deleted
        // as an OP_0 push, as on the reference.
        if !has_forkid_bit(sig_bytes) {
            let mut sig_script = Script::new();
            sig_script.write_bin(sig_bytes);
            subscript.find_and_delete(&sig_script);
        }

        Ok(subscript)
    }

    /// `OP_SUBSTR`, `OP_LEFT`, `OP_RIGHT`, `OP_LSHIFTNUM`, `OP_RSHIFTNUM` at
    /// `0xb3`-`0xb7` for a UTXO created after Chronicle (`interpreter.cpp:609-764`).
    /// The two shifts act on script NUMBERS (not on bytes, unlike `OP_LSHIFT`);
    /// a left shift whose result would not fit the memory budget is refused
    /// before it is computed (a local budget; the reference's bound is its
    /// consensus number length, `SCRIPTNUM_OVERFLOW`).
    fn op_chronicle_splice(&mut self, opcode: u8) -> Result<(), ScriptEvaluationError> {
        let name = match opcode {
            OP_NOP4 => "OP_SUBSTR",
            OP_NOP5 => "OP_LEFT",
            OP_NOP6 => "OP_RIGHT",
            OP_NOP7 => "OP_LSHIFTNUM",
            _ => "OP_RSHIFTNUM",
        };
        let need = if opcode == OP_NOP4 { 3 } else { 2 };
        if self.stack.len() < need {
            return Err(self.error(&format!(
                "{name} requires at least {} items to be on the stack.",
                if need == 3 { "three" } else { "two" }
            )));
        }
        let num = |s: &Self, bytes: &[u8]| -> Result<BigNumber, ScriptEvaluationError> {
            s.read_number(bytes)
        };
        match opcode {
            OP_NOP4 => {
                // (data offset len -- data[offset..offset+len])
                let len_bytes = self.pop_stack()?;
                let off_bytes = self.pop_stack()?;
                let len = num(self, &len_bytes)?.to_i64().unwrap_or(-1);
                let offset = num(self, &off_bytes)?.to_i64().unwrap_or(-1);
                let data = self.pop_stack()?;
                let size = data.len() as i64;
                if offset < 0 || offset >= size || len < 0 || len > size - offset {
                    return Err(self.error(&format!(
                        "OP_SUBSTR offset ({offset}) must be in range [0, {size}) and length ({len}) must be in range [0, {}]",
                        size - offset
                    )));
                }
                let (o, l) = (offset as usize, len as usize);
                self.push_stack(data[o..o + l].to_vec())?;
            }
            OP_NOP5 | OP_NOP6 => {
                // (data len -- the first / last len bytes)
                let len_bytes = self.pop_stack()?;
                let len = num(self, &len_bytes)?.to_i64().unwrap_or(-1);
                let data = self.pop_stack()?;
                let size = data.len() as i64;
                if len < 0 || len > size {
                    return Err(self.error(&format!(
                        "{name} length ({len}) must be in range [0, {size}]"
                    )));
                }
                let l = len as usize;
                let out = if opcode == OP_NOP5 {
                    data[..l].to_vec()
                } else {
                    data[data.len() - l..].to_vec()
                };
                self.push_stack(out)?;
            }
            _ => {
                // (x n -- x << n) / (x n -- x >> n), on script numbers
                let n_bytes = self.pop_stack()?;
                let n_bn = num(self, &n_bytes)?;
                if n_bn.is_negative() {
                    return Err(self.error(&format!("{name} bits to shift must not be negative.")));
                }
                let x_bytes = self.pop_stack()?;
                let x = num(self, &x_bytes)?;
                let n = n_bn.to_i64().map(|v| v as u64).unwrap_or(u64::MAX);
                let out = if opcode == OP_NOP7 {
                    // the result's size, before allocating it: a LOCAL budget
                    let bits = (x.bit_length() as u64).saturating_add(n);
                    let bytes = (bits / 8 + 2) as usize;
                    if !x.is_zero() && bytes > self.memory_limit {
                        return Err(self.resource_error(ScriptResource::ElementSize, bytes));
                    }
                    if x.is_zero() {
                        x
                    } else {
                        x.shl_bits(n)
                    }
                } else if n >= x.bit_length() as u64 {
                    BigNumber::zero()
                } else {
                    x.shr_bits_toward_zero(n)
                };
                self.push_number(&out)?;
            }
        }
        Ok(())
    }

    fn verify_signature(
        &self,
        sig_bytes: &[u8],
        pubkey_bytes: &[u8],
        subscript: &Script,
    ) -> Result<bool, ScriptEvaluationError> {
        // Parse signature and public key
        let tx_sig = match TransactionSignature::from_checksig_format(sig_bytes) {
            Ok(s) => s,
            Err(_) => return Ok(false),
        };

        let pubkey = match PublicKey::from_bytes(pubkey_bytes) {
            Ok(p) => p,
            Err(_) => return Ok(false),
        };

        // Build inputs array for sighash
        let inputs = self.build_inputs_array();

        // Compute sighash
        let sighash = compute_sighash_for_signing(&SighashParams {
            version: self.transaction_version,
            inputs: &inputs,
            outputs: &self.outputs,
            locktime: self.lock_time,
            input_index: self.input_index,
            subscript: &subscript.to_binary(),
            satoshis: self.source_satoshis,
            scope: tx_sig.scope(),
        });

        // Verify
        Ok(pubkey.verify(&sighash, tx_sig.signature()))
    }

    fn build_inputs_array(&self) -> Vec<TxInput> {
        let mut inputs = Vec::with_capacity(self.other_inputs.len() + 1);

        // Add other inputs
        for (i, other) in self.other_inputs.iter().enumerate() {
            if i == self.input_index {
                // Insert our input at the correct position
                inputs.push(TxInput {
                    txid: self.source_txid,
                    output_index: self.source_output_index,
                    script: self.unlocking_script.to_binary(),
                    sequence: self.input_sequence,
                });
            }
            inputs.push(other.clone());
        }

        // Handle case where our input is at the end or other_inputs is empty
        if self.input_index >= self.other_inputs.len() {
            inputs.push(TxInput {
                txid: self.source_txid,
                output_index: self.source_output_index,
                script: self.unlocking_script.to_binary(),
                sequence: self.input_sequence,
            });
        }

        inputs
    }

    // ========================================================================
    // Stack Helpers
    // ========================================================================

    fn push_stack(&mut self, item: Vec<u8>) -> Result<(), ScriptEvaluationError> {
        self.ensure_stack_mem(item.len())?;
        self.stack_mem += item.len();
        self.stack.push(item);
        Ok(())
    }

    fn push_stack_copy(&mut self, item: &[u8]) -> Result<(), ScriptEvaluationError> {
        self.push_stack(item.to_vec())
    }

    fn pop_stack(&mut self) -> Result<Vec<u8>, ScriptEvaluationError> {
        if self.stack.is_empty() {
            return Err(self.error("Attempted to pop from an empty stack."));
        }
        let item = self.stack.pop().unwrap();
        self.stack_mem -= item.len();
        Ok(item)
    }

    fn stack_top(&self) -> Result<&Vec<u8>, ScriptEvaluationError> {
        if self.stack.is_empty() {
            return Err(self.error("Stack is empty."));
        }
        Ok(&self.stack[self.stack.len() - 1])
    }

    fn stack_top_n(&self, n: usize) -> Result<&Vec<u8>, ScriptEvaluationError> {
        if self.stack.len() < n {
            return Err(self.error(&format!(
                "Stack underflow accessing element at index {}. Stack length is {}.",
                n,
                self.stack.len()
            )));
        }
        Ok(&self.stack[self.stack.len() - n])
    }

    fn push_alt_stack(&mut self, item: Vec<u8>) -> Result<(), ScriptEvaluationError> {
        self.ensure_alt_stack_mem(item.len())?;
        self.alt_stack_mem += item.len();
        self.alt_stack.push(item);
        Ok(())
    }

    fn pop_alt_stack(&mut self) -> Result<Vec<u8>, ScriptEvaluationError> {
        if self.alt_stack.is_empty() {
            return Err(self.error("Attempted to pop from an empty alt stack."));
        }
        let item = self.alt_stack.pop().unwrap();
        self.alt_stack_mem -= item.len();
        Ok(item)
    }

    fn ensure_stack_mem(&self, additional: usize) -> Result<(), ScriptEvaluationError> {
        if self.stack_mem + additional > self.memory_limit {
            return Err(self.resource_error(ScriptResource::Stack, self.stack_mem + additional));
        }
        Ok(())
    }

    fn ensure_alt_stack_mem(&self, additional: usize) -> Result<(), ScriptEvaluationError> {
        if self.alt_stack_mem + additional > self.memory_limit {
            return Err(
                self.resource_error(ScriptResource::AltStack, self.alt_stack_mem + additional)
            );
        }
        Ok(())
    }

    /// A LOCAL resource-limit error (the reference's `ScriptResourceLimitError`):
    /// the same message shape (`<label> has exceeded <limit> bytes`) plus the
    /// structured `resource_limit` a caller can branch on.
    fn resource_error(&self, resource: ScriptResource, attempted: usize) -> ScriptEvaluationError {
        let label = match resource {
            ScriptResource::Stack => "Stack memory usage",
            ScriptResource::AltStack => "Alt stack memory usage",
            ScriptResource::ElementSize => "Script element allocation",
        };
        self.error(&format!("{label} has exceeded {} bytes", self.memory_limit))
            .with_resource_limit(ScriptResourceLimit {
                resource,
                limit: self.memory_limit,
                attempted,
            })
    }

    // ========================================================================
    // Script numbers under the length limit
    // ========================================================================

    /// Decodes a stack element as a script number under `limit`: the length
    /// test precedes the decode and the minimal-encoding check, as on the
    /// reference (`script_num.cpp:62-68`; `SCRIPT_ERR_SCRIPTNUM_OVERFLOW`,
    /// `interpreter.cpp:1807-1810`).
    fn read_number_within(
        &self,
        bytes: &[u8],
        limit: Option<usize>,
    ) -> Result<BigNumber, ScriptEvaluationError> {
        if let Some(max) = limit {
            if bytes.len() > max {
                return Err(self.overflow_error(bytes.len(), max));
            }
        }
        ScriptNum::from_bytes(bytes, self.require_minimal)
            .map_err(|e| self.error(&format!("Invalid script number: {}", e)))
    }

    /// A script number read under the limit in force
    /// ([`max_script_num_length`](Self::max_script_num_length)).
    fn read_number(&self, bytes: &[u8]) -> Result<BigNumber, ScriptEvaluationError> {
        self.read_number_within(bytes, self.max_script_num_length())
    }

    /// `OP_CHECKMULTISIG`'s two counts: 4-byte numbers in every era
    /// (`CScriptNum::MAXIMUM_ELEMENT_SIZE`, `interpreter.cpp:1519-1525`,
    /// `1550-1552`) under a word; the default mode reads them as the
    /// TypeScript SDK does.
    fn read_count(&self, bytes: &[u8]) -> Result<BigNumber, ScriptEvaluationError> {
        self.read_number_within(bytes, self.flags.map(|_| 4))
    }

    /// Pushes a computed number, refusing one longer than the limit in force
    /// before it reaches the stack (the reference bounds the results of `+`,
    /// `-`, `*` and the numeric shifts: `script_num.cpp:164`, `194`, `214`,
    /// `301-315`).
    fn push_number(&mut self, value: &BigNumber) -> Result<(), ScriptEvaluationError> {
        let bytes = ScriptNum::to_bytes(value);
        if let Some(max) = self.max_script_num_length() {
            if bytes.len() > max {
                return Err(self.overflow_error(bytes.len(), max));
            }
        }
        self.push_stack(bytes)
    }

    fn overflow_error(&self, len: usize, max: usize) -> ScriptEvaluationError {
        self.error(&format!(
            "Script number overflow: {len} bytes, the limit is {max} bytes."
        ))
    }

    // ========================================================================
    // Error Helpers
    // ========================================================================

    fn error(&self, message: &str) -> ScriptEvaluationError {
        ScriptEvaluationError::new(
            message,
            to_hex(&self.source_txid),
            self.source_output_index,
            self.context,
            self.program_counter,
            self.stack.clone(),
            self.alt_stack.clone(),
            self.if_stack.clone(),
            self.stack_mem,
            self.alt_stack_mem,
        )
    }
}

// ============================================================================
// Helper Functions
// ============================================================================

/// `IsOpcodeDisabled` (interpreter.cpp:360-375): `OP_2MUL` and `OP_2DIV`
/// unless the UTXO was created after Chronicle. `OP_VER`, `OP_VERIF` and
/// `OP_VERNOTIF` are not "disabled" there but `BAD_OPCODE` when executed
/// before Chronicle, handled in their arms.
fn is_opcode_disabled(op: u8, utxo_after_chronicle: bool) -> bool {
    !utxo_after_chronicle && matches!(op, OP_2MUL | OP_2DIV)
}

/// Whether the signature's `r` or `s` is at or above the curve order: the
/// reference's lax DER parse (`ecdsa_signature_parse_der_lax`, pubkey.cpp:146-173)
/// overwrites such a signature with the all-zero one, which is low for
/// `CheckLowS` (356-365) and never verifies.
fn signature_overflows_the_order(sig: &TransactionSignature) -> bool {
    let n = BigNumber::secp256k1_order();
    BigNumber::from_bytes_be(sig.r()) >= n || BigNumber::from_bytes_be(sig.s()) >= n
}

/// Whether a signature's hash type carries `SIGHASH_FORKID`; an empty
/// signature has no hash type (`GetHashType`, interpreter.cpp:246-252).
fn has_forkid_bit(sig: &[u8]) -> bool {
    sig.last().is_some_and(|t| t & (SIGHASH_FORKID as u8) != 0)
}

/// Checks if a chunk uses minimal push encoding.
fn is_chunk_minimal_push(chunk: &ScriptChunk) -> bool {
    let data = match &chunk.data {
        Some(d) => d,
        None => return true,
    };
    let op = chunk.op;

    if data.is_empty() {
        return op == OP_0;
    }

    if data.len() == 1 && data[0] >= 1 && data[0] <= 16 {
        return op == OP_1 + (data[0] - 1);
    }

    if data.len() == 1 && data[0] == 0x81 {
        return op == OP_1NEGATE;
    }

    if data.len() <= 75 {
        return op as usize == data.len();
    }

    if data.len() <= 255 {
        return op == OP_PUSHDATA1;
    }

    if data.len() <= 65535 {
        return op == OP_PUSHDATA2;
    }

    true
}

/// Validates DER signature encoding (simplified check).
fn is_valid_signature_encoding(sig: &[u8]) -> bool {
    if sig.len() < 9 || sig.len() > 73 {
        return false;
    }

    // Sequence tag
    if sig[0] != 0x30 {
        return false;
    }

    // Length check
    if sig[1] as usize != sig.len() - 3 {
        return false;
    }

    // R value
    if sig[2] != 0x02 {
        return false;
    }

    let r_len = sig[3] as usize;
    if r_len == 0 || 5 + r_len >= sig.len() {
        return false;
    }

    // S value
    let s_offset = 4 + r_len;
    if sig[s_offset] != 0x02 {
        return false;
    }

    let s_len = sig[s_offset + 1] as usize;
    if s_len == 0 {
        return false;
    }

    // Check total length
    if r_len + s_len + 7 != sig.len() {
        return false;
    }

    // Check R not negative
    if (sig[4] & 0x80) != 0 {
        return false;
    }

    // Check R not excessively padded
    if r_len > 1 && sig[4] == 0x00 && (sig[5] & 0x80) == 0 {
        return false;
    }

    // Check S not negative
    let s_value_offset = s_offset + 2;
    if (sig[s_value_offset] & 0x80) != 0 {
        return false;
    }

    // Check S not excessively padded
    if s_len > 1 && sig[s_value_offset] == 0x00 && (sig[s_value_offset + 1] & 0x80) == 0 {
        return false;
    }

    true
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_is_opcode_disabled() {
        assert!(is_opcode_disabled(OP_2MUL, false));
        assert!(is_opcode_disabled(OP_2DIV, false));
        assert!(!is_opcode_disabled(OP_2MUL, true));
        assert!(!is_opcode_disabled(OP_2DIV, true));
        // BAD_OPCODE in their arms, not "disabled" (interpreter.cpp:360-375)
        assert!(!is_opcode_disabled(OP_VER, false));
        assert!(!is_opcode_disabled(OP_VERIF, false));
        assert!(!is_opcode_disabled(OP_VERNOTIF, false));

        assert!(!is_opcode_disabled(OP_DUP, false));
        assert!(!is_opcode_disabled(OP_MUL, false));
        assert!(!is_opcode_disabled(OP_CAT, false));
    }

    #[test]
    fn test_is_chunk_minimal_push() {
        // OP_0 for empty data
        let chunk = ScriptChunk::new(OP_0, Some(vec![]));
        assert!(is_chunk_minimal_push(&chunk));

        // Direct push for small data
        let chunk = ScriptChunk::new(3, Some(vec![1, 2, 3]));
        assert!(is_chunk_minimal_push(&chunk));

        // OP_1 for [1]
        let chunk = ScriptChunk::new(OP_1, Some(vec![1]));
        assert!(is_chunk_minimal_push(&chunk));

        // Non-minimal: using push opcode for [1] instead of OP_1
        let chunk = ScriptChunk::new(1, Some(vec![1]));
        assert!(!is_chunk_minimal_push(&chunk));
    }

    #[test]
    fn test_simple_stack_script() {
        // Test: OP_1 OP_2 OP_ADD OP_3 OP_EQUAL
        // Should leave [1] on stack (true)
        let locking = LockingScript::from_asm("OP_ADD OP_3 OP_EQUAL").unwrap();
        let unlocking = UnlockingScript::from_asm("OP_1 OP_2").unwrap();

        let mut spend = Spend::new(SpendParams {
            source_txid: [0u8; 32],
            source_output_index: 0,
            source_satoshis: 0,
            locking_script: locking,
            transaction_version: 1,
            other_inputs: vec![],
            outputs: vec![],
            input_index: 0,
            unlocking_script: unlocking,
            input_sequence: 0xffffffff,
            lock_time: 0,
            memory_limit: None,
        });

        let result = spend.validate();
        assert!(result.is_ok(), "Expected valid spend, got {:?}", result);
    }

    #[test]
    fn test_if_else_endif() {
        // Test: OP_1 OP_IF OP_2 OP_ELSE OP_3 OP_ENDIF
        // Should push 2 (true branch)
        let locking = LockingScript::from_asm("OP_IF OP_2 OP_ELSE OP_3 OP_ENDIF").unwrap();
        let unlocking = UnlockingScript::from_asm("OP_1").unwrap();

        let mut spend = Spend::new(SpendParams {
            source_txid: [0u8; 32],
            source_output_index: 0,
            source_satoshis: 0,
            locking_script: locking,
            transaction_version: 1,
            other_inputs: vec![],
            outputs: vec![],
            input_index: 0,
            unlocking_script: unlocking,
            input_sequence: 0xffffffff,
            lock_time: 0,
            memory_limit: None,
        });

        let result = spend.validate();
        assert!(result.is_ok(), "Expected valid spend, got {:?}", result);
    }

    #[test]
    fn test_hash_operations() {
        // Test that hash operations work
        // SHA256 produces 32 bytes, we check the size is 32 (0x20)
        // Use NIP to remove the hash after SIZE, leaving just the size to compare
        let locking = LockingScript::from_asm("OP_SHA256 OP_SIZE OP_NIP 20 OP_EQUAL").unwrap();
        let unlocking = UnlockingScript::from_asm("00").unwrap();

        let mut spend = Spend::new(SpendParams {
            source_txid: [0u8; 32],
            source_output_index: 0,
            source_satoshis: 0,
            locking_script: locking,
            transaction_version: 1,
            other_inputs: vec![],
            outputs: vec![],
            input_index: 0,
            unlocking_script: unlocking,
            input_sequence: 0xffffffff,
            lock_time: 0,
            memory_limit: None,
        });

        let result = spend.validate();
        assert!(result.is_ok(), "Expected valid spend, got {:?}", result);
    }

    #[test]
    fn test_failing_script() {
        // Test: just OP_0 should fail (stack has falsy value)
        let locking = LockingScript::from_asm("OP_0").unwrap();
        let unlocking = UnlockingScript::new();

        let mut spend = Spend::new(SpendParams {
            source_txid: [0u8; 32],
            source_output_index: 0,
            source_satoshis: 0,
            locking_script: locking,
            transaction_version: 1,
            other_inputs: vec![],
            outputs: vec![],
            input_index: 0,
            unlocking_script: unlocking,
            input_sequence: 0xffffffff,
            lock_time: 0,
            memory_limit: None,
        });

        let result = spend.validate();
        assert!(result.is_err(), "Expected failed validation");
    }
}

/// The flag words on the interpreter: every gate `set_flags` derives, exercised
/// on the smallest script that reaches it, against the TypeScript default
/// mode. The reference sites are cited in `flags.rs`.
#[cfg(test)]
mod flag_tests {
    use super::*;
    use crate::primitives::from_hex;
    use crate::script::flags::ProtocolEra;

    /// A compressed public key and a well-formed low-S signature with the
    /// FORKID hash type that does not verify in any context below.
    const PUBKEY: &str = "035935f55855afd8c999bdb5a8d08ae8e73b7618e200d4ef7687cd55d3c2e4c9d7";
    const WRONG_SIG: &str = "304402204bbb723c10080132ef81641e0e9963eb77782bf50c149f0f15c6d7b8e263464e02207f18ea8fdff74fb4d4d2dc677555fb1c94cf6219fe4bb4c40162e1e270f8924941";

    fn spend(lock_asm: &str, unlock_asm: &str, version: i32) -> Spend {
        Spend::new(SpendParams {
            source_txid: [0u8; 32],
            source_output_index: 0,
            source_satoshis: 1000,
            locking_script: LockingScript::from_asm(lock_asm).unwrap(),
            transaction_version: version,
            other_inputs: vec![],
            outputs: vec![],
            input_index: 0,
            unlocking_script: UnlockingScript::from_asm(unlock_asm).unwrap(),
            input_sequence: 0xffff_ffff,
            lock_time: 0,
            memory_limit: None,
        })
    }

    fn with_flags(lock_asm: &str, unlock_asm: &str, version: i32, flags: ScriptFlags) -> Spend {
        let mut s = spend(lock_asm, unlock_asm, version);
        s.set_flags(flags);
        s
    }

    fn message(r: Result<bool, ScriptEvaluationError>) -> String {
        r.expect_err("expected a refusal").message
    }

    fn valid(r: Result<bool, ScriptEvaluationError>) -> bool {
        matches!(r, Ok(true))
    }

    fn block() -> ScriptFlags {
        ScriptFlags::block(ProtocolEra::PostChronicle)
    }

    fn standard() -> ScriptFlags {
        ScriptFlags::standard(ProtocolEra::PostChronicle)
    }

    #[test]
    fn nullfail_refuses_a_failing_non_empty_checksig_signature_at_version_1_under_the_block_word() {
        let lock = format!("{PUBKEY} OP_CHECKSIG OP_NOT");
        // Version 1: NULLFAIL is mandatory and the gate is on.
        let msg = message(with_flags(&lock, WRONG_SIG, 1, block()).validate());
        assert_eq!(msg, "OP_CHECKSIG requires failing signatures to be empty.");
        // Version 2 post-Chronicle: the gate is off, the negated failure is a true top.
        assert!(valid(with_flags(&lock, WRONG_SIG, 2, block()).validate()));
        // Before Chronicle the gate is always on.
        assert!(with_flags(
            &lock,
            WRONG_SIG,
            2,
            ScriptFlags::block(ProtocolEra::PostGenesis)
        )
        .validate()
        .is_err());
        // An empty signature is what NULLFAIL asks for.
        assert!(valid(with_flags(&lock, "0", 1, block()).validate()));
        // The TypeScript default mode has no NULLFAIL rule.
        assert!(valid(spend(&lock, WRONG_SIG, 1).validate()));
    }

    #[test]
    fn nullfail_refuses_a_failing_checkmultisig_with_any_non_empty_signature_at_version_1() {
        let lock = format!("OP_1 {PUBKEY} OP_1 OP_CHECKMULTISIG OP_NOT");
        let msg = message(with_flags(&lock, &format!("0 {WRONG_SIG}"), 1, block()).validate());
        assert_eq!(
            msg,
            "OP_CHECKMULTISIG requires failing signatures to be empty."
        );
        assert!(valid(with_flags(&lock, "0 0", 1, block()).validate()));
        assert!(valid(
            with_flags(&lock, &format!("0 {WRONG_SIG}"), 2, block()).validate()
        ));
        assert!(valid(spend(&lock, &format!("0 {WRONG_SIG}"), 1).validate()));
    }

    #[test]
    fn nulldummy_is_a_standard_only_rule_gated_on_the_version() {
        // 0-of-0 multisig: only the dummy is consumed; OP_1 as the dummy.
        let lock = "OP_0 OP_0 OP_CHECKMULTISIG";
        // The block word never carries NULLDUMMY.
        assert!(valid(with_flags(lock, "OP_1", 1, block()).validate()));
        // The standard word does, under the gate: version 1 refused, version 2 accepted.
        let msg = message(with_flags(lock, "OP_1", 1, standard()).validate());
        assert_eq!(
            msg,
            "OP_CHECKMULTISIG requires the extra stack item (dummy) to be empty."
        );
        assert!(valid(with_flags(lock, "OP_1", 2, standard()).validate()));
        assert!(with_flags(
            lock,
            "OP_1",
            2,
            ScriptFlags::standard(ProtocolEra::PostGenesis)
        )
        .validate()
        .is_err());
        // The TypeScript default mode: strict at version 1, relaxed at version 2.
        assert!(spend(lock, "OP_1", 1).validate().is_err());
        assert!(valid(spend(lock, "OP_1", 2).validate()));
        // An empty dummy passes everywhere.
        assert!(valid(with_flags(lock, "0", 1, standard()).validate()));
    }

    #[test]
    fn minimaldata_low_s_and_cleanstack_follow_the_word_and_the_gate() {
        // A non-minimal push of 1 (`01 01` instead of OP_1) leaves a true top.
        let non_minimal = UnlockingScript::from_binary(&[0x01, 0x01]).unwrap();
        let mut s = spend("OP_1 OP_EQUAL", "", 1);
        s = Spend::new(SpendParams {
            unlocking_script: non_minimal.clone(),
            ..params_of(&s)
        });
        assert!(
            s.validate().is_err(),
            "the default mode enforces MINIMALDATA at version 1"
        );
        let mut s = Spend::new(SpendParams {
            unlocking_script: non_minimal.clone(),
            ..params_of(&spend("OP_1 OP_EQUAL", "", 1))
        });
        s.set_flags(block());
        assert!(
            valid(s.validate()),
            "the block word never carries MINIMALDATA"
        );
        let mut s = Spend::new(SpendParams {
            unlocking_script: non_minimal,
            ..params_of(&spend("OP_1 OP_EQUAL", "", 1))
        });
        s.set_flags(standard());
        assert!(
            s.validate().is_err(),
            "the standard word carries it, and version 1 is gated on"
        );

        // Two elements at the end: CLEANSTACK.
        assert!(valid(with_flags("OP_1 OP_1", "", 1, block()).validate()));
        assert!(with_flags("OP_1 OP_1", "", 1, standard())
            .validate()
            .is_err());
        assert!(valid(with_flags("OP_1 OP_1", "", 2, standard()).validate()));
    }

    /// `SpendParams` for a fresh interpreter with the same context as `s`.
    fn params_of(s: &Spend) -> SpendParams {
        SpendParams {
            source_txid: s.source_txid,
            source_output_index: s.source_output_index,
            source_satoshis: s.source_satoshis,
            locking_script: s.locking_script.clone(),
            transaction_version: s.transaction_version,
            other_inputs: s.other_inputs.clone(),
            outputs: s.outputs.clone(),
            input_index: s.input_index,
            unlocking_script: s.unlocking_script.clone(),
            input_sequence: s.input_sequence,
            lock_time: s.lock_time,
            memory_limit: Some(s.memory_limit),
        }
    }

    #[test]
    fn push_only_is_derived_from_the_word_and_the_version() {
        // A non-push opcode in the unlocking script.
        let lock = "OP_1 OP_EQUAL";
        let unlock = "OP_0 OP_1ADD";
        assert!(
            spend(lock, unlock, 2).validate().is_err(),
            "the default mode requires push-only at every version"
        );
        assert!(
            valid(with_flags(lock, unlock, 2, block()).validate()),
            "post-Chronicle, version 2: not required"
        );
        assert!(
            with_flags(lock, unlock, 1, block()).validate().is_err(),
            "post-Chronicle, version 1: required"
        );
        assert!(
            with_flags(
                lock,
                unlock,
                2,
                ScriptFlags::block(ProtocolEra::PostGenesis)
            )
            .validate()
            .is_err(),
            "pre-Chronicle: required at every version"
        );
        // The setter still overrides a derived rule.
        let mut s = with_flags(lock, unlock, 1, block());
        s.set_require_push_only(false);
        assert!(valid(s.validate()));
    }

    #[test]
    fn discourage_upgradable_nops_refuses_an_executed_nop1_to_nop10_under_the_standard_word_only() {
        // 0xb0-0xb2 and 0xb8-0xb9 are NOPs in every era; 0xb3-0xb7 only for a coin created
        // before Chronicle (their Chronicle meanings live under UTXO_AFTER_CHRONICLE), so
        // those are tested under the post-Genesis words.
        for (nop, era) in [
            ("OP_NOP1", ProtocolEra::PostChronicle),
            ("OP_NOP2", ProtocolEra::PostChronicle),
            ("OP_NOP3", ProtocolEra::PostChronicle),
            ("OP_NOP4", ProtocolEra::PostGenesis),
            ("OP_NOP8", ProtocolEra::PostGenesis),
            ("OP_NOP9", ProtocolEra::PostChronicle),
            ("OP_NOP10", ProtocolEra::PostChronicle),
        ] {
            let lock = format!("{nop} OP_1");
            assert!(
                valid(with_flags(&lock, "", 2, ScriptFlags::block(era)).validate()),
                "{nop}: a NOP in a block"
            );
            let msg = message(with_flags(&lock, "", 2, ScriptFlags::standard(era)).validate());
            assert_eq!(msg, format!("{nop} is discouraged by verification flags."));
            assert!(
                valid(spend(&lock, "", 1).validate()),
                "{nop}: the default mode has no such rule"
            );
        }
        // Not executed: not discouraged (interpreter.cpp: the check is inside fExec).
        assert!(valid(
            with_flags("OP_0 OP_IF OP_NOP1 OP_ENDIF OP_1", "", 2, standard()).validate()
        ));
        // OP_NOP itself is never discouraged.
        assert!(valid(
            with_flags("OP_NOP OP_1", "", 2, standard()).validate()
        ));
    }

    #[test]
    fn minimalif_requires_an_empty_or_0x01_argument_under_the_flag_and_the_gate() {
        let word = block() | ScriptFlags::MINIMALIF;
        let lock = "OP_IF OP_1 OP_ELSE OP_0 OP_ENDIF";
        assert!(valid(with_flags(lock, "OP_1", 1, word).validate()));
        let msg = message(with_flags(lock, "OP_2", 1, word).validate());
        assert_eq!(msg, "OP_IF and OP_NOTIF require minimal truth values.");
        assert!(
            valid(with_flags(lock, "OP_2", 2, word).validate()),
            "version 2 post-Chronicle: gated off"
        );
        assert!(
            valid(with_flags(lock, "OP_2", 1, block()).validate()),
            "not in the block word"
        );
        assert!(
            valid(spend(lock, "OP_2", 1).validate()),
            "not in the default mode"
        );
    }

    #[test]
    fn compressed_pubkeytype_refuses_an_uncompressed_key_under_the_flag() {
        // A well-formed uncompressed key (the generator point) with an empty signature:
        // CHECKSIG fails cleanly to false, then OP_NOT makes it true.
        let g = "0479be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8";
        let lock = format!("{g} OP_CHECKSIG OP_NOT");
        assert!(valid(with_flags(&lock, "0", 1, block()).validate()));
        let msg = message(
            with_flags(&lock, "0", 1, block() | ScriptFlags::COMPRESSED_PUBKEYTYPE).validate(),
        );
        assert_eq!(msg, "The public key must be compressed.");
        let compressed = format!("{PUBKEY} OP_CHECKSIG OP_NOT");
        assert!(valid(
            with_flags(
                &compressed,
                "0",
                1,
                block() | ScriptFlags::COMPRESSED_PUBKEYTYPE
            )
            .validate()
        ));
    }

    #[test]
    fn a_word_the_interpreter_cannot_honor_is_refused_by_validate_as_invalid_flags() {
        let word = block().without(ScriptFlags::SIGHASH_FORKID);
        let msg = message(with_flags("OP_1", "", 1, word).validate());
        assert!(
            msg.starts_with("Invalid verification flags: SIGHASH_FORKID is not set"),
            "{msg}"
        );
        let word = (standard() | ScriptFlags::CLEANSTACK).without(ScriptFlags::P2SH);
        let msg = message(with_flags("OP_1", "", 1, word).validate());
        assert!(msg.contains("CLEANSTACK without P2SH"), "{msg}");
        let s = with_flags("OP_1", "", 1, block());
        assert_eq!(s.flags(), Some(block()));
        assert_eq!(spend("OP_1", "", 1).flags(), None);
    }

    #[test]
    fn set_flags_replaces_the_default_switches_and_the_setters_override_afterwards() {
        // The default mode at version 1 enforces MINIMALDATA; the block word does not;
        // `set_require_minimal(true)` after `set_flags` re-enables it.
        let non_minimal = UnlockingScript::from_binary(&[0x01, 0x01]).unwrap();
        let mut s = Spend::new(SpendParams {
            unlocking_script: non_minimal,
            ..params_of(&spend("OP_1 OP_EQUAL", "", 1))
        });
        s.set_flags(block());
        s.set_require_minimal(true);
        assert!(s.validate().is_err());
        let _ = from_hex; // used by the witnesses' integration test; keep the import honest
    }
}

/// The five consensus divergences left after 0.3.26 (Calhooon/bsv-rs#12), each
/// rule on the smallest script that reaches it: the post-Chronicle opcodes and
/// their gate, the single-ELSE rule, a RETURN inside a conditional, truncated
/// pushes, undefined opcodes, and the scriptCode cleanup. Sites in `flags.rs`
/// and at the arms.
#[cfg(test)]
mod chronicle_tests {
    use super::*;
    use crate::script::flags::ProtocolEra;

    fn spend(lock_asm: &str, unlock_asm: &str, version: i32) -> Spend {
        Spend::new(SpendParams {
            source_txid: [0u8; 32],
            source_output_index: 0,
            source_satoshis: 1000,
            locking_script: LockingScript::from_asm(lock_asm).unwrap(),
            transaction_version: version,
            other_inputs: vec![],
            outputs: vec![],
            input_index: 0,
            unlocking_script: UnlockingScript::from_asm(unlock_asm).unwrap(),
            input_sequence: 0xffff_ffff,
            lock_time: 0,
            memory_limit: None,
        })
    }

    fn valid(r: Result<bool, ScriptEvaluationError>) -> bool {
        matches!(r, Ok(true))
    }

    fn message(r: Result<bool, ScriptEvaluationError>) -> String {
        r.expect_err("expected a refusal").message
    }

    #[test]
    fn substr_left_and_right_take_ranges_after_chronicle_and_refuse_out_of_range_ones() {
        // 0xb3 OP_SUBSTR (data offset len), 0xb4 OP_LEFT, 0xb5 OP_RIGHT (data len)
        assert!(valid(
            spend("OP_1 OP_2 OP_NOP4 bbcc OP_EQUAL", "aabbccdd", 2).validate()
        ));
        assert!(valid(
            spend("OP_2 OP_NOP5 aabb OP_EQUAL", "aabbccdd", 2).validate()
        ));
        assert!(valid(
            spend("OP_2 OP_NOP6 ccdd OP_EQUAL", "aabbccdd", 2).validate()
        ));
        assert!(valid(
            spend("OP_0 OP_NOP5 OP_0 OP_EQUAL", "aabbccdd", 2).validate()
        ));
        assert_eq!(
            message(spend("OP_5 OP_NOP5", "aabbccdd", 2).validate()),
            "OP_LEFT length (5) must be in range [0, 4]"
        );
        assert_eq!(
            message(spend("OP_4 OP_0 OP_NOP4", "aabbccdd", 2).validate()),
            "OP_SUBSTR offset (4) must be in range [0, 4) and length (0) must be in range [0, 0]"
        );
        assert!(
            message(spend("OP_1 OP_4 OP_NOP4", "aabbccdd", 2).validate())
                .starts_with("OP_SUBSTR offset (1)")
        );
        assert!(
            message(spend("OP_1NEGATE OP_NOP6", "aabbccdd", 2).validate())
                .contains("OP_RIGHT length (-1)")
        );
    }

    #[test]
    fn lshiftnum_and_rshiftnum_shift_script_numbers_toward_zero() {
        // 0xb6 OP_LSHIFTNUM, 0xb7 OP_RSHIFTNUM: (x n -- out) on numbers
        assert!(valid(
            spend("OP_1 OP_NOP7 OP_14 OP_EQUAL", "OP_7", 2).validate()
        ));
        assert!(valid(
            spend("OP_10 OP_NOP7 0004 OP_EQUAL", "OP_1", 2).validate()
        )); // 1 << 10 = 1024 = 0x0400 LE
            // -7 >> 1 is -3 (toward zero; 0x87 is -7, 0x83 is -3), not -4
        assert!(valid(spend("OP_1 OP_NOP8 83 OP_EQUAL", "87", 2).validate()));
        assert!(valid(
            spend("OP_1 OP_NOP8 OP_3 OP_EQUAL", "OP_7", 2).validate()
        ));
        // a shift past every bit is zero (the empty number)
        assert!(valid(
            spend("OP_16 OP_NOP8 OP_0 OP_EQUAL", "OP_7", 2).validate()
        ));
        assert!(valid(
            spend("OP_16 OP_NOP8 OP_0 OP_EQUAL", "87", 2).validate()
        ));
        // zero shifted left stays zero
        assert!(valid(
            spend("OP_16 OP_NOP7 OP_0 OP_EQUAL", "OP_0", 2).validate()
        ));
        assert_eq!(
            message(spend("OP_1NEGATE OP_NOP7", "OP_7", 2).validate()),
            "OP_LSHIFTNUM bits to shift must not be negative."
        );
        assert_eq!(
            message(spend("OP_1NEGATE OP_NOP8", "OP_7", 2).validate()),
            "OP_RSHIFTNUM bits to shift must not be negative."
        );
    }

    #[test]
    fn lshiftnum_refuses_a_result_beyond_the_memory_budget_before_computing_it() {
        let mut s = Spend::new(SpendParams {
            source_txid: [0u8; 32],
            source_output_index: 0,
            source_satoshis: 1000,
            locking_script: LockingScript::from_asm("2823 OP_NOP7").unwrap(), // 0x2328 = 9000 bits
            transaction_version: 2,
            other_inputs: vec![],
            outputs: vec![],
            input_index: 0,
            unlocking_script: UnlockingScript::from_asm("OP_1").unwrap(),
            input_sequence: 0xffff_ffff,
            lock_time: 0,
            memory_limit: Some(1000),
        });
        let err = s.validate().unwrap_err();
        assert!(err.is_resource_limit(), "{}", err.message);
        assert_eq!(
            err.resource_limit.unwrap().resource,
            ScriptResource::ElementSize
        );
    }

    #[test]
    fn before_chronicle_0xb3_to_0xb7_are_nops_and_discouraged_under_the_standard_word() {
        // version 1 in the default mode: the UTXO is taken as pre-Chronicle
        assert!(valid(
            spend("OP_NOP4 OP_NOP5 OP_NOP6 OP_NOP7 OP_NOP8", "OP_1", 1).validate()
        ));
        let mut s = spend("OP_NOP7 OP_1", "", 2);
        s.set_flags(ScriptFlags::standard(ProtocolEra::PostGenesis));
        assert_eq!(
            message(s.validate()),
            "OP_NOP7 is discouraged by verification flags."
        );
        // the block word of a post-Chronicle coin turns them on even at version 1
        let mut s = spend("OP_1 OP_NOP7 OP_14 OP_EQUAL", "OP_7", 1);
        s.set_flags(ScriptFlags::block(ProtocolEra::PostChronicle));
        assert!(valid(s.validate()));
        // and the setter overrides either way
        let mut s = spend("OP_1 OP_NOP7 OP_14 OP_EQUAL", "OP_7", 1);
        s.set_utxo_after_chronicle(true);
        assert!(valid(s.validate()));
    }

    #[test]
    fn op_ver_pushes_the_version_after_chronicle_and_is_refused_before() {
        assert!(valid(spend("OP_VER 02000000 OP_EQUAL", "", 2).validate()));
        assert_eq!(
            message(spend("OP_VER", "", 1).validate()),
            "OP_VER is disabled until Chronicle."
        );
        let mut s = spend("OP_VER 01000000 OP_EQUAL", "", 1);
        s.set_flags(ScriptFlags::block(ProtocolEra::PostChronicle));
        assert!(valid(s.validate()));
        // not executed: nothing happens, before or after Chronicle
        assert!(valid(
            spend("OP_0 OP_IF OP_VER OP_ENDIF OP_1", "", 1).validate()
        ));
    }

    #[test]
    fn op_verif_compares_the_top_with_the_version_and_is_skipped_or_refused_before_chronicle() {
        assert!(valid(
            spend("OP_VERIF OP_1 OP_ELSE OP_0 OP_ENDIF", "02000000", 2).validate()
        ));
        assert!(!valid(
            spend("OP_VERIF OP_1 OP_ELSE OP_0 OP_ENDIF", "01000000", 2).validate()
        ));
        // only an exactly 4-byte element can match; OP_2 (one byte) does not
        assert!(valid(
            spend("OP_VERIF OP_0 OP_ELSE OP_1 OP_ENDIF", "OP_2", 2).validate()
        ));
        assert!(valid(
            spend("OP_VERNOTIF OP_1 OP_ELSE OP_0 OP_ENDIF", "01000000", 2).validate()
        ));
        assert!(valid(
            spend("OP_VERNOTIF OP_0 OP_ELSE OP_1 OP_ENDIF", "02000000", 2).validate()
        ));
        // before Chronicle: executed is refused, not executed is skipped (no conditional pushed)
        assert_eq!(
            message(spend("OP_VERIF OP_1 OP_ENDIF", "02000000", 1).validate()),
            "OP_VERIF is disabled until Chronicle."
        );
        assert!(valid(
            spend("OP_0 OP_IF OP_VERIF OP_ENDIF OP_1", "", 1).validate()
        ));
        assert!(valid(
            spend("OP_0 OP_IF OP_VERNOTIF OP_ENDIF OP_1", "", 1).validate()
        ));
    }

    #[test]
    fn two_mul_and_two_div_are_disabled_before_chronicle_and_compute_after() {
        assert!(message(spend("OP_2MUL", "OP_7", 1).validate()).contains("currently disabled"));
        assert!(message(spend("OP_2DIV", "OP_7", 1).validate()).contains("currently disabled"));
        assert!(valid(spend("OP_2MUL OP_14 OP_EQUAL", "OP_7", 2).validate()));
        assert!(valid(spend("OP_2DIV OP_3 OP_EQUAL", "OP_7", 2).validate()));
        assert!(valid(spend("OP_2DIV 83 OP_EQUAL", "87", 2).validate())); // -7 / 2 = -3
        assert!(valid(spend("OP_2MUL 8e OP_EQUAL", "87", 2).validate())); // -7 * 2 = -14 (0x8e)
                                                                          // not executed: no refusal before Chronicle either (interpreter.cpp:458-459, post-Genesis)
        assert!(valid(
            spend("OP_0 OP_IF OP_2MUL OP_ENDIF OP_1", "", 1).validate()
        ));
    }

    #[test]
    fn one_op_else_per_op_if_after_genesis() {
        assert!(valid(
            spend("OP_IF OP_1 OP_ELSE OP_0 OP_ENDIF", "OP_1", 2).validate()
        ));
        assert_eq!(
            message(spend("OP_IF OP_1 OP_ELSE OP_1 OP_ELSE OP_1 OP_ENDIF", "OP_1", 2).validate()),
            "OP_ELSE may only be used once for each OP_IF or OP_NOTIF after Genesis."
        );
        // one per level, nested
        assert!(valid(
            spend(
                "OP_IF OP_0 OP_IF OP_ELSE OP_ENDIF OP_ELSE OP_ENDIF OP_1",
                "OP_1",
                2
            )
            .validate()
        ));
        // in every mode: version 1 too
        assert!(
            message(spend("OP_IF OP_ELSE OP_ELSE OP_ENDIF OP_1", "OP_1", 1).validate())
                .contains("only be used once")
        );
    }

    #[test]
    fn a_return_inside_a_conditional_stops_execution_but_the_balance_and_the_parse_still_hold() {
        // execution stops at the RETURN: the OP_0 after it never runs, the ENDIF still closes the IF
        assert!(valid(
            spend("OP_1 OP_IF OP_RETURN OP_0 OP_ENDIF", "OP_1", 2).validate()
        ));
        // the conditional must still balance
        assert!(message(spend("OP_1 OP_IF OP_RETURN", "OP_1", 2).validate())
            .contains("terminated with OP_ENDIF"));
        // an undefined opcode after the RETURN is not executed: fine
        let lock = LockingScript::from_binary(&[0x51, 0x63, 0x6a, 0x68, 0xba]).unwrap();
        let mut s = spend("OP_1", "OP_1", 2);
        s = Spend::new(SpendParams {
            locking_script: lock,
            ..params_of(&s)
        });
        assert!(valid(s.validate()));
        // a truncated push after the RETURN is still a parse failure
        let lock = LockingScript::from_binary(&[0x51, 0x63, 0x6a, 0x68, 0x03, 0x01]).unwrap();
        let mut s = Spend::new(SpendParams {
            locking_script: lock,
            ..params_of(&spend("OP_1", "OP_1", 2))
        });
        assert!(message(s.validate()).starts_with("A push declares more bytes"));
        // a top-level RETURN ends the script successfully, whatever follows
        let lock = LockingScript::from_binary(&[0x51, 0x6a, 0xba, 0x03, 0x01]).unwrap();
        let mut s = Spend::new(SpendParams {
            locking_script: lock,
            ..params_of(&spend("OP_1", "", 2))
        });
        assert!(valid(s.validate()));
    }

    #[test]
    fn an_undefined_opcode_is_refused_only_when_executed() {
        assert!(message(spend("OP_1 OP_NOP77", "", 2).validate()).starts_with("Invalid opcode 252"));
        assert!(valid(
            spend("OP_0 OP_IF OP_NOP77 OP_ENDIF OP_1", "", 2).validate()
        ));
        let lock = LockingScript::from_binary(&[0x51, 0xba]).unwrap();
        let mut s = Spend::new(SpendParams {
            locking_script: lock,
            ..params_of(&spend("OP_1", "", 1))
        });
        assert!(message(s.validate()).starts_with("Invalid opcode 186"));
    }

    #[test]
    fn a_truncated_push_is_refused_where_the_walk_reaches_it_even_unexecuted() {
        // OP_0 OP_IF <push 3 with 1 byte>: the branch does not execute, the parse still fails there
        let lock = LockingScript::from_binary(&[0x00, 0x63, 0x03, 0x01]).unwrap();
        assert_eq!(lock.as_script().truncated_push(), Some(2));
        let mut s = Spend::new(SpendParams {
            locking_script: lock,
            ..params_of(&spend("OP_1", "", 2))
        });
        assert!(message(s.validate()).contains("(pc=2)"));
        // a complete script has no truncated push; bytes after a top-level RETURN are data
        assert_eq!(
            Script::from_binary(&[0x51, 0x03, 0x01, 0x02, 0x03])
                .unwrap()
                .truncated_push(),
            None
        );
        assert_eq!(
            Script::from_binary(&[0x6a, 0x03, 0x01])
                .unwrap()
                .truncated_push(),
            None
        );
        assert_eq!(
            Script::from_binary(&[0x4c]).unwrap().truncated_push(),
            Some(0)
        );
        assert_eq!(
            Script::from_binary(&[0x51, 0x4d, 0x01])
                .unwrap()
                .truncated_push(),
            Some(1)
        );
        assert_eq!(
            Script::from_binary(&[0x4e, 0x01, 0x00, 0x00, 0x00])
                .unwrap()
                .truncated_push(),
            Some(0)
        );
        assert_eq!(
            Script::from_binary(&[0x4e, 0x01, 0x00, 0x00, 0x00, 0xaa])
                .unwrap()
                .truncated_push(),
            None
        );
        // an earlier failure wins: the walk never reaches the truncated push
        let lock = LockingScript::from_binary(&[0x69, 0x03, 0x01]).unwrap(); // OP_VERIFY on an empty stack
        let mut s = Spend::new(SpendParams {
            locking_script: lock,
            ..params_of(&spend("OP_1", "", 2))
        });
        assert!(message(s.validate()).contains("OP_VERIFY requires"));
    }

    #[test]
    fn the_scriptcode_keeps_a_forkid_signatures_push_and_deletes_an_empty_ones_op_0() {
        let sig = "304402204c9195e05dc41a9119b4cf65f43e450a057818d74c12265faee6a21ae2e0ab87022051c94bb55d9c54d68efaa16785c6ba6a7958757745528974a92d8cddcb993c1241";
        let lock_asm = format!("{sig} OP_DROP OP_1");
        let mut s = spend(&lock_asm, "", 2);
        s.context = ExecutionContext::LockingScript;
        let sig_bytes = crate::primitives::from_hex(sig).unwrap();
        assert!(has_forkid_bit(&sig_bytes));
        let sub = s.build_subscript(&sig_bytes).unwrap();
        assert_eq!(
            sub.to_binary(),
            s.locking_script.to_binary(),
            "a FORKID signature's push stays"
        );
        // an empty signature carries no hash type: its OP_0 push is deleted, as on the reference
        let mut s = spend("OP_0 OP_1 OP_0", "", 2);
        s.context = ExecutionContext::LockingScript;
        assert!(!has_forkid_bit(&[]));
        let sub = s.build_subscript(&[]).unwrap();
        assert_eq!(sub.to_asm(), "OP_1");
        // a signature without the FORKID bit would be deleted (and is refused by the encoding check)
        assert!(!has_forkid_bit(&[
            0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01
        ]));
    }

    /// `SpendParams` for a fresh interpreter with the same context as `s`.
    fn params_of(s: &Spend) -> SpendParams {
        SpendParams {
            source_txid: s.source_txid,
            source_output_index: s.source_output_index,
            source_satoshis: s.source_satoshis,
            locking_script: s.locking_script.clone(),
            transaction_version: s.transaction_version,
            other_inputs: s.other_inputs.clone(),
            outputs: s.outputs.clone(),
            input_index: s.input_index,
            unlocking_script: s.unlocking_script.clone(),
            input_sequence: s.input_sequence,
            lock_time: s.lock_time,
            memory_limit: Some(s.memory_limit),
        }
    }
}

/// The low-S check at the curve order (Calhooon/bsv-rs#14): an `r` or `s` at or
/// above the order is the zero signature for the reference's lax parse, which
/// is low; only n/2 < s < n is a high-S refusal.
#[cfg(test)]
mod low_s_order_tests {
    use super::*;

    const N: &str = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141";
    const HALF: &str = "7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0";

    /// A strict-DER signature (r, s as 32-byte big-endian hex) with the FORKID hash type.
    fn der(r: &str, s: &str) -> Vec<u8> {
        fn int(hex: &str) -> Vec<u8> {
            let mut v = crate::primitives::from_hex(hex).unwrap();
            while v.len() > 1 && v[0] == 0 && v[1] & 0x80 == 0 {
                v.remove(0);
            }
            if v[0] & 0x80 != 0 {
                v.insert(0, 0);
            }
            let mut out = vec![0x02, v.len() as u8];
            out.extend(v);
            out
        }
        let body = [int(r), int(s)].concat();
        let mut out = vec![0x30, body.len() as u8];
        out.extend(body);
        out.push(0x41);
        out
    }

    fn checker() -> Spend {
        Spend::new(SpendParams {
            source_txid: [0u8; 32],
            source_output_index: 0,
            source_satoshis: 1000,
            locking_script: LockingScript::from_asm("OP_1").unwrap(),
            transaction_version: 1, // the default mode at version 1 requires low S
            other_inputs: vec![],
            outputs: vec![],
            input_index: 0,
            unlocking_script: UnlockingScript::new(),
            input_sequence: 0xffff_ffff,
            lock_time: 0,
            memory_limit: None,
        })
    }

    fn s_plus(hex: &str, k: u64) -> String {
        let v = BigNumber::from_bytes_be(&crate::primitives::from_hex(hex).unwrap())
            .add(&BigNumber::from_i64(k as i64));
        crate::primitives::to_hex(&v.to_bytes_be(32))
    }

    #[test]
    fn s_at_or_above_the_order_passes_the_low_s_check_as_the_zero_signature() {
        let one = "0000000000000000000000000000000000000000000000000000000000000001";
        let c = checker();
        assert!(c.check_signature_encoding(&der(one, N)).is_ok(), "s = n");
        assert!(
            c.check_signature_encoding(&der(one, &s_plus(N, 1))).is_ok(),
            "s = n + 1"
        );
        assert!(c.check_signature_encoding(&der(N, one)).is_ok(), "r = n");
        // the boundary: n/2 is low, n/2 + 1 through n - 1 are high
        assert!(
            c.check_signature_encoding(&der(one, HALF)).is_ok(),
            "s = n/2"
        );
        let high = c
            .check_signature_encoding(&der(one, &s_plus(HALF, 1)))
            .unwrap_err();
        assert_eq!(high.message, "The signature must have a low S value.");
        let n_minus_1 = "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364140";
        assert_eq!(
            c.check_signature_encoding(&der(one, n_minus_1))
                .unwrap_err()
                .message,
            "The signature must have a low S value."
        );
        // and such a signature never verifies: a CHECKSIG with s = n at version 1 under the
        // block word is NULLFAIL, in the default mode a false top
        let pk = "035935f55855afd8c999bdb5a8d08ae8e73b7618e200d4ef7687cd55d3c2e4c9d7";
        let sig_hex = crate::primitives::to_hex(&der(one, N));
        let mut spend = Spend::new(SpendParams {
            source_txid: [0u8; 32],
            source_output_index: 0,
            source_satoshis: 1000,
            locking_script: LockingScript::from_asm(&format!("{pk} OP_CHECKSIG")).unwrap(),
            transaction_version: 1,
            other_inputs: vec![],
            outputs: vec![],
            input_index: 0,
            unlocking_script: UnlockingScript::from_asm(&sig_hex).unwrap(),
            input_sequence: 0xffff_ffff,
            lock_time: 0,
            memory_limit: None,
        });
        spend.set_flags(ScriptFlags::block(
            crate::script::flags::ProtocolEra::PostChronicle,
        ));
        assert_eq!(
            spend.validate().unwrap_err().message,
            "OP_CHECKSIG requires failing signatures to be empty."
        );
    }
}

#[cfg(test)]
mod script_num_length_tests {
    use super::*;
    use crate::primitives::to_hex;
    use crate::script::flags::ProtocolEra;

    const PUBKEY: &str = "035935f55855afd8c999bdb5a8d08ae8e73b7618e200d4ef7687cd55d3c2e4c9d7";

    /// A minimal push of `n` as a script number (always under 76 bytes here).
    fn push_num(lock: &mut Vec<u8>, n: u64) {
        let bytes = ScriptNum::to_bytes(&BigNumber::from_u64(n));
        lock.push(bytes.len() as u8);
        lock.extend_from_slice(&bytes);
    }

    /// `OP_1 <n> OP_NUM2BIN OP_1ADD OP_DROP OP_1`: OP_1ADD reads an n-byte
    /// number (the value 1, padded).
    fn read_n_bytes(n: u64) -> Vec<u8> {
        let mut lock = vec![OP_1];
        push_num(&mut lock, n);
        lock.extend_from_slice(&[OP_NUM2BIN, OP_1ADD, OP_DROP, OP_1]);
        lock
    }

    /// `OP_1 <n> OP_NUM2BIN <0x40> OP_CAT OP_DUP OP_MUL OP_DROP OP_1`: two
    /// (n + 1)-byte operands whose product is about 2(n + 1) bytes long.
    fn square_of_n_plus_one_bytes(n: u64) -> Vec<u8> {
        let mut lock = vec![OP_1];
        push_num(&mut lock, n);
        lock.extend_from_slice(&[
            OP_NUM2BIN, 0x01, 0x40, OP_CAT, OP_DUP, OP_MUL, OP_DROP, OP_1,
        ]);
        lock
    }

    /// `OP_1 <n> OP_NUM2BIN <0x40> OP_CAT OP_BIN2NUM OP_DROP OP_1`: OP_BIN2NUM's
    /// result is (n + 1) bytes long and minimal.
    fn bin2num_of_n_plus_one_bytes(n: u64) -> Vec<u8> {
        let mut lock = vec![OP_1];
        push_num(&mut lock, n);
        lock.extend_from_slice(&[OP_NUM2BIN, 0x01, 0x40, OP_CAT, OP_BIN2NUM, OP_DROP, OP_1]);
        lock
    }

    /// `OP_0 OP_0 <pubkey> <count as `len` bytes> OP_CHECKMULTISIG`: zero
    /// signatures of one key, the key count encoded non-minimally.
    fn checkmultisig_with_a_count_of(len: u8) -> Vec<u8> {
        let mut lock = vec![OP_0, OP_0, 0x21];
        lock.extend_from_slice(&crate::primitives::from_hex(PUBKEY).unwrap());
        lock.push(len);
        lock.push(0x01);
        lock.extend_from_slice(&vec![0u8; len as usize - 1]);
        lock.push(OP_CHECKMULTISIG);
        lock
    }

    fn spend(lock: &[u8], version: i32) -> Spend {
        Spend::new(SpendParams {
            source_txid: [0u8; 32],
            source_output_index: 0,
            source_satoshis: 1000,
            locking_script: LockingScript::from_hex(&to_hex(lock)).unwrap(),
            transaction_version: version,
            other_inputs: vec![],
            outputs: vec![],
            input_index: 0,
            unlocking_script: UnlockingScript::from_binary(&[]).unwrap(),
            input_sequence: 0xffff_ffff,
            lock_time: 0,
            memory_limit: Some(200_000_000),
        })
    }

    fn block() -> ScriptFlags {
        ScriptFlags::block(ProtocolEra::PostChronicle)
    }

    fn standard() -> ScriptFlags {
        ScriptFlags::standard(ProtocolEra::PostChronicle)
    }

    /// The verdict as a string: `Ok(true)`, or the refusal's message.
    fn run(
        lock: &[u8],
        version: i32,
        word: Option<ScriptFlags>,
        utxo_after_chronicle: Option<bool>,
        policy: Option<usize>,
    ) -> String {
        let mut s = spend(lock, version);
        if let Some(w) = word {
            s.set_flags(w);
        }
        if let Some(after) = utxo_after_chronicle {
            s.set_utxo_after_chronicle(after);
        }
        if let Some(bytes) = policy {
            s.set_script_num_length_policy(bytes);
        }
        match s.validate() {
            Ok(v) => format!("Ok({v})"),
            Err(e) => e.message,
        }
    }

    fn overflow(len: usize, max: usize) -> String {
        format!("Script number overflow: {len} bytes, the limit is {max} bytes.")
    }

    #[test]
    fn the_word_and_the_coins_era_decide_the_limit() {
        assert!(!block().is_mempool_word());
        assert!(standard().is_mempool_word());
        assert_eq!(block().max_script_num_length(false, 10_000), 750_000);
        assert_eq!(block().max_script_num_length(true, 10_000), 32_000_000);
        assert_eq!(standard().max_script_num_length(false, 10_000), 10_000);
        assert_eq!(standard().max_script_num_length(true, 10_000), 10_000);
        assert_eq!(standard().max_script_num_length(false, 0), 750_000);
        assert_eq!(standard().max_script_num_length(true, 0), 32_000_000);

        let lock = read_n_bytes(1);
        assert_eq!(spend(&lock, 2).max_script_num_length(), None);
        let mut s = spend(&lock, 2);
        s.set_flags(block());
        assert_eq!(s.max_script_num_length(), Some(32_000_000));
        s.set_utxo_after_chronicle(false);
        assert_eq!(s.max_script_num_length(), Some(750_000));
        s.set_flags(standard());
        assert_eq!(s.max_script_num_length(), Some(10_000));
        s.set_script_num_length_policy(0);
        assert_eq!(s.max_script_num_length(), Some(32_000_000));
    }

    /// A coin created after Genesis, before Chronicle, on the block path:
    /// 750,000 bytes read, 750,001 refused (`consensus.h:64`).
    #[test]
    fn a_coin_created_after_genesis_reads_750_000_bytes_and_refuses_750_001_under_the_block_word() {
        assert_eq!(
            run(&read_n_bytes(750_000), 2, Some(block()), Some(false), None),
            "Ok(true)"
        );
        assert_eq!(
            run(&read_n_bytes(750_001), 2, Some(block()), Some(false), None),
            overflow(750_001, 750_000)
        );
    }

    /// A coin created after Chronicle, on the block path: 32,000,000 bytes
    /// read, 32,000,001 refused (`consensus.h:66`).
    #[test]
    fn a_coin_created_after_chronicle_reads_32_000_000_bytes_and_refuses_32_000_001() {
        assert_eq!(
            run(
                &read_n_bytes(32_000_000),
                2,
                Some(block()),
                Some(true),
                None
            ),
            "Ok(true)"
        );
        assert_eq!(
            run(
                &read_n_bytes(32_000_001),
                2,
                Some(block()),
                Some(true),
                None
            ),
            overflow(32_000_001, 32_000_000)
        );
    }

    /// The mempool path: the policy default of 10,000 bytes whatever the
    /// coin's era (`policy.h:156`); a policy of 0 selects the consensus limit.
    #[test]
    fn the_standard_word_applies_the_policy_default_in_both_eras_and_zero_selects_the_consensus_limit(
    ) {
        for after in [false, true] {
            assert_eq!(
                run(
                    &read_n_bytes(10_000),
                    2,
                    Some(standard()),
                    Some(after),
                    None
                ),
                "Ok(true)"
            );
            assert_eq!(
                run(
                    &read_n_bytes(10_001),
                    2,
                    Some(standard()),
                    Some(after),
                    None
                ),
                overflow(10_001, 10_000)
            );
        }
        assert_eq!(
            run(
                &read_n_bytes(750_000),
                2,
                Some(standard()),
                Some(false),
                Some(0)
            ),
            "Ok(true)"
        );
        assert_eq!(
            run(
                &read_n_bytes(750_001),
                2,
                Some(standard()),
                Some(false),
                Some(0)
            ),
            overflow(750_001, 750_000)
        );
        assert_eq!(
            run(
                &read_n_bytes(20_000),
                2,
                Some(standard()),
                Some(false),
                Some(20_000)
            ),
            "Ok(true)"
        );
        assert_eq!(
            run(
                &read_n_bytes(20_001),
                2,
                Some(standard()),
                Some(false),
                Some(20_000)
            ),
            overflow(20_001, 20_000)
        );
    }

    /// The length test precedes the minimal-encoding test
    /// (`script_num.cpp:62` before `:67`): at version 1 under the standard
    /// word a padded number of 10,000 bytes is a minimal-encoding refusal,
    /// one of 10,001 bytes an overflow.
    #[test]
    fn the_length_test_precedes_the_minimal_encoding_test() {
        assert_eq!(
            run(
                &read_n_bytes(10_000),
                1,
                Some(standard()),
                Some(false),
                None
            ),
            "Invalid script number: script execution error: Non-minimally encoded script number"
        );
        assert_eq!(
            run(
                &read_n_bytes(10_001),
                1,
                Some(standard()),
                Some(false),
                None
            ),
            overflow(10_001, 10_000)
        );
    }

    /// A product longer than the limit is refused before it is pushed
    /// (`script_num.cpp:214`); one within it is pushed.
    #[test]
    fn a_product_longer_than_the_limit_is_refused_before_it_is_pushed() {
        assert_eq!(
            run(
                &square_of_n_plus_one_bytes(369_999),
                2,
                Some(block()),
                Some(false),
                None
            ),
            "Ok(true)"
        );
        let refused = run(
            &square_of_n_plus_one_bytes(379_999),
            2,
            Some(block()),
            Some(false),
            None,
        );
        assert!(
            refused.starts_with("Script number overflow: 7")
                && refused.ends_with("the limit is 750000 bytes."),
            "{refused}"
        );
    }

    /// `OP_BIN2NUM`'s result beyond the limit is refused as the reference
    /// refuses it (`interpreter.cpp:1789-1790`).
    #[test]
    fn bin2num_refuses_a_result_longer_than_the_limit() {
        assert_eq!(
            run(
                &bin2num_of_n_plus_one_bytes(9_999),
                2,
                Some(standard()),
                Some(false),
                None
            ),
            "Ok(true)"
        );
        assert_eq!(
            run(
                &bin2num_of_n_plus_one_bytes(10_000),
                2,
                Some(standard()),
                Some(false),
                None
            ),
            "OP_BIN2NUM requires that the resulting number is valid."
        );
    }

    /// `OP_CHECKMULTISIG`'s counts are 4-byte numbers under a word
    /// (`interpreter.cpp:1519-1525`); the default mode reads them as the
    /// TypeScript SDK does.
    #[test]
    fn a_five_byte_checkmultisig_count_is_an_overflow_under_a_word() {
        assert_eq!(
            run(
                &checkmultisig_with_a_count_of(4),
                2,
                Some(block()),
                Some(false),
                None
            ),
            "Ok(true)"
        );
        assert_eq!(
            run(
                &checkmultisig_with_a_count_of(5),
                2,
                Some(block()),
                Some(false),
                None
            ),
            overflow(5, 4)
        );
        assert_eq!(
            run(&checkmultisig_with_a_count_of(5), 2, None, None, None),
            "Ok(true)"
        );
    }

    /// The default mode is the TypeScript SDK's: a number of any length.
    #[test]
    fn the_default_mode_reads_a_number_of_any_length() {
        assert_eq!(
            run(&read_n_bytes(1_048_577), 2, None, None, None),
            "Ok(true)"
        );
    }
}