kaspa-txscript 2.1.0

Kaspa txscript engine library
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
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
#[macro_use]
mod macros;
use crate::MAX_SCRIPT_ELEMENT_SIZE;
use crate::zk_precompiles::{parse_tag, verify_zk};
use crate::{
    LOCK_TIME_THRESHOLD, MAX_TX_IN_SEQUENCE_NUM, NO_COST_OPCODE, SEQUENCE_LOCK_TIME_DISABLED, SEQUENCE_LOCK_TIME_MASK, ScriptSource,
    SpkEncoding, TxScriptEngine, TxScriptError,
    data_stack::{OpcodeData, StackEntry, serialize_i64},
};
use blake2b_simd::Params;
use kaspa_consensus_core::hashing::sighash::SigHashReusedValues;
use kaspa_consensus_core::hashing::sighash_type::SigHashType;
use kaspa_consensus_core::mass::ScriptUnits;
use kaspa_consensus_core::tx::VerifiableTransaction;
use kaspa_hashes::Hash;
use kaspa_hashes::ZERO_HASH;
use kaspa_utils::hex::FromHex;
use sha2::{Digest, Sha256};
use std::{
    fmt::{Debug, Formatter},
    num::TryFromIntError,
};

/// First value in the range formed by the "small integer" Op# opcodes
pub const OP_SMALL_INT_MIN_VAL: u8 = 1;
/// Last value in the range formed by the "small integer" Op# opcodes
pub const OP_SMALL_INT_MAX_VAL: u8 = 16;
/// First value in the range formed by OpData# opcodes (where opcode == value)
pub const OP_DATA_MIN_VAL: u8 = self::codes::OpData1;
/// Last value in the range formed by OpData# opcodes (where opcode == value)
pub const OP_DATA_MAX_VAL: u8 = self::codes::OpData75;
/// Minus 1 value
pub const OP_1_NEGATE_VAL: u8 = 0x81;

#[derive(Debug, PartialEq, Eq)]
pub(crate) enum OpCond {
    False,
    True,
    Skip,
}

impl OpCond {
    pub fn negate(&self) -> OpCond {
        match self {
            OpCond::True => OpCond::False,
            OpCond::False => OpCond::True,
            OpCond::Skip => OpCond::Skip,
        }
    }
}

type OpCodeResult = Result<(), TxScriptError>;

#[derive(Copy, Clone)]
enum HashOpcodePricing {
    Blake2b,
    Blake3,
    Sha256,
}

impl HashOpcodePricing {
    const fn units_per_byte(self) -> u64 {
        match self {
            Self::Blake2b => 2,
            Self::Blake3 => 1,
            Self::Sha256 => 1,
        }
    }

    fn script_units_for_data(self, data_len: usize) -> ScriptUnits {
        ScriptUnits((data_len as u64).saturating_mul(self.units_per_byte()))
    }
}

pub(crate) struct OpCode<const CODE: u8> {
    data: Vec<u8>,
}

impl<const CODE: u8> Debug for OpCode<CODE> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "Opcode<{:#2x}>{{ data:{:?} }}", CODE, self.data)
    }
}

pub trait OpCodeMetadata: Debug {
    // Opcode number
    fn value(&self) -> u8;
    // length of data
    fn len(&self) -> usize;
    // Conditional should be executed also is not in branch
    fn is_conditional(&self) -> bool;

    fn is_disabled(&self) -> bool;
    fn always_illegal(&self) -> bool;
    fn is_push_opcode(&self) -> bool;
    fn get_data(&self) -> &[u8];

    fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

pub trait OpCodeExecution<T: VerifiableTransaction, Reused: SigHashReusedValues> {
    fn empty() -> Result<Box<dyn OpCodeImplementation<T, Reused>>, TxScriptError>
    where
        Self: Sized;
    #[allow(clippy::new_ret_no_self)]
    fn new(data: Vec<u8>) -> Result<Box<dyn OpCodeImplementation<T, Reused>>, TxScriptError>
    where
        Self: Sized;

    fn execute(&self, vm: &mut TxScriptEngine<T, Reused>) -> OpCodeResult;
}

pub trait OpcodeSerialization {
    fn serialize(&self) -> Vec<u8>;
    fn deserialize<'i, I: Iterator<Item = &'i u8>, T: VerifiableTransaction, Reused: SigHashReusedValues>(
        it: &mut I,
    ) -> Result<Box<dyn OpCodeImplementation<T, Reused>>, TxScriptError>
    where
        Self: Sized;
}

pub trait OpCodeImplementation<T: VerifiableTransaction, Reused: SigHashReusedValues>:
    OpCodeExecution<T, Reused> + OpCodeMetadata + OpcodeSerialization + std::fmt::Display
{
}

impl<const CODE: u8> OpCodeMetadata for OpCode<CODE> {
    fn value(&self) -> u8 {
        CODE
    }

    fn is_disabled(&self) -> bool {
        matches!(CODE, codes::OpLeft | codes::OpRight | codes::Op2Mul | codes::Op2Div | codes::OpLShift | codes::OpRShift)
    }

    fn always_illegal(&self) -> bool {
        matches!(CODE, codes::OpVerIf | codes::OpVerNotIf)
    }

    fn is_push_opcode(&self) -> bool {
        CODE <= NO_COST_OPCODE
    }

    fn len(&self) -> usize {
        self.data.len()
    }

    // TODO: add it to opcode specification
    fn is_conditional(&self) -> bool {
        self.value() >= 0x63 && self.value() <= 0x68
    }

    fn get_data(&self) -> &[u8] {
        &self.data
    }
}

// Helpers for some opcodes with shared data
// Literal opcode data is already paid for in script size, so it does not consume script units.
#[inline]
fn push_literal_data<T: VerifiableTransaction, Reused: SigHashReusedValues>(
    data: Vec<u8>,
    vm: &mut TxScriptEngine<T, Reused>,
) -> OpCodeResult {
    vm.dstack.push_unmetered(data.into())
}

#[inline]
fn push_data<T: VerifiableTransaction, Reused: SigHashReusedValues>(
    data: Vec<u8>,
    vm: &mut TxScriptEngine<T, Reused>,
) -> OpCodeResult {
    vm.dstack.push(data.into())
}

// Literal opcode numbers are already paid for in script size, so this push does not consume script units.
#[inline]
fn push_literal_number<T: VerifiableTransaction, Reused: SigHashReusedValues>(
    number: i64,
    vm: &mut TxScriptEngine<T, Reused>,
) -> OpCodeResult {
    vm.dstack.push_item_unmetered(number)
}

#[inline]
fn push_number<T: VerifiableTransaction, Reused: SigHashReusedValues>(
    number: i64,
    vm: &mut TxScriptEngine<T, Reused>,
) -> OpCodeResult {
    vm.dstack.push_item(number)?;
    Ok(())
}

fn substring(data: &[u8], start: usize, end: usize) -> Result<Vec<u8>, TxScriptError> {
    let diff = end.checked_sub(start).ok_or(TxScriptError::InvalidRange { start, end })?;
    // Since this function is only used post-Toccata, we can use the post-Toccata max size here.
    if diff > MAX_SCRIPT_ELEMENT_SIZE {
        return Err(TxScriptError::ElementTooBig(diff, MAX_SCRIPT_ELEMENT_SIZE));
    }
    data.get(start..end).map(<[u8]>::to_vec).ok_or(TxScriptError::OutOfBoundsSubstring(start, end, data.len()))
}

pub(crate) fn i32_to_usize(value: i32) -> Result<usize, TxScriptError> {
    value.try_into().map_err(|_| TxScriptError::InvalidIndex(value))
}

pub(crate) fn i32s_to_usizes<const N: usize>(arr: [i32; N]) -> Result<[usize; N], TxScriptError> {
    let mut out = [0usize; N];
    for i in 0..N {
        out[i] = i32_to_usize(arr[i])?;
    }
    Ok(out)
}

/*
The following is the implementation and metadata of all opcodes. Each opcode has unique
number (and template system makes it impossible to use two opcodes), length specification,
and execution code.

The syntax is as follows:
```
opcode OpCodeName<id, length>(self, vm) {
    code;
    output
}
// OR
opcode OpCodeName<id, length>(self, vm) statement

// in case of an opcode alias
opcode |OpCodeAlias| OpCodeName<id, length>(self, vm) {
    code;
    output
}
// OR
opcode |OpCodeAlias| OpCodeName<id, length>(self, vm) statement
```

Length specification is either a number (for fixed length) or a unsigned integer type
(for var length).
The execution code is implementing OpCodeImplementation. You can access the engine using the `vm`
variable.

Implementation details in `opcodes/macros.rs`.
*/
opcode_list! {

    // Data push opcodes.
    opcode |Op0| OpFalse<0x00, 1>(self , vm) {
        push_literal_data(vec![], vm)
    }

    opcode OpData1<0x01, 2>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData2<0x02, 3>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData3<0x03, 4>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData4<0x04, 5>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData5<0x05, 6>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData6<0x06, 7>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData7<0x07, 8>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData8<0x08, 9>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData9<0x09, 10>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData10<0x0a, 11>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData11<0x0b, 12>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData12<0x0c, 13>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData13<0x0d, 14>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData14<0x0e, 15>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData15<0x0f, 16>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData16<0x10, 17>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData17<0x11, 18>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData18<0x12, 19>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData19<0x13, 20>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData20<0x14, 21>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData21<0x15, 22>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData22<0x16, 23>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData23<0x17, 24>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData24<0x18, 25>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData25<0x19, 26>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData26<0x1a, 27>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData27<0x1b, 28>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData28<0x1c, 29>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData29<0x1d, 30>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData30<0x1e, 31>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData31<0x1f, 32>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData32<0x20, 33>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData33<0x21, 34>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData34<0x22, 35>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData35<0x23, 36>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData36<0x24, 37>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData37<0x25, 38>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData38<0x26, 39>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData39<0x27, 40>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData40<0x28, 41>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData41<0x29, 42>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData42<0x2a, 43>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData43<0x2b, 44>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData44<0x2c, 45>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData45<0x2d, 46>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData46<0x2e, 47>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData47<0x2f, 48>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData48<0x30, 49>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData49<0x31, 50>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData50<0x32, 51>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData51<0x33, 52>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData52<0x34, 53>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData53<0x35, 54>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData54<0x36, 55>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData55<0x37, 56>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData56<0x38, 57>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData57<0x39, 58>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData58<0x3a, 59>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData59<0x3b, 60>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData60<0x3c, 61>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData61<0x3d, 62>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData62<0x3e, 63>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData63<0x3f, 64>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData64<0x40, 65>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData65<0x41, 66>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData66<0x42, 67>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData67<0x43, 68>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData68<0x44, 69>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData69<0x45, 70>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData70<0x46, 71>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData71<0x47, 72>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData72<0x48, 73>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData73<0x49, 74>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData74<0x4a, 75>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpData75<0x4b, 76>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpPushData1<0x4c, u8>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpPushData2<0x4d, u16>(self, vm) push_literal_data(self.data.clone(), vm)
    opcode OpPushData4<0x4e, u32>(self, vm) push_literal_data(self.data.clone(), vm)

    opcode Op1Negate<0x4f, 1>(self, vm) push_literal_number(-1, vm)

    opcode OpReserved<0x50, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))

    opcode |Op1| OpTrue<0x51, 1>(self, vm) push_literal_number(1, vm)
    opcode Op2<0x52, 1>(self, vm) push_literal_number(2, vm)
    opcode Op3<0x53, 1>(self, vm) push_literal_number(3, vm)
    opcode Op4<0x54, 1>(self, vm) push_literal_number(4, vm)
    opcode Op5<0x55, 1>(self, vm) push_literal_number(5, vm)
    opcode Op6<0x56, 1>(self, vm) push_literal_number(6, vm)
    opcode Op7<0x57, 1>(self, vm) push_literal_number(7, vm)
    opcode Op8<0x58, 1>(self, vm) push_literal_number(8, vm)
    opcode Op9<0x59, 1>(self, vm) push_literal_number(9, vm)
    opcode Op10<0x5a, 1>(self, vm) push_literal_number(10, vm)
    opcode Op11<0x5b, 1>(self, vm) push_literal_number(11, vm)
    opcode Op12<0x5c, 1>(self, vm) push_literal_number(12, vm)
    opcode Op13<0x5d, 1>(self, vm) push_literal_number(13, vm)
    opcode Op14<0x5e, 1>(self, vm) push_literal_number(14, vm)
    opcode Op15<0x5f, 1>(self, vm) push_literal_number(15, vm)
    opcode Op16<0x60, 1>(self, vm) push_literal_number(16, vm)

    // Control opcodes.
    opcode OpNop<0x61, 1>(self, vm) Ok(())
    opcode OpVer<0x62, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))

    opcode OpIf<0x63, 1>(self, vm) {
        let cond = if vm.is_executing() {
            let [cond]: [bool; 1] = vm.dstack.pop_items()?;
            if cond {
                OpCond::True
            } else {
                OpCond::False
            }
        } else {
            OpCond::Skip
        };

        vm.cond_stack.push(cond);
        Ok(())
    }

    opcode OpNotIf<0x64, 1>(self, vm) {
        let cond = if vm.is_executing() {
            let [cond]: [bool; 1] = vm.dstack.pop_items()?;
            if cond {
                OpCond::False
            } else {
                OpCond::True
            }
        }else{
            OpCond::Skip
        };

        vm.cond_stack.push(cond);
        Ok(())
    }

    opcode OpVerIf<0x65, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
    opcode OpVerNotIf<0x66, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))

    opcode OpElse<0x67, 1>(self, vm) {
        if let Some(cond) = vm.cond_stack.last_mut() {
            *cond = cond.negate();
            Ok(())
        } else {
            Err(TxScriptError::InvalidState("condition stack empty".to_string()))
        }
    }

    opcode OpEndIf<0x68, 1>(self, vm) {
        match vm.cond_stack.pop() {
            None => Err(TxScriptError::InvalidState("condition stack empty".to_string())),
            _ => Ok(())
        }
    }

    opcode OpVerify<0x69, 1>(self, vm) {
        let [result]: [bool; 1] = vm.dstack.pop_items()?;
        match result {
            true => Ok(()),
            false => Err(TxScriptError::VerifyError)
        }
    }

    opcode OpReturn<0x6a, 1>(self, vm) Err(TxScriptError::EarlyReturn)

    // Stack opcodes.
    opcode OpToAltStack<0x6b, 1>(self, vm) {
        let [item] = vm.dstack.pop_raw()?;
        // Pure move between stacks, so we don't consume script units.
        vm.astack.push_unmetered(item)
    }

    opcode OpFromAltStack<0x6c, 1>(self, vm) {
        let last = vm.astack.pop()?;
        // Pure move between stacks, so we don't consume script units.
        vm.dstack.push_unmetered(last)
    }

    opcode Op2Drop<0x6d, 1>(self, vm) vm.dstack.drop_items::<2>()
    opcode Op2Dup<0x6e, 1>(self, vm) vm.dstack.dup_items::<2>()
    opcode Op3Dup<0x6f, 1>(self, vm) vm.dstack.dup_items::<3>()
    opcode Op2Over<0x70, 1>(self, vm) vm.dstack.over_items::<2>()
    opcode Op2Rot<0x71, 1>(self, vm) vm.dstack.rot_items::<2>()
    opcode Op2Swap<0x72, 1>(self, vm) vm.dstack.swap_items::<2>()

    opcode OpIfDup<0x73, 1>(self, vm) {
        let [result] = vm.dstack.peek_raw()?;
        if <StackEntry as OpcodeData<bool>>::deserialize(&result)? {
            vm.dstack.push(result)?;
        }
        Ok(())
    }

    opcode OpDepth<0x74, 1>(self, vm) push_number(vm.dstack.len() as i64, vm)

    opcode OpDrop<0x75, 1>(self, vm) vm.dstack.drop_items::<1>()
    opcode OpDup<0x76, 1>(self, vm) vm.dstack.dup_items::<1>()

    opcode OpNip<0x77, 1>(self, vm) {
        match vm.dstack.len() >= 2 {
            true => {
                vm.dstack.remove(vm.dstack.len()-2);
                Ok(())
            }
            false => Err(TxScriptError::InvalidStackOperation(2, vm.dstack.len())),
        }
    }

    opcode OpOver<0x78, 1>(self, vm) vm.dstack.over_items::<1>()

    opcode OpPick<0x79, 1>(self, vm) {
        let [loc]: [i32; 1] = vm.dstack.pop_items()?;
        if  loc < 0 || loc as usize >= vm.dstack.len() {
            return Err(TxScriptError::InvalidState("pick at an invalid location".to_string()));
        }
        vm.dstack.push(vm.dstack[vm.dstack.len()-(loc as usize)-1].clone())
    }

    opcode OpRoll<0x7a, 1>(self, vm) {
        let [loc]: [i32; 1] = vm.dstack.pop_items()?;
        if  loc < 0 || loc as usize >= vm.dstack.len() {
            return Err(TxScriptError::InvalidState("roll at an invalid location".to_string()));
        }
        vm.dstack.roll(loc as usize)
    }

    opcode OpRot<0x7b, 1>(self, vm) vm.dstack.rot_items::<1>()
    opcode OpSwap<0x7c, 1>(self, vm) vm.dstack.swap_items::<1>()

    opcode OpTuck<0x7d, 1>(self, vm) {
        match vm.dstack.len() >= 2 {
            true => {
                vm.dstack.insert(vm.dstack.len()-2, vm.dstack.last().expect("We have at least two items").clone())?;
                Ok(())
            }
            false => Err(TxScriptError::InvalidStackOperation(2, vm.dstack.len()))
        }
    }

    // Splice opcodes.
    opcode OpCat<0x7e, 1>(self, vm) {
        let b = vm.dstack.pop()?;
        let a = vm.dstack.pop()?;
        let mut r = a;
        r.extend_from_slice(&b);
        vm.dstack.push(r)
    }

    opcode OpSubstr<0x7f, 1>(self, vm) {
        let [start, end] = vm.dstack.pop_items()?;
        let data = vm.dstack.pop()?;
        let [start, end] = i32s_to_usizes([start, end])?;
        let substr = substring(&data, start, end)?;
        vm.dstack.push(substr.into())
    }

    opcode OpLeft<0x80, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
    opcode OpRight<0x81, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))

    opcode OpSize<0x82, 1>(self, vm) {
        match vm.dstack.last() {
            Some(last) => {
                vm.dstack.push_item(i64::try_from(last.len()).map_err(|e| TxScriptError::NumberTooBig(e.to_string()))?)?;
                Ok(())
            },
            None => Err(TxScriptError::InvalidStackOperation(1, 0))
        }
    }

    // Bitwise logic opcodes.
    opcode OpInvert<0x83, 1>(self, vm) {
        let data = vm.dstack.pop()?;
        let r: StackEntry = data.into_iter().map(|b| !b).collect();
        vm.dstack.push(r)
    }

    opcode OpAnd<0x84, 1>(self, vm) {
        let b = vm.dstack.pop()?;
        let a = vm.dstack.pop()?;
        if a.len() != b.len() {
            return Err(TxScriptError::InvalidState("AND operands must be of equal length".to_string()));
        }
        let r: StackEntry = a.into_iter().zip(b.into_iter()).map(|(a_byte, b_byte)| a_byte & b_byte).collect();
        vm.dstack.push(r)
    }

    opcode OpOr<0x85, 1>(self, vm) {
        let b = vm.dstack.pop()?;
        let a = vm.dstack.pop()?;
        if a.len() != b.len() {
            return Err(TxScriptError::InvalidState("OR operands must be of equal length".to_string()));
        }
        let r: StackEntry = a.into_iter().zip(b.into_iter()).map(|(a_byte, b_byte)| a_byte | b_byte).collect();
        vm.dstack.push(r)
    }

    opcode OpXor<0x86, 1>(self, vm) {
        let b = vm.dstack.pop()?;
        let a = vm.dstack.pop()?;
        if a.len() != b.len() {
            return Err(TxScriptError::InvalidState("XOR operands must be of equal length".to_string()));
        }
        let r: StackEntry = a.into_iter().zip(b.into_iter()).map(|(a_byte, b_byte)| a_byte ^ b_byte).collect();
        vm.dstack.push(r)
    }

    opcode OpEqual<0x87, 1>(self, vm) {
        match vm.dstack.len() >= 2 {
            true => {
                let pair = vm.dstack.split_off(vm.dstack.len() - 2);
                match pair[0] == pair[1] {
                    true => vm.dstack.push(([1]).as_slice().into()),
                    false => vm.dstack.push(([]).as_slice().into()),
                }
            }
            false => Err(TxScriptError::InvalidStackOperation(2, vm.dstack.len()))
        }
    }

    opcode OpEqualVerify<0x88, 1>(self, vm) {
        match vm.dstack.len() >= 2 {
            true => {
                let pair = vm.dstack.split_off(vm.dstack.len() - 2);
                match pair[0] == pair[1] {
                    true => Ok(()),
                    false => Err(TxScriptError::VerifyError),
                }
            }
            false => Err(TxScriptError::InvalidStackOperation(2, vm.dstack.len()))
        }
    }

    opcode OpReserved1<0x89, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))
    opcode OpReserved2<0x8a, 1>(self, vm) Err(TxScriptError::OpcodeReserved(format!("{self:?}")))

    // Numeric related opcodes.
    opcode Op1Add<0x8b, 1>(self, vm) {
        let [value]: [i64; 1] = vm.dstack.pop_items()?;
        let r = value.checked_add(1).ok_or_else(|| TxScriptError::NumberTooBig("Result of addition exceeds 64-bit signed integer range".to_string()))?;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode Op1Sub<0x8c, 1>(self, vm) {
        let [value]: [i64; 1] = vm.dstack.pop_items()?;
        let r = value.checked_sub(1).ok_or_else(|| TxScriptError::NumberTooBig("Result of subtraction exceeds 64-bit signed integer range".to_string()))?;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode Op2Mul<0x8d, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
    opcode Op2Div<0x8e, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))

    opcode OpNegate<0x8f, 1>(self, vm) {
        let [value]: [i64; 1] = vm.dstack.pop_items()?;
        let r = value.checked_neg().ok_or_else(|| TxScriptError::NumberTooBig("Negation result exceeds 64-bit signed integer range".to_string()))?;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpAbs<0x90, 1>(self, vm) {
        let [ value ]: [i64; 1] = vm.dstack.pop_items()?;
        let r = value.checked_abs().ok_or_else(|| TxScriptError::NumberTooBig("Absolute value exceeds 64-bit signed integer range".to_string()))?;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpNot<0x91, 1>(self, vm) {
        let [ m ]: [i64; 1] = vm.dstack.pop_items()?;
        let r = (m == 0) as i64;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode Op0NotEqual<0x92, 1>(self, vm) {
        let [ m ]: [i64; 1] = vm.dstack.pop_items()?;
        let r = (m != 0) as i64;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpAdd<0x93, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = a.checked_add(b).ok_or_else(|| TxScriptError::NumberTooBig("Sum exceeds 64-bit signed integer range".to_string()))?;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpSub<0x94, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = a.checked_sub(b).ok_or_else(|| TxScriptError::NumberTooBig("Difference exceeds 64-bit signed integer range".to_string()))?;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpMul<0x95, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = a.checked_mul(b).ok_or_else(|| TxScriptError::NumberTooBig("Product exceeds 64-bit signed integer range".to_string()))?;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpDiv<0x96, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = a.checked_div(b).ok_or_else(|| TxScriptError::InvalidState("Quotient exceeds 64-bit signed integer range, or there was a division by zero".to_string()))?;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpMod<0x97, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = a.checked_rem(b).ok_or_else(|| TxScriptError::InvalidState("Illegal modulo by zero".to_string()))?;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpLShift<0x98, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))
    opcode OpRShift<0x99, 1>(self, vm) Err(TxScriptError::OpcodeDisabled(format!("{self:?}")))

    opcode OpBoolAnd<0x9a, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = ((a != 0) && (b != 0)) as i64;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpBoolOr<0x9b, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = ((a != 0) || (b != 0)) as i64;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpNumEqual<0x9c, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = (a == b) as i64;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpNumEqualVerify<0x9d, 1>(self, vm) {
        let [a,b]: [i64; 2] = vm.dstack.pop_items()?;
        match a == b {
            true => Ok(()),
            false => Err(TxScriptError::VerifyError)
        }
    }

    opcode OpNumNotEqual<0x9e, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = (a != b) as i64;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpLessThan<0x9f, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = (a < b) as i64;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpGreaterThan<0xa0, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = (a > b) as i64;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpLessThanOrEqual<0xa1, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = (a <= b) as i64;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpGreaterThanOrEqual<0xa2, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = (a >= b) as i64;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpMin<0xa3, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = a.min(b);
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpMax<0xa4, 1>(self, vm) {
        let [ a, b ]: [i64; 2] = vm.dstack.pop_items()?;
        let r = a.max(b);
        vm.dstack.push_item(r)?;
        Ok(())
    }

    opcode OpWithin<0xa5, 1>(self, vm) {
        let [ x, l, u ]: [i64; 3] = vm.dstack.pop_items()?;
        let r = (x >= l && x < u) as i64;
        vm.dstack.push_item(r)?;
        Ok(())
    }

    // ZK precompile opcodes.
    opcode OpZkPrecompile<0xa6, 1>(self, vm) {
        // Parse the ZK Precompile tag
        let tag = parse_tag(&mut vm.dstack)?;

        // Consume the tag cost
        vm.consume_script_units(tag.cost())?;

        // Verify the ZK proof
        verify_zk(tag, &mut vm.dstack, &mut vm.runtime_resource_meter)?;

        // If no errors, push true to the stack
        vm.dstack.push_item(true)?;
        Ok(())
    }

    // Crypto opcodes.
    opcode OpBlake2bWithKey<0xa7, 1>(self, vm) {
        let [data, key] = vm.dstack.pop_raw()?;
        if key.len() > blake2b_simd::KEYBYTES {
            return Err(TxScriptError::ElementTooBig(key.len(), blake2b_simd::KEYBYTES))
        }
        vm.consume_script_units(HashOpcodePricing::Blake2b.script_units_for_data(data.len()))?;
        let hash = Params::new().hash_length(32).key(&key).to_state().update(&data).finalize();
        vm.dstack.push(hash.as_bytes().into())
    }

    opcode OpSHA256<0xa8, 1>(self, vm) {
        let [last] = vm.dstack.pop_raw()?;
        vm.consume_script_units(HashOpcodePricing::Sha256.script_units_for_data(last.len()))?;
        let mut hasher = Sha256::new();
        hasher.update(last);
        vm.dstack.push(hasher.finalize().as_slice().into())
    }

    opcode OpCheckMultiSigECDSA<0xa9, 1>(self, vm) {
        vm.op_check_multisig_schnorr_or_ecdsa(true)
    }

    opcode OpBlake2b<0xaa, 1>(self, vm) {
        let [last] = vm.dstack.pop_raw()?;
        vm.consume_script_units(HashOpcodePricing::Blake2b.script_units_for_data(last.len()))?;
        let hash = Params::new().hash_length(32).to_state().update(&last).finalize();
        vm.dstack.push(hash.as_bytes().into())
    }

    opcode OpCheckSigECDSA<0xab, 1>(self, vm) {
        let [mut sig, key] = vm.dstack.pop_raw()?;
        // Hash type
        match sig.pop() {
            Some(typ) => {
                let hash_type = SigHashType::from_u8(typ).map_err(|e| TxScriptError::InvalidSigHashType(typ))?;
                match vm.check_ecdsa_signature(hash_type, key.as_slice(), sig.as_slice()) {
                    Ok(valid) => {
                        vm.dstack.push_item(valid)?;
                        Ok(())
                    },
                    Err(e) => {
                        Err(e)
                    }
                }
            }
            None => {
                vm.dstack.push_item(false)?;
                Ok(())
            }
        }
    }

    opcode OpCheckSig<0xac, 1>(self, vm) {
        let [mut sig, key] = vm.dstack.pop_raw()?;
        // Hash type
        match sig.pop() {
            Some(typ) => {
                let hash_type = SigHashType::from_u8(typ).map_err(|e| TxScriptError::InvalidSigHashType(typ))?;
                match vm.check_schnorr_signature(hash_type, key.as_slice(), sig.as_slice()) {
                    Ok(valid) => {
                        vm.dstack.push_item(valid)?;
                        Ok(())
                    },
                    Err(e) => {
                        Err(e)
                    }
                }
            }
            None => {
                vm.dstack.push_item(false)?;
                Ok(())
            }
        }
    }

    opcode OpCheckSigVerify<0xad, 1>(self, vm) {
        // TODO: when changing impl to array based, change this too
        OpCheckSig{data: self.data.clone()}.execute(vm)?;
        let [valid]: [bool; 1] = vm.dstack.pop_items()?;
        match valid {
            true => Ok(()),
            false => Err(TxScriptError::VerifyError)
        }
    }

    opcode OpCheckMultiSig<0xae, 1>(self, vm) {
        vm.op_check_multisig_schnorr_or_ecdsa(false)
    }

    opcode OpCheckMultiSigVerify<0xaf, 1>(self, vm) {
        // TODO: when changing impl to array based, change this too
        OpCheckMultiSig{data: self.data.clone()}.execute(vm)?;
        let [valid]: [bool; 1] = vm.dstack.pop_items()?;
        match valid {
            true => Ok(()),
            false => Err(TxScriptError::VerifyError)
        }
    }

    opcode OpCheckLockTimeVerify<0xb0, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput {input, tx, ..} => {
                let [mut lock_time_bytes] = vm.dstack.pop_raw()?;

                // Make sure lockTimeBytes is exactly 8 bytes.
                // If more - return ErrNumberTooBig
                // If less - pad with 0's
                if lock_time_bytes.len() > 8 {
                    return Err(TxScriptError::NumberTooBig(format!("lockTime value represented as {lock_time_bytes:x?} is longer then 8 bytes")))
                }
                lock_time_bytes.resize(8, 0);
                let stack_lock_time = u64::from_le_bytes(lock_time_bytes.as_slice().try_into().expect("checked vector size"));

                // The lock time field of a transaction is either a DAA score at
                // which the transaction is finalized or a timestamp depending on if the
                // value is before the constants.LockTimeThreshold. When it is under the
                // threshold it is a DAA score.
                if !(
                    (tx.tx().lock_time < LOCK_TIME_THRESHOLD && stack_lock_time < LOCK_TIME_THRESHOLD) ||
                    (tx.tx().lock_time >= LOCK_TIME_THRESHOLD && stack_lock_time >= LOCK_TIME_THRESHOLD)
                ){
                    return Err(TxScriptError::UnsatisfiedLockTime(format!("mismatched locktime types -- tx locktime {}, stack locktime {}", tx.tx().lock_time, stack_lock_time)))
                }

                if stack_lock_time > tx.tx().lock_time {
                    return Err(TxScriptError::UnsatisfiedLockTime(format!("locktime requirement not satisfied -- locktime is greater than the transaction locktime: {} > {}", stack_lock_time, tx.tx().lock_time)))
                }

                // The lock time feature can also be disabled, thereby bypassing
                // OP_CHECKLOCKTIMEVERIFY, if every transaction input has been finalized by
                // setting its sequence to the maximum value (constants.MaxTxInSequenceNum). This
                // condition would result in the transaction being allowed into the blockDAG
                // making the opcode ineffective.
                //
                // This condition is prevented by enforcing that the input being used by
                // the opcode is unlocked (its sequence number is less than the max
                // value). This is sufficient to prove correctness without having to
                // check every input.
                //
                // NOTE: This implies that even if the transaction is not finalized due to
                // another input being unlocked, the opcode execution will still fail when the
                // input being used by the opcode is locked.
                if input.sequence == MAX_TX_IN_SEQUENCE_NUM {
                    return Err(TxScriptError::UnsatisfiedLockTime("transaction input is finalized".to_string()));
                }
                Ok(())
            }
            _ => Err(TxScriptError::InvalidSource("LockTimeVerify only applies to transaction inputs".to_string()))
        }
    }

    opcode OpCheckSequenceVerify<0xb1, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput {input, tx, ..} => {
                let [mut sequence_bytes] = vm.dstack.pop_raw()?;

                // Make sure sequenceBytes is exactly 8 bytes.
                // If more - return ErrNumberTooBig
                // If less - pad with 0's
                if sequence_bytes.len() > 8 {
                    return Err(TxScriptError::NumberTooBig(format!("lockTime value represented as {sequence_bytes:x?} is longer then 8 bytes")))
                }
                // Don't use makeScriptNum here, since sequence is not an actual number, minimal encoding rules don't apply to it,
                // and is more convenient to be represented as an unsigned int.
                sequence_bytes.resize(8, 0);
                let stack_sequence = u64::from_le_bytes(sequence_bytes.as_slice().try_into().expect("ensured size checks"));

                // To provide for future soft-fork extensibility, if the
                // operand has the disabled lock-time flag set,
                // CHECKSEQUENCEVERIFY behaves as a NOP.
                if stack_sequence & SEQUENCE_LOCK_TIME_DISABLED != 0 {
                    return Ok(());
                }

                // Sequence numbers with their most significant bit set are not
                // consensus constrained. Testing that the transaction's sequence
                // number does not have this bit set prevents using this property
                // to get around a CHECKSEQUENCEVERIFY check.
                if input.sequence & SEQUENCE_LOCK_TIME_DISABLED != 0 {
                    return Err(TxScriptError::UnsatisfiedLockTime(format!("transaction sequence has sequence locktime disabled bit set: {:#x}", input.sequence)));
                }

                // Mask off non-consensus bits before doing comparisons.
                if (stack_sequence & SEQUENCE_LOCK_TIME_MASK) > (input.sequence & SEQUENCE_LOCK_TIME_MASK) {
                    return Err(TxScriptError::UnsatisfiedLockTime(format!("locktime requirement not satisfied -- locktime is greater than the transaction locktime: {} > {}", stack_sequence & SEQUENCE_LOCK_TIME_MASK, input.sequence & SEQUENCE_LOCK_TIME_MASK)))
                }
                Ok(())
            }
            _ => Err(TxScriptError::InvalidSource("LockTimeVerify only applies to transaction inputs".to_string()))
        }
    }

    // Introspection opcodes
    // Transaction level opcodes (following Transaction struct field order)
    opcode OpTxVersion<0xb2, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                push_number(tx.tx().version as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxVersion only applies to transaction inputs".to_string()))
        }


    }
    opcode OpTxInputCount<0xb3, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                push_number(tx.inputs().len() as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpInputCount only applies to transaction inputs".to_string()))
        }
    }
    opcode OpTxOutputCount<0xb4, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                push_number(tx.outputs().len() as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpOutputCount only applies to transaction inputs".to_string()))
        }
    }
    opcode OpTxLockTime<0xb5, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                push_number(tx.tx().lock_time as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxLockTime only applies to transaction inputs".to_string()))
        }


    }
    opcode OpTxSubnetId<0xb6, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                push_data(tx.tx().subnetwork_id.into(), vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxSubnetId only applies to transaction inputs".to_string()))
        }


    }
    opcode OpTxGas<0xb7, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                push_number(tx.tx().gas as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxGas only applies to transaction inputs".to_string()))
        }


    }
    opcode OpTxPayloadSubstr<0xb8, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [start, end] = i32s_to_usizes(vm.dstack.pop_items()?)?;
                let substr = substring(&tx.tx().payload, start, end)?;
                push_data(substr, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxPayloadSubstr only applies to transaction inputs".to_string()))
        }


    }
    // Input related opcodes (following TransactionInput struct field order)
    opcode OpTxInputIndex<0xb9, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{idx, ..} => {
                push_number(idx as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpInputIndex only applies to transaction inputs".to_string()))
        }
    }
    opcode OpOutpointTxId<0xba, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let idx = i32_to_usize(idx)?;
                let input = tx.inputs().get(idx).ok_or_else(|| TxScriptError::InvalidInputIndex(idx as i32, tx.inputs().len()))?;
                push_data(input.previous_outpoint.transaction_id.as_bytes().into(), vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpOutpointTxId only applies to transaction inputs".to_string()))
        }


    }
    opcode OpOutpointIndex<0xbb, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let idx = i32_to_usize(idx)?;
                let input = tx.inputs().get(idx).ok_or_else(|| TxScriptError::InvalidInputIndex(idx as i32, tx.inputs().len()))?;
                push_number(input.previous_outpoint.index as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpOutpointIndex only applies to transaction inputs".to_string()))
        }


    }
    opcode OpTxInputScriptSigSubstr<0xbc, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx, start, end] = i32s_to_usizes(vm.dstack.pop_items()?)?;
                let input = tx.inputs().get(idx).ok_or_else(|| TxScriptError::InvalidInputIndex(idx as i32, tx.inputs().len()))?;
                let substr = substring(&input.signature_script, start, end)?;
                push_data(substr, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxInputScriptSigSubstr only applies to transaction inputs".to_string()))
        }


    }
    opcode OpTxInputSeq<0xbd, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let idx = i32_to_usize(idx)?;
                let input = tx.inputs().get(idx).ok_or_else(|| TxScriptError::InvalidInputIndex(idx as i32, tx.inputs().len()))?;
                // sequence is used as a bitflag field, so push as raw bytes (minimal number encoding doesn't apply). See CheckSequenceVerify for more details.
                push_data(input.sequence.to_le_bytes().into(), vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxInputSeq only applies to transaction inputs".to_string()))
        }


    }
    // UTXO related opcodes (following UtxoEntry struct field order)
    opcode OpTxInputAmount<0xbe, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let utxo = usize::try_from(idx).ok()
                    .and_then(|idx| tx.utxo(idx))
                    .ok_or_else(|| TxScriptError::InvalidInputIndex(idx, tx.inputs().len()))?;
                push_number(utxo.amount.try_into().map_err(|e: TryFromIntError| TxScriptError::NumberTooBig(e.to_string()))?, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpInputAmount only applies to transaction inputs".to_string()))
        }
    }
    opcode OpTxInputSpk<0xbf, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let utxo = usize::try_from(idx).ok()
                    .and_then(|idx| tx.utxo(idx))
                    .ok_or_else(|| TxScriptError::InvalidInputIndex(idx, tx.inputs().len()))?;
                vm.dstack.push(utxo.script_public_key.to_bytes().into())
            },
            _ => Err(TxScriptError::InvalidSource("OpInputSpk only applies to transaction inputs".to_string()))
        }
    }
    opcode OpTxInputDaaScore<0xc0, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let idx = i32_to_usize(idx)?;
                let utxo = tx.utxo(idx).ok_or_else(|| TxScriptError::InvalidInputIndex(idx as i32, tx.inputs().len()))?;
                push_number(utxo.block_daa_score as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxInputDaaScore only applies to transaction inputs".to_string()))
        }


    }
    opcode OpTxInputIsCoinbase<0xc1, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let idx = i32_to_usize(idx)?;
                let utxo = tx.utxo(idx).ok_or_else(|| TxScriptError::InvalidInputIndex(idx as i32, tx.inputs().len()))?;
                push_number(utxo.is_coinbase as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxInputIsCoinbase only applies to transaction inputs".to_string()))
        }


    }
    // Output related opcodes (following TransactionOutput struct field order)
    opcode OpTxOutputAmount<0xc2, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let output = usize::try_from(idx).ok()
                    .and_then(|idx| tx.outputs().get(idx))
                    .ok_or_else(|| TxScriptError::InvalidOutputIndex(idx, tx.outputs().len()))?;
                push_number(output.value.try_into().map_err(|e: TryFromIntError| TxScriptError::NumberTooBig(e.to_string()))?, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxOutputAmount only applies to transaction inputs".to_string()))
        }
    }
    opcode OpTxOutputSpk<0xc3, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let output = usize::try_from(idx).ok()
                    .and_then(|idx| tx.outputs().get(idx))
                    .ok_or_else(|| TxScriptError::InvalidOutputIndex(idx, tx.outputs().len()))?;
                vm.dstack.push(output.script_public_key.to_bytes().into())
            },
            _ => Err(TxScriptError::InvalidSource("OpTxOutputSpk only applies to transaction inputs".to_string()))
        }
    }

    opcode OpTxPayloadLen<0xc4, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                push_number(tx.tx().payload.len() as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxPayloadLen only applies to transaction inputs".to_string()))
        }


    }

    opcode OpTxInputSpkLen<0xc5, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let idx = i32_to_usize(idx)?;
                let utxo = tx.utxo(idx).ok_or_else(|| TxScriptError::InvalidInputIndex(idx as i32, tx.inputs().len()))?;
                // TODO: Consider adding a method to ScriptPublicKey for getting length directly, instead of converting to bytes first.
                let len = utxo.script_public_key.to_bytes().len() as i64;
                push_number(len, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxInputSpkLen only applies to transaction inputs".to_string()))
        }


    }

    opcode OpTxInputSpkSubstr<0xc6, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx, start, end] = i32s_to_usizes(vm.dstack.pop_items()?)?;
                let utxo = tx.utxo(idx).ok_or_else(|| TxScriptError::InvalidInputIndex(idx as i32, tx.inputs().len()))?;
                let spk_bytes = utxo.script_public_key.to_bytes();
                let substr = substring(&spk_bytes, start, end)?;
                push_data(substr, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxInputSpkSubstr only applies to transaction inputs".to_string()))
        }


    }

    opcode OpTxOutputSpkLen<0xc7, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let idx = i32_to_usize(idx)?;
                let output = tx.outputs().get(idx).ok_or_else(|| TxScriptError::InvalidOutputIndex(idx as i32, tx.outputs().len()))?;
                // TODO: Consider adding a method to ScriptPublicKey for getting length directly, instead of converting to bytes first.
                let len = output.script_public_key.to_bytes().len() as i64;
                push_number(len, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxOutputSpkLen only applies to transaction inputs".to_string()))
        }


    }

    opcode OpTxOutputSpkSubstr<0xc8, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx, start, end] = i32s_to_usizes(vm.dstack.pop_items()?)?;
                let output = tx.outputs().get(idx).ok_or_else(|| TxScriptError::InvalidOutputIndex(idx as i32, tx.outputs().len()))?;
                let spk_bytes = output.script_public_key.to_bytes();
                let substr = substring(&spk_bytes, start, end)?;
                push_data(substr, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxOutputSpkSubstr only applies to transaction inputs".to_string()))
        }


    }

    opcode OpTxInputScriptSigLen<0xc9, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let idx = i32_to_usize(idx)?;
                let input = tx.inputs().get(idx).ok_or_else(|| TxScriptError::InvalidInputIndex(idx as i32, tx.inputs().len()))?;
                let len = input.signature_script.len() as i64;
                push_number(len, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpTxInputScriptSigLen only applies to transaction inputs".to_string()))
        }


    }
    opcode OpUnknown202<0xca, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpAuthOutputCount<0xcb, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [input_idx]: [i32; 1] = vm.dstack.pop_items()?;
                let input_idx = i32_to_usize(input_idx)?;
                if input_idx >= tx.inputs().len() {
                    return Err(TxScriptError::InvalidInputIndex(input_idx.try_into().expect("casted above"), tx.inputs().len()));
                }
                let count = vm.covenants_ctx.num_auth_outputs(input_idx);
                push_number(count as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpAuthOutputCount only applies to transaction inputs".to_string()))
        }


    }

    opcode OpAuthOutputIdx<0xcc, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [input_idx, k] = i32s_to_usizes(vm.dstack.pop_items()?)?;
                if input_idx >= tx.inputs().len() {
                    return Err(TxScriptError::InvalidInputIndex(input_idx.try_into().expect("casted above"), tx.inputs().len()));
                }
                let output_idx = vm.covenants_ctx.auth_output_index(input_idx, k)?;
                push_number(output_idx as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpAuthOutputIdx only applies to transaction inputs".to_string()))
        }


    }

    opcode OpNum2Bin<0xcd, 1>(self, vm) {
        let [size]: [i32; 1] = vm.dstack.pop_items()?;
        let size = i32_to_usize(size)?;
        if size > 8 {
            return Err(TxScriptError::NotMinimalData(format!("NUM2BIN target size {size} exceeds 8 bytes")));
        }
        let [num]: [i64; 1] = vm.dstack.pop_items()?;
        let r = serialize_i64(num, Some(size))?;
        vm.dstack.push(r)


    }

    opcode OpBin2Num<0xce, 1>(self, vm) {
        // pop_items deserializes the stack item to `i64`, while `push_number` pushes it back as minimally encoded bytes.
        let [num]: [i64; 1] = vm.dstack.pop_items()?;
        push_number(num, vm)


    }

    opcode OpInputCovenantId<0xcf, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let idx = i32_to_usize(idx)?;
                let utxo = tx.utxo(idx).ok_or_else(|| TxScriptError::InvalidInputIndex(idx as i32, tx.inputs().len()))?;
                let covenant_id = utxo.covenant_id.unwrap_or(ZERO_HASH);
                push_data(covenant_id.as_bytes().into(), vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpInputCovenantId only applies to transaction inputs".to_string()))
        }


    }

    opcode OpCovInputCount<0xd0, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [covenant_id]: [Hash; 1] = vm.dstack.pop_items()?;
                let count = vm.covenants_ctx.num_covenant_inputs(covenant_id);
                push_number(count as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpCovInputCount only applies to transaction inputs".to_string()))
        }


    }

    opcode OpCovInputIdx<0xd1, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [k]: [i32; 1] = vm.dstack.pop_items()?;
                let k = i32_to_usize(k)?;
                let [covenant_id]: [Hash; 1] = vm.dstack.pop_items()?;
                let idx = vm.covenants_ctx.covenant_input_index(covenant_id, k)?;
                push_number(idx as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpCovInputIdx only applies to transaction inputs".to_string()))
        }


    }

    opcode OpCovOutputCount<0xd2, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [covenant_id]: [Hash; 1] = vm.dstack.pop_items()?;
                let count = vm.covenants_ctx.num_covenant_outputs(covenant_id);
                push_number(count as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpCovOutputCount only applies to transaction inputs".to_string()))
        }


    }

    opcode OpCovOutputIdx<0xd3, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [k]: [i32; 1] = vm.dstack.pop_items()?;
                let k = i32_to_usize(k)?;
                let [covenant_id]: [Hash; 1] = vm.dstack.pop_items()?;
                let idx = vm.covenants_ctx.covenant_output_index(covenant_id, k)?;
                push_number(idx as i64, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpCovOutputIdx only applies to transaction inputs".to_string()))
        }


    }

    opcode OpChainblockSeqCommit<0xd4, 1>(self, vm) {
        let Some(seq_commit_accessor) = vm.ctx.seq_commit_accessor else {
            // seq_commit_access is none only if the opcode is not enabled
            return Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
        };
        let [block]: [Hash; 1] = vm.dstack.pop_items()?; // TODO: We actually could convert slice ref into hash ref if it was repr(transparent)
        match seq_commit_accessor.is_chain_ancestor_from_pov(block) {
            None => return Err(TxScriptError::BlockAlreadyPruned(block.to_string())),
            Some(false) => return Err(TxScriptError::BlockNotSelected(block.to_string())),
            Some(true) => {}
        };
        let commitment = seq_commit_accessor.seq_commitment_within_depth(block)
            .ok_or_else(|| TxScriptError::BlockIsTooDeep(block.to_string()))?;
        vm.dstack.push_item(commitment)?;
        Ok(())
    }

    opcode OpOutputCovenantId<0xd5, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let idx = i32_to_usize(idx)?;
                let output = tx.outputs().get(idx).ok_or_else(|| TxScriptError::InvalidOutputIndex(idx as i32, tx.outputs().len()))?;
                let covenant_id = output.covenant.map(|c| c.covenant_id).unwrap_or(ZERO_HASH);
                push_data(covenant_id.as_bytes().into(), vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpOutputCovenantId only applies to transaction inputs".to_string()))
        }


    }

    opcode OpOutputAuthorizingInput<0xd6, 1>(self, vm) {
        match vm.script_source {
            ScriptSource::TxInput{tx, ..} => {
                let [idx]: [i32; 1] = vm.dstack.pop_items()?;
                let idx = i32_to_usize(idx)?;
                let output = tx.outputs().get(idx).ok_or_else(|| TxScriptError::InvalidOutputIndex(idx as i32, tx.outputs().len()))?;
                let auth_input_idx = output.covenant.as_ref()
                    .map(|c| c.authorizing_input as i64)
                    .unwrap_or(-1i64);
                push_number(auth_input_idx, vm)
            },
            _ => Err(TxScriptError::InvalidSource("OpOutputAuthorizingInput only applies to transaction inputs".to_string()))
        }


    }

    opcode OpCheckSigFromStack<0xd7, 1>(self, vm) {
        let [signature, msg_hash, pubkey] = vm.dstack.pop_raw()?;
        let msg_hash = Hash::try_from(msg_hash.as_slice()).map_err(|_| TxScriptError::InvalidState("message hash must be 32 bytes".to_string()))?;
        let is_valid = vm.check_schnorr_signature_with_msg_hash(&pubkey, &signature, |_| msg_hash)?;
        vm.dstack.push_item(is_valid)


    }

    opcode OpCheckSigFromStackECDSA<0xd8, 1>(self, vm) {
        let [signature, msg_hash, pubkey] = vm.dstack.pop_raw()?;
        let msg_hash = Hash::try_from(msg_hash.as_slice()).map_err(|_| TxScriptError::InvalidState("message hash must be 32 bytes".to_string()))?;
        let is_valid = vm.check_ecdsa_signature_with_msg_hash(&pubkey, &signature, |_| msg_hash)?;
        vm.dstack.push_item(is_valid)


    }

    opcode OpBlake3<0xd9, 1>(self, vm) {
        let [data] = vm.dstack.pop_raw()?;
        vm.consume_script_units(HashOpcodePricing::Blake3.script_units_for_data(data.len()))?;
        let hash = blake3::hash(&data);
        vm.dstack.push(hash.as_slice().into())


    }

    opcode OpBlake3WithKey<0xda, 1>(self, vm) {
        let [data, key] = vm.dstack.pop_raw()?;
        let key: &[u8; blake3::KEY_LEN] = key.as_slice().try_into().map_err(|_| {
            TxScriptError::MalformedPush(blake3::KEY_LEN, key.len())
        })?;
        vm.consume_script_units(HashOpcodePricing::Blake3.script_units_for_data(data.len()))?;
        let hash = blake3::keyed_hash(key, &data);
        vm.dstack.push(hash.as_slice().into())


    }

    opcode OpUnknown219<0xdb, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown220<0xdc, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown221<0xdd, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown222<0xde, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown223<0xdf, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown224<0xe0, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown225<0xe1, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown226<0xe2, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown227<0xe3, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown228<0xe4, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown229<0xe5, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown230<0xe6, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown231<0xe7, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown232<0xe8, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown233<0xe9, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown234<0xea, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown235<0xeb, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown236<0xec, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown237<0xed, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown238<0xee, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown239<0xef, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown240<0xf0, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown241<0xf1, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown242<0xf2, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown243<0xf3, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown244<0xf4, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown245<0xf5, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown246<0xf6, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown247<0xf7, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown248<0xf8, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown249<0xf9, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))

    opcode OpSmallInteger<0xfa, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpPubKeys<0xfb, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpUnknown252<0xfc, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpPubKeyHash<0xfd, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpPubKey<0xfe, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
    opcode OpInvalidOpCode<0xff, 1>(self, vm) Err(TxScriptError::InvalidOpcode(format!("{self:?}")))
}

// converts an opcode from the list of Op0 to Op16 to its associated value
#[allow(clippy::borrowed_box)]
pub fn to_small_int<T: VerifiableTransaction, Reused: SigHashReusedValues>(opcode: &Box<dyn OpCodeImplementation<T, Reused>>) -> u8 {
    let value = opcode.value();
    if value == codes::OpFalse {
        return 0;
    }

    assert!((codes::OpTrue..codes::Op16).contains(&value), "expected op codes between from the list of Op0 to Op16");
    value - (codes::OpTrue - 1)
}

#[cfg(test)]
mod test {
    use crate::caches::Cache;
    use crate::data_stack::{Stack, StackEntry};
    use crate::opcodes::{OpCodeExecution, OpCodeImplementation};
    use crate::{
        EngineContext, EngineFlags, LOCK_TIME_THRESHOLD, TxScriptEngine, TxScriptError, opcodes, pay_to_address_script, script_to_str,
    };
    use kaspa_addresses::{Address, Prefix, Version};
    use kaspa_consensus_core::constants::{SOMPI_PER_KASPA, TX_VERSION};
    use kaspa_consensus_core::hashing::sighash::SigHashReusedValuesUnsync;
    use kaspa_consensus_core::subnets::SUBNETWORK_ID_NATIVE;
    use kaspa_consensus_core::tx::{
        PopulatedTransaction, ScriptPublicKey, Transaction, TransactionInput, TransactionOutpoint, TransactionOutput, UtxoEntry,
        VerifiableTransaction,
    };

    struct TestCase<'a> {
        init: Vec<Vec<u8>>,
        code: Box<dyn OpCodeImplementation<PopulatedTransaction<'a>, SigHashReusedValuesUnsync>>,
        dstack: Vec<Vec<u8>>,
    }

    struct ErrorTestCase<'a> {
        init: Vec<Vec<u8>>,
        code: Box<dyn OpCodeImplementation<PopulatedTransaction<'a>, SigHashReusedValuesUnsync>>,
        error: TxScriptError,
    }

    fn run_success_test_cases(tests: Vec<TestCase>) {
        run_success_test_cases_with_flags(tests, Default::default());
    }

    fn run_success_test_cases_with_flags(tests: Vec<TestCase>, flags: EngineFlags) {
        let cache = Cache::new(10_000);
        let reused_values = SigHashReusedValuesUnsync::new();
        let ctx = EngineContext::new(&cache).with_reused(&reused_values);
        for TestCase { init, code, dstack } in tests {
            let init: Stack = init.into();
            let dstack = dstack.into();
            let mut vm = TxScriptEngine::new(ctx, flags);
            vm.dstack = init.clone();
            code.execute(&mut vm).unwrap_or_else(|_| panic!("Opcode {} should not fail", code.value()));
            assert_eq!(vm.dstack, dstack, "OpCode {} Pushed wrong value", code.value());
        }
    }

    fn run_error_test_cases(tests: Vec<ErrorTestCase>) {
        run_error_test_cases_with_flags(tests, Default::default());
    }

    fn run_error_test_cases_with_flags(tests: Vec<ErrorTestCase>, flags: EngineFlags) {
        let cache = Cache::new(10_000);
        let reused_values = SigHashReusedValuesUnsync::new();
        let ctx = EngineContext::new(&cache).with_reused(&reused_values);
        for ErrorTestCase { init, code, error } in tests {
            let mut vm = TxScriptEngine::new(ctx, flags);
            vm.dstack = init.clone().into();
            assert_eq!(
                code.execute(&mut vm)
                    .expect_err(format!("Opcode {} should have errored (init: {:?})", code.value(), init.clone()).as_str()),
                error,
                "Opcode {} returned wrong error {:?}",
                code.value(),
                init
            );
        }
    }

    #[test]
    fn test_opcode_disabled() {
        let tests: Vec<Box<dyn OpCodeImplementation<PopulatedTransaction, SigHashReusedValuesUnsync>>> = vec![
            opcodes::OpLeft::empty().expect("Should accept empty"),
            opcodes::OpRight::empty().expect("Should accept empty"),
            opcodes::Op2Mul::empty().expect("Should accept empty"),
            opcodes::Op2Div::empty().expect("Should accept empty"),
            opcodes::OpLShift::empty().expect("Should accept empty"),
            opcodes::OpRShift::empty().expect("Should accept empty"),
        ];

        let cache = Cache::new(10_000);
        let reused_values = SigHashReusedValuesUnsync::new();
        let ctx = EngineContext::new(&cache).with_reused(&reused_values);
        let mut vm = TxScriptEngine::new(ctx, Default::default());

        for pop in tests {
            match pop.execute(&mut vm) {
                Err(TxScriptError::OpcodeDisabled(_)) => {}
                _ => panic!("Opcode {pop:?} should be disabled"),
            }
        }
    }

    #[test]
    fn test_opcode_reserved() {
        let tests: Vec<Box<dyn OpCodeImplementation<PopulatedTransaction, SigHashReusedValuesUnsync>>> = vec![
            opcodes::OpReserved::empty().expect("Should accept empty"),
            opcodes::OpVer::empty().expect("Should accept empty"),
            opcodes::OpVerIf::empty().expect("Should accept empty"),
            opcodes::OpVerNotIf::empty().expect("Should accept empty"),
            opcodes::OpReserved1::empty().expect("Should accept empty"),
            opcodes::OpReserved2::empty().expect("Should accept empty"),
        ];

        let cache = Cache::new(10_000);
        let reused_values = SigHashReusedValuesUnsync::new();
        let ctx = EngineContext::new(&cache).with_reused(&reused_values);
        let mut vm = TxScriptEngine::new(ctx, Default::default());

        for pop in tests {
            match pop.execute(&mut vm) {
                Err(TxScriptError::OpcodeReserved(_)) => {}
                _ => panic!("Opcode {pop:?} should be disabled"),
            }
        }
    }

    #[test]
    fn test_opcode_invalid() {
        let tests: Vec<Box<dyn OpCodeImplementation<PopulatedTransaction, SigHashReusedValuesUnsync>>> = vec![
            opcodes::OpUnknown202::empty().expect("Should accept empty"),
            opcodes::OpUnknown219::empty().expect("Should accept empty"),
            opcodes::OpUnknown220::empty().expect("Should accept empty"),
            opcodes::OpUnknown221::empty().expect("Should accept empty"),
            opcodes::OpUnknown222::empty().expect("Should accept empty"),
            opcodes::OpUnknown223::empty().expect("Should accept empty"),
            opcodes::OpUnknown224::empty().expect("Should accept empty"),
            opcodes::OpUnknown225::empty().expect("Should accept empty"),
            opcodes::OpUnknown226::empty().expect("Should accept empty"),
            opcodes::OpUnknown227::empty().expect("Should accept empty"),
            opcodes::OpUnknown228::empty().expect("Should accept empty"),
            opcodes::OpUnknown229::empty().expect("Should accept empty"),
            opcodes::OpUnknown230::empty().expect("Should accept empty"),
            opcodes::OpUnknown231::empty().expect("Should accept empty"),
            opcodes::OpUnknown232::empty().expect("Should accept empty"),
            opcodes::OpUnknown233::empty().expect("Should accept empty"),
            opcodes::OpUnknown234::empty().expect("Should accept empty"),
            opcodes::OpUnknown235::empty().expect("Should accept empty"),
            opcodes::OpUnknown236::empty().expect("Should accept empty"),
            opcodes::OpUnknown237::empty().expect("Should accept empty"),
            opcodes::OpUnknown238::empty().expect("Should accept empty"),
            opcodes::OpUnknown239::empty().expect("Should accept empty"),
            opcodes::OpUnknown240::empty().expect("Should accept empty"),
            opcodes::OpUnknown241::empty().expect("Should accept empty"),
            opcodes::OpUnknown242::empty().expect("Should accept empty"),
            opcodes::OpUnknown243::empty().expect("Should accept empty"),
            opcodes::OpUnknown244::empty().expect("Should accept empty"),
            opcodes::OpUnknown245::empty().expect("Should accept empty"),
            opcodes::OpUnknown246::empty().expect("Should accept empty"),
            opcodes::OpUnknown247::empty().expect("Should accept empty"),
            opcodes::OpUnknown248::empty().expect("Should accept empty"),
            opcodes::OpUnknown249::empty().expect("Should accept empty"),
        ];

        let cache = Cache::new(10_000);
        let reused_values = SigHashReusedValuesUnsync::new();
        let ctx = EngineContext::new(&cache).with_reused(&reused_values);
        let mut vm = TxScriptEngine::new(ctx, Default::default());

        for pop in tests {
            match pop.execute(&mut vm) {
                Err(TxScriptError::InvalidOpcode(_)) => {}
                _ => panic!("Opcode {pop:?} should be disabled"),
            }
        }
    }

    #[test]
    fn test_opcode_to_string_without_data() {
        let opcode: Box<dyn OpCodeImplementation<PopulatedTransaction, SigHashReusedValuesUnsync>> =
            opcodes::OpTrue::empty().expect("Should accept empty");
        assert_eq!(opcode.to_string(), "OpTrue");
    }

    #[test]
    fn test_opcode_to_string_with_data() {
        let opcode: Box<dyn OpCodeImplementation<PopulatedTransaction, SigHashReusedValuesUnsync>> =
            opcodes::OpData2::new(vec![0xab, 0xcd]).expect("Should accept data");
        assert_eq!(opcode.to_string(), "OpData2 0xabcd");
    }

    #[test]
    fn test_script_builder_roundtrip_to_joined_opcode_string() {
        use opcodes::codes::{OpBlake2b, OpCheckSig, OpDrop, OpDup, OpEqualVerify, OpVerify};

        let mut builder = crate::script_builder::ScriptBuilder::new();
        builder
            .add_op(OpDup)
            .unwrap()
            .add_data(&[0x02, 0xab, 0xcd])
            .unwrap()
            .add_op(OpBlake2b)
            .unwrap()
            .add_data(b"kaspa")
            .unwrap()
            .add_op(OpEqualVerify)
            .unwrap()
            .add_i64(-1)
            .unwrap()
            .add_i64(16)
            .unwrap()
            .add_op(OpCheckSig)
            .unwrap()
            .add_data(&[0xde, 0xad, 0xbe, 0xef])
            .unwrap()
            .add_op(OpDrop)
            .unwrap()
            .add_op(OpVerify)
            .unwrap();

        let script = builder.drain();

        assert_eq!(
            script_to_str(&script).unwrap(),
            "OpDup OpData3 0x02abcd OpBlake2b OpData5 0x6b61737061 OpEqualVerify Op1Negate Op16 OpCheckSig OpData4 0xdeadbeef OpDrop OpVerify"
        );
    }

    #[test]
    fn test_push_data() {
        run_success_test_cases(vec![
            TestCase { code: opcodes::OpFalse::empty().expect("Should accept empty"), dstack: vec![vec![]], init: Default::default() },
            TestCase {
                code: opcodes::OpData1::new([1u8; 1].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 1].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData2::new([1u8; 2].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 2].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData3::new([1u8; 3].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 3].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData4::new([1u8; 4].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 4].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData5::new([1u8; 5].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 5].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData6::new([1u8; 6].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 6].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData7::new([1u8; 7].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 7].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData8::new([1u8; 8].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 8].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData9::new([1u8; 9].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 9].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData10::new([1u8; 10].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 10].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData11::new([1u8; 11].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 11].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData12::new([1u8; 12].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 12].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData13::new([1u8; 13].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 13].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData14::new([1u8; 14].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 14].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData15::new([1u8; 15].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 15].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData16::new([1u8; 16].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 16].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData17::new([1u8; 17].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 17].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData18::new([1u8; 18].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 18].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData19::new([1u8; 19].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 19].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData20::new([1u8; 20].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 20].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData21::new([1u8; 21].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 21].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData22::new([1u8; 22].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 22].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData23::new([1u8; 23].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 23].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData24::new([1u8; 24].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 24].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData25::new([1u8; 25].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 25].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData26::new([1u8; 26].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 26].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData27::new([1u8; 27].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 27].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData28::new([1u8; 28].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 28].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData29::new([1u8; 29].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 29].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData30::new([1u8; 30].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 30].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData31::new([1u8; 31].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 31].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData32::new([1u8; 32].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 32].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData33::new([1u8; 33].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 33].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData34::new([1u8; 34].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 34].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData35::new([1u8; 35].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 35].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData36::new([1u8; 36].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 36].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData37::new([1u8; 37].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 37].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData38::new([1u8; 38].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 38].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData39::new([1u8; 39].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 39].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData40::new([1u8; 40].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 40].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData41::new([1u8; 41].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 41].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData42::new([1u8; 42].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 42].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData43::new([1u8; 43].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 43].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData44::new([1u8; 44].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 44].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData45::new([1u8; 45].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 45].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData46::new([1u8; 46].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 46].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData47::new([1u8; 47].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 47].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData48::new([1u8; 48].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 48].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData49::new([1u8; 49].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 49].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData50::new([1u8; 50].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 50].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData51::new([1u8; 51].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 51].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData52::new([1u8; 52].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 52].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData53::new([1u8; 53].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 53].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData54::new([1u8; 54].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 54].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData55::new([1u8; 55].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 55].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData56::new([1u8; 56].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 56].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData57::new([1u8; 57].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 57].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData58::new([1u8; 58].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 58].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData59::new([1u8; 59].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 59].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData60::new([1u8; 60].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 60].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData61::new([1u8; 61].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 61].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData62::new([1u8; 62].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 62].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData63::new([1u8; 63].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 63].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData64::new([1u8; 64].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 64].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData65::new([1u8; 65].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 65].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData66::new([1u8; 66].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 66].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData67::new([1u8; 67].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 67].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData68::new([1u8; 68].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 68].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData69::new([1u8; 69].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 69].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData70::new([1u8; 70].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 70].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData71::new([1u8; 71].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 71].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData72::new([1u8; 72].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 72].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData73::new([1u8; 73].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 73].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData74::new([1u8; 74].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 74].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpData75::new([1u8; 75].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 75].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpPushData1::new([1u8; 76].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 76].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpPushData2::new([1u8; 0x100].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 0x100].to_vec()],
                init: Default::default(),
            },
            TestCase {
                code: opcodes::OpPushData4::new([1u8; 0x10000].to_vec()).expect("Valid opcode"),
                dstack: vec![[1u8; 0x10000].to_vec()],
                init: Default::default(),
            },
        ]);
    }

    #[test]
    fn test_push_num() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::Op1Negate::empty().expect("Should accept empty"),
                dstack: vec![vec![0x81]],
                init: Default::default(),
            },
            TestCase { code: opcodes::Op1::empty().expect("Should accept empty"), dstack: vec![vec![1]], init: Default::default() },
            TestCase { code: opcodes::Op2::empty().expect("Should accept empty"), dstack: vec![vec![2]], init: Default::default() },
            TestCase { code: opcodes::Op3::empty().expect("Should accept empty"), dstack: vec![vec![3]], init: Default::default() },
            TestCase { code: opcodes::Op4::empty().expect("Should accept empty"), dstack: vec![vec![4]], init: Default::default() },
            TestCase { code: opcodes::Op5::empty().expect("Should accept empty"), dstack: vec![vec![5]], init: Default::default() },
            TestCase { code: opcodes::Op6::empty().expect("Should accept empty"), dstack: vec![vec![6]], init: Default::default() },
            TestCase { code: opcodes::Op7::empty().expect("Should accept empty"), dstack: vec![vec![7]], init: Default::default() },
            TestCase { code: opcodes::Op8::empty().expect("Should accept empty"), dstack: vec![vec![8]], init: Default::default() },
            TestCase { code: opcodes::Op9::empty().expect("Should accept empty"), dstack: vec![vec![9]], init: Default::default() },
            TestCase { code: opcodes::Op10::empty().expect("Should accept empty"), dstack: vec![vec![10]], init: Default::default() },
            TestCase { code: opcodes::Op11::empty().expect("Should accept empty"), dstack: vec![vec![11]], init: Default::default() },
            TestCase { code: opcodes::Op12::empty().expect("Should accept empty"), dstack: vec![vec![12]], init: Default::default() },
            TestCase { code: opcodes::Op13::empty().expect("Should accept empty"), dstack: vec![vec![13]], init: Default::default() },
            TestCase { code: opcodes::Op14::empty().expect("Should accept empty"), dstack: vec![vec![14]], init: Default::default() },
            TestCase { code: opcodes::Op15::empty().expect("Should accept empty"), dstack: vec![vec![15]], init: Default::default() },
            TestCase { code: opcodes::Op16::empty().expect("Should accept empty"), dstack: vec![vec![16]], init: Default::default() },
        ]);
    }

    #[test]
    fn test_uniary_num_ops() {
        run_success_test_cases(vec![
            TestCase { code: opcodes::Op1Add::empty().expect("Should accept empty"), init: vec![vec![]], dstack: vec![vec![1]] },
            TestCase { code: opcodes::Op1Add::empty().expect("Should accept empty"), init: vec![vec![1]], dstack: vec![vec![2]] },
            TestCase {
                code: opcodes::Op1Add::empty().expect("Should accept empty"),
                init: vec![vec![2, 1]],
                dstack: vec![vec![3, 1]],
            },
            TestCase { code: opcodes::Op1Add::empty().expect("Should accept empty"), init: vec![vec![0x81]], dstack: vec![vec![]] },
            TestCase { code: opcodes::Op1Sub::empty().expect("Should accept empty"), init: vec![vec![]], dstack: vec![vec![0x81]] },
            TestCase { code: opcodes::Op1Sub::empty().expect("Should accept empty"), init: vec![vec![1]], dstack: vec![vec![]] },
            TestCase { code: opcodes::Op1Sub::empty().expect("Should accept empty"), init: vec![vec![2]], dstack: vec![vec![1]] },
            TestCase {
                code: opcodes::Op1Sub::empty().expect("Should accept empty"),
                init: vec![vec![3, 1]],
                dstack: vec![vec![2, 1]],
            },
            TestCase { code: opcodes::OpNegate::empty().expect("Should accept empty"), init: vec![vec![]], dstack: vec![vec![]] },
            TestCase { code: opcodes::OpNegate::empty().expect("Should accept empty"), init: vec![vec![1]], dstack: vec![vec![0x81]] },
            TestCase { code: opcodes::OpNegate::empty().expect("Should accept empty"), init: vec![vec![0x81]], dstack: vec![vec![1]] },
            TestCase {
                code: opcodes::OpNegate::empty().expect("Should accept empty"),
                init: vec![vec![3, 1]],
                dstack: vec![vec![3, 0x81]],
            },
            TestCase { code: opcodes::OpAbs::empty().expect("Should accept empty"), init: vec![vec![]], dstack: vec![vec![]] },
            TestCase { code: opcodes::OpAbs::empty().expect("Should accept empty"), init: vec![vec![3, 1]], dstack: vec![vec![3, 1]] },
            TestCase {
                code: opcodes::OpAbs::empty().expect("Should accept empty"),
                init: vec![vec![3, 0x81]],
                dstack: vec![vec![3, 1]],
            },
            TestCase { code: opcodes::OpAbs::empty().expect("Should accept empty"), init: vec![vec![1]], dstack: vec![vec![1]] },
            TestCase { code: opcodes::OpAbs::empty().expect("Should accept empty"), init: vec![vec![0x81]], dstack: vec![vec![1]] },
            TestCase {
                code: opcodes::OpAbs::empty().expect("Should accept empty"),
                init: vec![vec![1, 1, 0x82]],
                dstack: vec![vec![1, 1, 2]],
            },
            TestCase { code: opcodes::OpNot::empty().expect("Should accept empty"), init: vec![vec![]], dstack: vec![vec![1]] },
            TestCase { code: opcodes::OpNot::empty().expect("Should accept empty"), init: vec![vec![1]], dstack: vec![vec![]] },
            TestCase { code: opcodes::OpNot::empty().expect("Should accept empty"), init: vec![vec![1, 2, 3]], dstack: vec![vec![]] },
            TestCase { code: opcodes::Op0NotEqual::empty().expect("Should accept empty"), init: vec![vec![]], dstack: vec![vec![]] },
            TestCase { code: opcodes::Op0NotEqual::empty().expect("Should accept empty"), init: vec![vec![1]], dstack: vec![vec![1]] },
            TestCase { code: opcodes::Op0NotEqual::empty().expect("Should accept empty"), init: vec![vec![2]], dstack: vec![vec![1]] },
            TestCase {
                code: opcodes::Op0NotEqual::empty().expect("Should accept empty"),
                init: vec![vec![1, 2, 3]],
                dstack: vec![vec![1]],
            },
        ]);
    }

    #[test]
    fn test_binary_num_ops() {
        run_success_test_cases(vec![
            TestCase { code: opcodes::OpAdd::empty().expect("Should accept empty"), init: vec![vec![], vec![]], dstack: vec![vec![]] },
            TestCase {
                code: opcodes::OpAdd::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpAdd::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpAdd::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![1]],
                dstack: vec![vec![2]],
            },
            TestCase {
                code: opcodes::OpAdd::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpAdd::empty().expect("Should accept empty"),
                init: vec![vec![0x7f], vec![1]],
                dstack: vec![vec![0x80, 0]],
            },
            TestCase {
                code: opcodes::OpAdd::empty().expect("Should accept empty"),
                init: vec![vec![0x80, 0], vec![0x80, 0]],
                dstack: vec![vec![0, 1]],
            },
            TestCase {
                code: opcodes::OpAdd::empty().expect("Should accept empty"),
                init: vec![vec![0xff, 0], vec![1]],
                dstack: vec![vec![0, 1]],
            },
            TestCase { code: opcodes::OpSub::empty().expect("Should accept empty"), init: vec![vec![], vec![]], dstack: vec![vec![]] },
            TestCase {
                code: opcodes::OpSub::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![0x81]],
            },
            TestCase {
                code: opcodes::OpSub::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpSub::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpSub::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![1]],
                dstack: vec![vec![0x82]],
            },
            TestCase {
                code: opcodes::OpSub::empty().expect("Should accept empty"),
                init: vec![vec![0x80, 0], vec![1]],
                dstack: vec![vec![0x7f]],
            },
            TestCase {
                code: opcodes::OpSub::empty().expect("Should accept empty"),
                init: vec![vec![0, 1], vec![0x80, 0]],
                dstack: vec![vec![0x80, 0]],
            },
            TestCase {
                code: opcodes::OpSub::empty().expect("Should accept empty"),
                init: vec![vec![0, 1], vec![1]],
                dstack: vec![vec![0xff, 0]],
            },
            TestCase {
                code: opcodes::OpMax::empty().expect("Should accept empty"),
                init: vec![vec![0, 1], vec![1]],
                dstack: vec![vec![0, 1]],
            },
            TestCase {
                code: opcodes::OpMax::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![0, 1]],
                dstack: vec![vec![0, 1]],
            },
            TestCase {
                code: opcodes::OpMax::empty().expect("Should accept empty"),
                init: vec![vec![0, 0x81], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpMin::empty().expect("Should accept empty"),
                init: vec![vec![0, 1], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpMin::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![0, 1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpMin::empty().expect("Should accept empty"),
                init: vec![vec![0, 0x81], vec![1]],
                dstack: vec![vec![0, 0x81]],
            },
        ]);
    }

    #[test]
    fn test_logical_ops() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpEqual::empty().expect("Should accept empty"),
                init: vec![vec![0, 1, 1, 0], vec![0, 1, 1, 0]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![0]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpEqual::empty().expect("Should accept empty"),
                init: vec![vec![0, 1, 1, 0], vec![0, 1, 1, 1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpBoolAnd::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpBoolAnd::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpBoolAnd::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpBoolAnd::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpBoolAnd::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![0x81]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpBoolOr::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpBoolOr::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpBoolOr::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpBoolOr::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpBoolOr::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpBoolOr::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpNumEqual::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpNumEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpNumEqual::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpNumEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpNumNotEqual::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpNumNotEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpNumNotEqual::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpNumNotEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpLessThan::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpLessThan::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpLessThan::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpLessThan::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpLessThan::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpLessThan::empty().expect("Should accept empty"),
                init: vec![vec![], vec![0x81]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpLessThan::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![0x81]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpLessThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpLessThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpLessThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpLessThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpLessThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpLessThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![0x81]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpLessThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![0x81]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpGreaterThan::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpGreaterThan::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpGreaterThan::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpGreaterThan::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpGreaterThan::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpGreaterThan::empty().expect("Should accept empty"),
                init: vec![vec![], vec![0x81]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpGreaterThan::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![0x81]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpGreaterThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpGreaterThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpGreaterThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpGreaterThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpGreaterThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpGreaterThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![], vec![0x81]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpGreaterThanOrEqual::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![0x81]],
                dstack: vec![vec![1]],
            },
        ]);
    }

    #[test]
    fn test_opdepth() {
        run_success_test_cases(vec![
            TestCase { code: opcodes::OpDepth::empty().expect("Should accept empty"), init: vec![], dstack: vec![vec![]] },
            TestCase {
                code: opcodes::OpDepth::empty().expect("Should accept empty"),
                init: vec![vec![]],
                dstack: vec![vec![], vec![1]],
            },
            TestCase {
                code: opcodes::OpDepth::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3]],
                dstack: vec![vec![1], vec![2], vec![3], vec![3]],
            },
        ]);
    }

    #[test]
    fn test_opdrop() {
        run_success_test_cases(vec![
            TestCase { code: opcodes::OpDrop::empty().expect("Should accept empty"), init: vec![vec![]], dstack: vec![] },
            TestCase {
                code: opcodes::OpDrop::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpDrop::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3], vec![3]],
                dstack: vec![vec![1], vec![2], vec![3]],
            },
        ]);

        run_error_test_cases(vec![ErrorTestCase {
            code: opcodes::OpDrop::empty().expect("Should accept empty"),
            init: vec![],
            error: TxScriptError::InvalidStackOperation(1, 0),
        }])
    }

    #[test]
    fn test_op2drop() {
        run_success_test_cases(vec![
            TestCase { code: opcodes::Op2Drop::empty().expect("Should accept empty"), init: vec![vec![], vec![1]], dstack: vec![] },
            TestCase {
                code: opcodes::Op2Drop::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3], vec![3]],
                dstack: vec![vec![1], vec![2]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::Op2Drop::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(2, 0),
            },
            ErrorTestCase {
                code: opcodes::Op2Drop::empty().expect("Should accept empty"),
                init: vec![vec![]],
                error: TxScriptError::InvalidStackOperation(2, 1),
            },
        ])
    }

    #[test]
    fn test_opdup() {
        run_success_test_cases(vec![
            TestCase { code: opcodes::OpDup::empty().expect("Should accept empty"), init: vec![vec![]], dstack: vec![vec![], vec![]] },
            TestCase {
                code: opcodes::OpDup::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![], vec![1], vec![1]],
            },
            TestCase {
                code: opcodes::OpDup::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3], vec![3]],
                dstack: vec![vec![1], vec![2], vec![3], vec![3], vec![3]],
            },
        ]);

        run_error_test_cases(vec![ErrorTestCase {
            code: opcodes::OpDup::empty().expect("Should accept empty"),
            init: vec![],
            error: TxScriptError::InvalidStackOperation(1, 0),
        }])
    }

    #[test]
    fn test_op2dup() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::Op2Dup::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![], vec![1], vec![], vec![1]],
            },
            TestCase {
                code: opcodes::Op2Dup::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3]],
                dstack: vec![vec![1], vec![2], vec![3], vec![2], vec![3]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::Op2Dup::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(2, 0),
            },
            ErrorTestCase {
                code: opcodes::Op2Dup::empty().expect("Should accept empty"),
                init: vec![vec![]],
                error: TxScriptError::InvalidStackOperation(2, 1),
            },
        ]);
    }

    #[test]
    fn test_op3dup() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::Op3Dup::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![], vec![1]],
                dstack: vec![vec![0x81], vec![], vec![1], vec![0x81], vec![], vec![1]],
            },
            TestCase {
                code: opcodes::Op3Dup::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3]],
                dstack: vec![vec![1], vec![2], vec![3], vec![1], vec![2], vec![3]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::Op3Dup::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(3, 0),
            },
            ErrorTestCase {
                code: opcodes::Op3Dup::empty().expect("Should accept empty"),
                init: vec![vec![]],
                error: TxScriptError::InvalidStackOperation(3, 1),
            },
            ErrorTestCase {
                code: opcodes::Op3Dup::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                error: TxScriptError::InvalidStackOperation(3, 2),
            },
        ]);
    }

    #[test]
    fn test_opnip() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpNip::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpNip::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpNip::empty().expect("Should accept empty"),
                init: vec![vec![2], vec![], vec![1]],
                dstack: vec![vec![2], vec![1]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::OpNip::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(2, 0),
            },
            ErrorTestCase {
                code: opcodes::OpNip::empty().expect("Should accept empty"),
                init: vec![vec![]],
                error: TxScriptError::InvalidStackOperation(2, 1),
            },
        ]);
    }

    #[test]
    fn test_opover() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpOver::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                dstack: vec![vec![], vec![1], vec![]],
            },
            TestCase {
                code: opcodes::OpOver::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                dstack: vec![vec![1], vec![], vec![1]],
            },
            TestCase {
                code: opcodes::OpOver::empty().expect("Should accept empty"),
                init: vec![vec![2], vec![], vec![1]],
                dstack: vec![vec![2], vec![], vec![1], vec![]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::OpOver::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(2, 0),
            },
            ErrorTestCase {
                code: opcodes::OpOver::empty().expect("Should accept empty"),
                init: vec![vec![]],
                error: TxScriptError::InvalidStackOperation(2, 1),
            },
        ]);
    }

    #[test]
    fn test_op2over() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::Op2Over::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![2], vec![], vec![1]],
                dstack: vec![vec![0x81], vec![2], vec![], vec![1], vec![0x81], vec![2]],
            },
            TestCase {
                code: opcodes::Op2Over::empty().expect("Should accept empty"),
                init: vec![vec![], vec![0x81], vec![2], vec![], vec![1]],
                dstack: vec![vec![], vec![0x81], vec![2], vec![], vec![1], vec![0x81], vec![2]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::Op2Over::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(4, 0),
            },
            ErrorTestCase {
                code: opcodes::Op2Over::empty().expect("Should accept empty"),
                init: vec![vec![]],
                error: TxScriptError::InvalidStackOperation(4, 1),
            },
            ErrorTestCase {
                code: opcodes::Op2Over::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                error: TxScriptError::InvalidStackOperation(4, 2),
            },
            ErrorTestCase {
                code: opcodes::Op2Over::empty().expect("Should accept empty"),
                init: vec![vec![], vec![], vec![]],
                error: TxScriptError::InvalidStackOperation(4, 3),
            },
        ]);
    }

    #[test]
    fn test_oppick() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpPick::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![vec![], vec![]],
            },
            TestCase {
                code: opcodes::OpPick::empty().expect("Should accept empty"),
                init: vec![vec![2], vec![], vec![1]],
                dstack: vec![vec![2], vec![], vec![2]],
            },
            TestCase {
                code: opcodes::OpPick::empty().expect("Should accept empty"),
                init: vec![vec![5], vec![4], vec![3], vec![], vec![2]],
                dstack: vec![vec![5], vec![4], vec![3], vec![], vec![4]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::OpPick::empty().expect("Should accept empty"),
                init: vec![vec![5], vec![4], vec![3], vec![], vec![4]],
                error: TxScriptError::InvalidState("pick at an invalid location".to_string()),
            },
            ErrorTestCase {
                code: opcodes::OpPick::empty().expect("Should accept empty"),
                init: vec![vec![5], vec![4], vec![3], vec![], vec![0x81]],
                error: TxScriptError::InvalidState("pick at an invalid location".to_string()),
            },
        ])
    }

    #[test]
    fn test_oproll() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpRoll::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpRoll::empty().expect("Should accept empty"),
                init: vec![vec![2], vec![], vec![1]],
                dstack: vec![vec![], vec![2]],
            },
            TestCase {
                code: opcodes::OpRoll::empty().expect("Should accept empty"),
                init: vec![vec![5], vec![4], vec![3], vec![], vec![2]],
                dstack: vec![vec![5], vec![3], vec![], vec![4]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::OpRoll::empty().expect("Should accept empty"),
                init: vec![vec![5], vec![4], vec![3], vec![], vec![4]],
                error: TxScriptError::InvalidState("roll at an invalid location".to_string()),
            },
            ErrorTestCase {
                code: opcodes::OpRoll::empty().expect("Should accept empty"),
                init: vec![vec![5], vec![4], vec![3], vec![], vec![0x81]],
                error: TxScriptError::InvalidState("roll at an invalid location".to_string()),
            },
        ])
    }

    #[test]
    fn test_oprot() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpRot::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3]],
                dstack: vec![vec![2], vec![3], vec![1]],
            },
            TestCase {
                code: opcodes::OpRot::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1], vec![2], vec![3]],
                dstack: vec![vec![], vec![2], vec![3], vec![1]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::OpRot::empty().expect("Should accept empty"),
                init: vec![vec![2], vec![3]],
                error: TxScriptError::InvalidStackOperation(3, 2),
            },
            ErrorTestCase {
                code: opcodes::OpRot::empty().expect("Should accept empty"),
                init: vec![vec![3]],
                error: TxScriptError::InvalidStackOperation(3, 1),
            },
            ErrorTestCase {
                code: opcodes::OpRot::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(3, 0),
            },
        ]);
    }

    #[test]
    fn test_op2rot() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::Op2Rot::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3], vec![4], vec![5], vec![6]],
                dstack: vec![vec![3], vec![4], vec![5], vec![6], vec![1], vec![2]],
            },
            TestCase {
                code: opcodes::Op2Rot::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1], vec![2], vec![3], vec![4], vec![5], vec![6]],
                dstack: vec![vec![], vec![3], vec![4], vec![5], vec![6], vec![1], vec![2]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::Op2Rot::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3], vec![4], vec![5]],
                error: TxScriptError::InvalidStackOperation(6, 5),
            },
            ErrorTestCase {
                code: opcodes::Op2Rot::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3], vec![4]],
                error: TxScriptError::InvalidStackOperation(6, 4),
            },
            ErrorTestCase {
                code: opcodes::Op2Rot::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3]],
                error: TxScriptError::InvalidStackOperation(6, 3),
            },
            ErrorTestCase {
                code: opcodes::Op2Rot::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2]],
                error: TxScriptError::InvalidStackOperation(6, 2),
            },
            ErrorTestCase {
                code: opcodes::Op2Rot::empty().expect("Should accept empty"),
                init: vec![vec![1]],
                error: TxScriptError::InvalidStackOperation(6, 1),
            },
            ErrorTestCase {
                code: opcodes::Op2Rot::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(6, 0),
            },
        ]);
    }

    #[test]
    fn test_opswap() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpSwap::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2]],
                dstack: vec![vec![2], vec![1]],
            },
            TestCase {
                code: opcodes::OpSwap::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1], vec![5]],
                dstack: vec![vec![], vec![5], vec![1]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::OpSwap::empty().expect("Should accept empty"),
                init: vec![vec![1]],
                error: TxScriptError::InvalidStackOperation(2, 1),
            },
            ErrorTestCase {
                code: opcodes::OpSwap::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(2, 0),
            },
        ]);
    }

    #[test]
    fn test_op2swap() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::Op2Swap::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2], vec![3], vec![4]],
                dstack: vec![vec![3], vec![4], vec![1], vec![2]],
            },
            TestCase {
                code: opcodes::Op2Swap::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1], vec![2], vec![3], vec![4]],
                dstack: vec![vec![], vec![3], vec![4], vec![1], vec![2]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::Op2Swap::empty().expect("Should accept empty"),
                init: vec![vec![], vec![2], vec![1]],
                error: TxScriptError::InvalidStackOperation(4, 3),
            },
            ErrorTestCase {
                code: opcodes::Op2Swap::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1]],
                error: TxScriptError::InvalidStackOperation(4, 2),
            },
            ErrorTestCase {
                code: opcodes::Op2Swap::empty().expect("Should accept empty"),
                init: vec![vec![1]],
                error: TxScriptError::InvalidStackOperation(4, 1),
            },
            ErrorTestCase {
                code: opcodes::Op2Swap::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(4, 0),
            },
        ]);
    }

    #[test]
    fn test_optuck() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpTuck::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![2]],
                dstack: vec![vec![2], vec![1], vec![2]],
            },
            TestCase {
                code: opcodes::OpTuck::empty().expect("Should accept empty"),
                init: vec![vec![3], vec![9], vec![2]],
                dstack: vec![vec![3], vec![2], vec![9], vec![2]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::OpTuck::empty().expect("Should accept empty"),
                init: vec![vec![3]],
                error: TxScriptError::InvalidStackOperation(2, 1),
            },
            ErrorTestCase {
                code: opcodes::OpTuck::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(2, 0),
            },
        ]);
    }

    #[test]
    fn test_opequalverify() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpEqualVerify::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![],
            },
            TestCase {
                code: opcodes::OpEqualVerify::empty().expect("Should accept empty"),
                init: vec![vec![], vec![1, 0, 1], vec![1, 0, 1]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpNumEqualVerify::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                dstack: vec![],
            },
            TestCase {
                code: opcodes::OpNumEqualVerify::empty().expect("Should accept empty"),
                init: vec![vec![], vec![0, 0, 1], vec![0, 0, 1]],
                dstack: vec![vec![]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::OpEqualVerify::empty().expect("Should accept empty"),
                init: vec![vec![], vec![2, 0, 1], vec![1, 0, 1]],
                error: TxScriptError::VerifyError,
            },
            ErrorTestCase {
                code: opcodes::OpEqualVerify::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                error: TxScriptError::VerifyError,
            },
            ErrorTestCase {
                code: opcodes::OpNumEqualVerify::empty().expect("Should accept empty"),
                init: vec![vec![], vec![2, 0, 1], vec![1, 0, 1]],
                error: TxScriptError::VerifyError,
            },
            ErrorTestCase {
                code: opcodes::OpNumEqualVerify::empty().expect("Should accept empty"),
                init: vec![vec![1], vec![]],
                error: TxScriptError::VerifyError,
            },
        ]);
    }

    #[test]
    fn test_opsize() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpSize::empty().expect("Should accept empty"),
                init: vec![vec![]],
                dstack: vec![vec![], vec![]],
            },
            TestCase {
                code: opcodes::OpSize::empty().expect("Should accept empty"),
                init: vec![vec![5]],
                dstack: vec![vec![5], vec![1]],
            },
            TestCase {
                code: opcodes::OpSize::empty().expect("Should accept empty"),
                init: vec![vec![0x80, 1]],
                dstack: vec![vec![0x80, 1], vec![2]],
            },
        ]);

        run_error_test_cases(vec![ErrorTestCase {
            code: opcodes::OpSize::empty().expect("Should accept empty"),
            init: vec![],
            error: TxScriptError::InvalidStackOperation(1, 0),
        }]);
    }

    #[test]
    fn test_opwithin() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpWithin::empty().expect("Should accept empty"),
                init: vec![vec![], vec![], vec![1]],
                dstack: vec![vec![1]],
            },
            TestCase {
                code: opcodes::OpWithin::empty().expect("Should accept empty"),
                init: vec![vec![], vec![], vec![]],
                dstack: vec![vec![]],
            },
            TestCase {
                code: opcodes::OpWithin::empty().expect("Should accept empty"),
                init: vec![vec![0x81], vec![0x91], vec![1]],
                dstack: vec![vec![1]],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::OpWithin::empty().expect("Should accept empty"),
                init: vec![vec![], vec![]],
                error: TxScriptError::InvalidStackOperation(3, 2),
            },
            ErrorTestCase {
                code: opcodes::OpWithin::empty().expect("Should accept empty"),
                init: vec![vec![]],
                error: TxScriptError::InvalidStackOperation(3, 1),
            },
            ErrorTestCase {
                code: opcodes::OpWithin::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(3, 0),
            },
        ]);
    }

    #[test]
    fn test_opsha256() {
        // Some test vectors from https://www.dlitz.net/crypto/shad256-test-vectors/
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpSHA256::empty().expect("Should accept empty"),
                init: vec![vec![]],
                dstack: vec![b"\xe3\xb0\xc4\x42\x98\xfc\x1c\x14\x9a\xfb\xf4\xc8\x99\x6f\xb9\x24\x27\xae\x41\xe4\x64\x9b\x93\x4c\xa4\x95\x99\x1b\x78\x52\xb8\x55".to_vec()],
            },
            TestCase {
                code: opcodes::OpSHA256::empty().expect("Should accept empty"),
                init: vec![b"abc".to_vec()],
                dstack: vec![b"\xba\x78\x16\xbf\x8f\x01\xcf\xea\x41\x41\x40\xde\x5d\xae\x22\x23\xb0\x03\x61\xa3\x96\x17\x7a\x9c\xb4\x10\xff\x61\xf2\x00\x15\xad".to_vec()],
            },
            TestCase {
                code: opcodes::OpSHA256::empty().expect("Should accept empty"),
                init: vec![b"\xde\x18\x89\x41\xa3\x37\x5d\x3a\x8a\x06\x1e\x67\x57\x6e\x92\x6d".to_vec()],
                dstack: vec![b"\x06\x7c\x53\x12\x69\x73\x5c\xa7\xf5\x41\xfd\xac\xa8\xf0\xdc\x76\x30\x5d\x3c\xad\xa1\x40\xf8\x93\x72\xa4\x10\xfe\x5e\xff\x6e\x4d".to_vec()],
            },
        ]);

        run_error_test_cases(vec![ErrorTestCase {
            code: opcodes::OpSHA256::empty().expect("Should accept empty"),
            init: vec![],
            error: TxScriptError::InvalidStackOperation(1, 0),
        }]);
    }

    #[test]
    fn test_opblake2b() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpBlake2b::empty().expect("Should accept empty"),
                init: vec![b"".to_vec()],
                dstack: vec![b"\x0e\x57\x51\xc0\x26\xe5\x43\xb2\xe8\xab\x2e\xb0\x60\x99\xda\xa1\xd1\xe5\xdf\x47\x77\x8f\x77\x87\xfa\xab\x45\xcd\xf1\x2f\xe3\xa8".to_vec()],
            },
            TestCase {
                code: opcodes::OpBlake2b::empty().expect("Should accept empty"),
                init: vec![b"abc".to_vec()],
                dstack: vec![b"\xbd\xdd\x81\x3c\x63\x42\x39\x72\x31\x71\xef\x3f\xee\x98\x57\x9b\x94\x96\x4e\x3b\xb1\xcb\x3e\x42\x72\x62\xc8\xc0\x68\xd5\x23\x19".to_vec()],
            },
        ]);

        run_error_test_cases(vec![ErrorTestCase {
            code: opcodes::OpBlake2b::empty().expect("Should accept empty"),
            init: vec![],
            error: TxScriptError::InvalidStackOperation(1, 0),
        }]);
    }

    #[test]
    fn test_opnop() {
        run_success_test_cases(vec![TestCase {
            code: opcodes::OpNop::empty().expect("Should accept empty"),
            init: vec![vec![], vec![1], vec![2]],
            dstack: vec![vec![], vec![1], vec![2]],
        }]);
    }

    #[derive(Clone)]
    struct VerifiableTransactionMock(Transaction);

    impl VerifiableTransaction for VerifiableTransactionMock {
        fn tx(&self) -> &Transaction {
            &self.0
        }

        fn populated_input(&self, _index: usize) -> (&TransactionInput, &UtxoEntry) {
            unimplemented!()
        }
        fn utxo(&self, _index: usize) -> Option<&UtxoEntry> {
            unimplemented!()
        }
    }

    fn make_mock_transaction(lock_time: u64) -> (VerifiableTransactionMock, TransactionInput, UtxoEntry) {
        let dummy_prev_out = TransactionOutpoint::new(kaspa_hashes::Hash::from_u64_word(1), 1);
        let dummy_sig_script = vec![0u8; 65];
        let dummy_tx_input = TransactionInput::new(dummy_prev_out, dummy_sig_script, 10, 1);
        let addr_hash = vec![1u8; 32];

        let addr = Address::new(Prefix::Testnet, Version::PubKey, &addr_hash);
        let dummy_script_public_key = pay_to_address_script(&addr);
        let dummy_tx_out = TransactionOutput::new(SOMPI_PER_KASPA, dummy_script_public_key);

        let tx = VerifiableTransactionMock(Transaction::new(
            TX_VERSION + 1,
            vec![dummy_tx_input.clone()],
            vec![dummy_tx_out.clone()],
            lock_time,
            SUBNETWORK_ID_NATIVE,
            0,
            vec![],
        ));
        let utxo_entry = UtxoEntry::new(0, ScriptPublicKey::default(), 0, false, None);
        (tx, dummy_tx_input, utxo_entry)
    }

    #[test]
    fn test_opchecklocktimeverify() {
        // Everything we need to build a script source
        let (base_tx, input, utxo_entry) = make_mock_transaction(1);

        let sig_cache = Cache::new(10_000);
        let reused_values = SigHashReusedValuesUnsync::new();
        let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);

        let code = opcodes::OpCheckLockTimeVerify::empty().expect("Should accept empty");

        for (tx_lock_time, lock_time, should_fail) in [
            (1u64, vec![], false),                                // Case 1: 0 = locktime < txLockTime
            (0x800000, vec![0x7f, 0, 0], false),                  // Case 2: 0 < locktime < txLockTime
            (0x800000, vec![0x7f, 0, 0, 0, 0, 0, 0, 0, 0], true), // Case 3: locktime too big
            (LOCK_TIME_THRESHOLD * 2, vec![0x7f, 0, 0, 0], true), // Case 4: lock times are inconsistent
        ] {
            let mut tx = base_tx.clone();
            tx.0.lock_time = tx_lock_time;
            let mut vm = TxScriptEngine::from_transaction_input(&tx, &input, 0, &utxo_entry, ctx, Default::default());
            vm.dstack = vec![lock_time.clone()].into();
            match code.execute(&mut vm) {
                // Message is based on the should_fail values
                Ok(()) => assert!(
                    !should_fail,
                    "Opcode {} must fail (tx_lock_time: {}, lock_time: {:?})",
                    code.value(),
                    tx_lock_time,
                    lock_time
                ),
                Err(e) => assert!(
                    should_fail,
                    "Opcode {} should not fail. Got {} (tx_lock_time: {}, lock_time: {:?})",
                    code.value(),
                    e,
                    tx_lock_time,
                    lock_time
                ),
            }
        }
    }

    #[test]
    fn test_opchecksequencerify() {
        // Everything we need to build a script source
        let (tx, base_input, utxo_entry) = make_mock_transaction(1);

        let sig_cache = Cache::new(10_000);
        let reused_values = SigHashReusedValuesUnsync::new();
        let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);

        let code = opcodes::OpCheckSequenceVerify::empty().expect("Should accept empty");

        for (tx_sequence, sequence, should_fail) in [
            (1u64, vec![], false),                                // Case 1: 0 = sequence < tx_sequence
            (0x800000, vec![0x7f, 0, 0], false),                  // Case 2: 0 < sequence < tx_sequence
            (0x800000, vec![0x7f, 0, 0, 0, 0, 0, 0, 0, 0], true), // Case 3: sequence too big
            (1 << 63, vec![0x7f, 0, 0], true),                    // Case 4: disabled
            ((1 << 63) | 0xffff, vec![0x7f, 0, 0], true),         // Case 5: another disabled
        ] {
            let mut input = base_input.clone();
            input.sequence = tx_sequence;
            let mut vm = TxScriptEngine::from_transaction_input(&tx, &input, 0, &utxo_entry, ctx, Default::default());
            vm.dstack = vec![sequence.clone()].into();
            match code.execute(&mut vm) {
                // Message is based on the should_fail values
                Ok(()) => {
                    assert!(!should_fail, "Opcode {} must fail (tx_sequence: {}, sequence: {:?})", code.value(), tx_sequence, sequence)
                }
                Err(e) => assert!(
                    should_fail,
                    "Opcode {} should not fail. Got {} (tx_sequence: {}, sequence: {:?})",
                    code.value(),
                    e,
                    tx_sequence,
                    sequence
                ),
            }
        }
    }

    #[test]
    fn test_opreturn() {
        run_error_test_cases(vec![ErrorTestCase {
            code: opcodes::OpReturn::empty().expect("Should accept empty"),
            init: vec![],
            error: TxScriptError::EarlyReturn,
        }]);
    }

    #[test]
    fn test_opverify() {
        run_success_test_cases(vec![
            TestCase { code: opcodes::OpVerify::empty().expect("Should accept empty"), init: vec![vec![1]], dstack: vec![] },
            TestCase { code: opcodes::OpVerify::empty().expect("Should accept empty"), init: vec![vec![0x81]], dstack: vec![] },
            TestCase { code: opcodes::OpVerify::empty().expect("Should accept empty"), init: vec![vec![0x80, 0]], dstack: vec![] },
            TestCase {
                code: opcodes::OpVerify::empty().expect("Should accept empty"),
                init: vec![vec![1, 0, 0, 0, 0]],
                dstack: vec![],
            },
        ]);

        run_error_test_cases(vec![
            ErrorTestCase {
                code: opcodes::OpVerify::empty().expect("Should accept empty"),
                init: vec![vec![0, 0, 0, 0x80]],
                error: TxScriptError::VerifyError,
            },
            ErrorTestCase {
                code: opcodes::OpVerify::empty().expect("Should accept empty"),
                init: vec![vec![0, 0, 0, 0]],
                error: TxScriptError::VerifyError,
            },
            ErrorTestCase {
                code: opcodes::OpVerify::empty().expect("Should accept empty"),
                init: vec![vec![0x80]],
                error: TxScriptError::VerifyError,
            },
            ErrorTestCase {
                code: opcodes::OpVerify::empty().expect("Should accept empty"),
                init: vec![vec![0]],
                error: TxScriptError::VerifyError,
            },
            ErrorTestCase {
                code: opcodes::OpVerify::empty().expect("Should accept empty"),
                init: vec![vec![]],
                error: TxScriptError::VerifyError,
            },
            ErrorTestCase {
                code: opcodes::OpVerify::empty().expect("Should accept empty"),
                init: vec![],
                error: TxScriptError::InvalidStackOperation(1, 0),
            },
        ])
    }

    #[test]
    fn test_opifdup() {
        run_success_test_cases(vec![
            TestCase {
                code: opcodes::OpIfDup::empty().expect("Should accept empty"),
                init: vec![vec![1]],
                dstack: vec![vec![1], vec![1]],
            },
            TestCase {
                code: opcodes::OpIfDup::empty().expect("Should accept empty"),
                init: vec![vec![0x80, 0]],
                dstack: vec![vec![0x80, 0], vec![0x80, 0]],
            },
            TestCase { code: opcodes::OpIfDup::empty().expect("Should accept empty"), init: vec![vec![]], dstack: vec![vec![]] },
            TestCase {
                code: opcodes::OpIfDup::empty().expect("Should accept empty"),
                init: vec![vec![0x80]],
                dstack: vec![vec![0x80]],
            },
            TestCase {
                code: opcodes::OpIfDup::empty().expect("Should accept empty"),
                init: vec![vec![0, 0x80]],
                dstack: vec![vec![0, 0x80]],
            },
            TestCase { code: opcodes::OpIfDup::empty().expect("Should accept empty"), init: vec![vec![]], dstack: vec![vec![]] },
        ])
    }

    mod kip10 {
        use super::*;
        use crate::{
            SpkEncoding,
            data_stack::OpcodeData,
            opcodes::{codes::*, push_number},
            pay_to_script_hash_script,
            script_builder::ScriptBuilder,
        };
        use kaspa_consensus_core::tx::MutableTransaction;

        #[derive(Clone, Debug)]
        struct Kip10Mock {
            spk: ScriptPublicKey,
            amount: u64,
        }

        fn create_mock_spk(value: u8) -> ScriptPublicKey {
            let pub_key = vec![value; 32];
            let addr = Address::new(Prefix::Testnet, Version::PubKey, &pub_key);
            pay_to_address_script(&addr)
        }

        fn kip_10_tx_mock(inputs: Vec<Kip10Mock>, outputs: Vec<Kip10Mock>) -> (Transaction, Vec<UtxoEntry>) {
            let dummy_prev_out = TransactionOutpoint::new(kaspa_hashes::Hash::from_u64_word(1), 1);
            let dummy_sig_script = vec![0u8; 65];
            let (utxos, tx_inputs) = inputs
                .into_iter()
                .map(|Kip10Mock { spk, amount }| {
                    (
                        UtxoEntry::new(amount, spk, 0, false, None),
                        TransactionInput::new(dummy_prev_out, dummy_sig_script.clone(), 10, 0),
                    )
                })
                .unzip();

            let tx_out = outputs.into_iter().map(|Kip10Mock { spk, amount }| TransactionOutput::new(amount, spk));

            let tx = Transaction::new(TX_VERSION + 1, tx_inputs, tx_out.collect(), 0, SUBNETWORK_ID_NATIVE, 0, vec![]);
            (tx, utxos)
        }

        #[derive(Debug)]
        struct TestGroup {
            name: &'static str,
            test_cases: Vec<TestCase>,
        }

        #[derive(Debug)]
        enum Operation {
            InputSpk,
            OutputSpk,
            InputAmount,
            OutputAmount,
        }

        #[derive(Debug)]
        enum TestCase {
            Successful { operation: Operation, index: i64, expected_result: ExpectedResult },
            Incorrect { operation: Operation, index: Option<i64>, expected_error: TxScriptError },
        }

        #[derive(Debug)]
        struct ExpectedResult {
            expected_spk: Option<Vec<u8>>,
            expected_amount: Option<Vec<u8>>,
        }

        fn execute_test_group(group: &TestGroup) {
            let input_spk1 = create_mock_spk(1);
            let input_spk2 = create_mock_spk(2);
            let output_spk1 = create_mock_spk(3);
            let output_spk2 = create_mock_spk(4);

            let inputs = vec![
                Kip10Mock { spk: input_spk1.clone(), amount: 1111 },
                Kip10Mock { spk: input_spk2.clone(), amount: 2222 },
                Kip10Mock { spk: create_mock_spk(5), amount: 5555 },
            ];
            let outputs =
                vec![Kip10Mock { spk: output_spk1.clone(), amount: 3333 }, Kip10Mock { spk: output_spk2.clone(), amount: 4444 }];

            let (tx, utxo_entries) = kip_10_tx_mock(inputs, outputs);
            let tx = PopulatedTransaction::new(&tx, utxo_entries);
            let sig_cache = Cache::new(10_000);
            let reused_values = SigHashReusedValuesUnsync::new();
            let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);

            for current_idx in 0..tx.inputs().len() {
                let mut vm = TxScriptEngine::from_transaction_input(
                    &tx,
                    &tx.inputs()[current_idx],
                    current_idx,
                    tx.utxo(current_idx).unwrap(),
                    ctx,
                    Default::default(),
                );

                // Check input index opcode first
                let op_input_idx = opcodes::OpTxInputIndex::empty().expect("Should accept empty");

                let mut expected = vm.dstack.clone();
                expected.push_item(current_idx as i64).unwrap();
                op_input_idx.execute(&mut vm).unwrap();
                assert_eq!(vm.dstack, expected);
                vm.dstack.clear();

                // Prepare opcodes
                let op_input_spk = opcodes::OpTxInputSpk::empty().expect("Should accept empty");
                let op_output_spk = opcodes::OpTxOutputSpk::empty().expect("Should accept empty");
                let op_input_amount = opcodes::OpTxInputAmount::empty().expect("Should accept empty");
                let op_output_amount = opcodes::OpTxOutputAmount::empty().expect("Should accept empty");

                // Execute each test case
                for test_case in &group.test_cases {
                    match test_case {
                        TestCase::Successful { operation, index, expected_result } => {
                            push_number(*index, &mut vm).unwrap();
                            let result = match operation {
                                Operation::InputSpk => op_input_spk.execute(&mut vm),
                                Operation::OutputSpk => op_output_spk.execute(&mut vm),
                                Operation::InputAmount => op_input_amount.execute(&mut vm),
                                Operation::OutputAmount => op_output_amount.execute(&mut vm),
                            };
                            assert!(result.is_ok());

                            // Check the result matches expectations
                            if let Some(ref expected_spk) = expected_result.expected_spk {
                                assert_eq!(vm.dstack.inner(), vec![StackEntry::from_vec(expected_spk.clone())]);
                            }
                            if let Some(ref expected_amount) = expected_result.expected_amount {
                                assert_eq!(vm.dstack.inner(), vec![StackEntry::from_vec(expected_amount.clone())]);
                            }
                            vm.dstack.clear();
                        }
                        TestCase::Incorrect { operation, index, expected_error } => {
                            if let Some(idx) = index {
                                push_number(*idx, &mut vm).unwrap();
                            }

                            let result = match operation {
                                Operation::InputSpk => op_input_spk.execute(&mut vm),
                                Operation::OutputSpk => op_output_spk.execute(&mut vm),
                                Operation::InputAmount => op_input_amount.execute(&mut vm),
                                Operation::OutputAmount => op_output_amount.execute(&mut vm),
                            };

                            assert_eq!(result, Err(expected_error.clone()));
                            vm.dstack.clear();
                        }
                    }
                }
            }
        }

        #[test]
        fn test_unary_introspection_ops() {
            let test_groups = vec![
                TestGroup {
                    name: "Valid input indices",
                    test_cases: vec![
                        TestCase::Successful {
                            operation: Operation::InputSpk,
                            index: 0,
                            expected_result: ExpectedResult {
                                expected_spk: Some(create_mock_spk(1).to_bytes()),
                                expected_amount: None,
                            },
                        },
                        TestCase::Successful {
                            operation: Operation::InputSpk,
                            index: 1,
                            expected_result: ExpectedResult {
                                expected_spk: Some(create_mock_spk(2).to_bytes()),
                                expected_amount: None,
                            },
                        },
                        TestCase::Successful {
                            operation: Operation::InputAmount,
                            index: 0,
                            expected_result: ExpectedResult {
                                expected_spk: None,
                                expected_amount: Some(OpcodeData::<i64>::serialize(&1111).unwrap()),
                            },
                        },
                        TestCase::Successful {
                            operation: Operation::InputAmount,
                            index: 1,
                            expected_result: ExpectedResult {
                                expected_spk: None,
                                expected_amount: Some(OpcodeData::<i64>::serialize(&2222).unwrap()),
                            },
                        },
                    ],
                },
                TestGroup {
                    name: "Valid output indices",
                    test_cases: vec![
                        TestCase::Successful {
                            operation: Operation::OutputSpk,
                            index: 0,
                            expected_result: ExpectedResult {
                                expected_spk: Some(create_mock_spk(3).to_bytes()),
                                expected_amount: None,
                            },
                        },
                        TestCase::Successful {
                            operation: Operation::OutputSpk,
                            index: 1,
                            expected_result: ExpectedResult {
                                expected_spk: Some(create_mock_spk(4).to_bytes()),
                                expected_amount: None,
                            },
                        },
                        TestCase::Successful {
                            operation: Operation::OutputAmount,
                            index: 0,
                            expected_result: ExpectedResult {
                                expected_spk: None,
                                expected_amount: Some(OpcodeData::<i64>::serialize(&3333).unwrap()),
                            },
                        },
                        TestCase::Successful {
                            operation: Operation::OutputAmount,
                            index: 1,
                            expected_result: ExpectedResult {
                                expected_spk: None,
                                expected_amount: Some(OpcodeData::<i64>::serialize(&4444).unwrap()),
                            },
                        },
                    ],
                },
                TestGroup {
                    name: "Error cases",
                    test_cases: vec![
                        TestCase::Incorrect {
                            operation: Operation::InputAmount,
                            index: None,
                            expected_error: TxScriptError::InvalidStackOperation(1, 0),
                        },
                        TestCase::Incorrect {
                            operation: Operation::InputAmount,
                            index: Some(-1),
                            expected_error: TxScriptError::InvalidInputIndex(-1, 3),
                        },
                        TestCase::Incorrect {
                            operation: Operation::InputAmount,
                            index: Some(3),
                            expected_error: TxScriptError::InvalidInputIndex(3, 3),
                        },
                        TestCase::Incorrect {
                            operation: Operation::OutputAmount,
                            index: None,
                            expected_error: TxScriptError::InvalidStackOperation(1, 0),
                        },
                        TestCase::Incorrect {
                            operation: Operation::OutputAmount,
                            index: Some(-1),
                            expected_error: TxScriptError::InvalidOutputIndex(-1, 2),
                        },
                        TestCase::Incorrect {
                            operation: Operation::OutputAmount,
                            index: Some(2),
                            expected_error: TxScriptError::InvalidOutputIndex(2, 2),
                        },
                        TestCase::Incorrect {
                            operation: Operation::OutputSpk,
                            index: Some(2),
                            expected_error: TxScriptError::InvalidOutputIndex(2, 2),
                        },
                    ],
                },
            ];

            for group in test_groups {
                println!("Running test group: {}", group.name);
                execute_test_group(&group);
            }
        }
        fn create_mock_tx(input_count: usize, output_count: usize) -> (Transaction, Vec<UtxoEntry>) {
            let dummy_prev_out = TransactionOutpoint::new(kaspa_hashes::Hash::from_u64_word(1), 1);
            let dummy_sig_script = vec![0u8; 65];

            // Create inputs with different SPKs and amounts
            let inputs: Vec<Kip10Mock> =
                (0..input_count).map(|i| Kip10Mock { spk: create_mock_spk(i as u8), amount: 1000 + i as u64 }).collect();

            // Create outputs with different SPKs and amounts
            let outputs: Vec<Kip10Mock> =
                (0..output_count).map(|i| Kip10Mock { spk: create_mock_spk((100 + i) as u8), amount: 2000 + i as u64 }).collect();

            let (utxos, tx_inputs): (Vec<_>, Vec<_>) = inputs
                .into_iter()
                .map(|Kip10Mock { spk, amount }| {
                    (
                        UtxoEntry::new(amount, spk, 0, false, None),
                        TransactionInput::new(dummy_prev_out, dummy_sig_script.clone(), 10, 0),
                    )
                })
                .unzip();

            let tx_outputs: Vec<_> =
                outputs.into_iter().map(|Kip10Mock { spk, amount }| TransactionOutput::new(amount, spk)).collect();

            let tx = Transaction::new(TX_VERSION + 1, tx_inputs, tx_outputs, 0, SUBNETWORK_ID_NATIVE, 0, vec![]);

            (tx, utxos)
        }

        #[test]
        fn test_op_input_output_count() {
            // Test cases with different input/output combinations
            let test_cases = vec![
                (1, 0), // Minimum inputs, no outputs
                (1, 1), // Minimum inputs, one output
                (1, 2), // Minimum inputs, multiple outputs
                (2, 1), // Multiple inputs, one output
                (3, 2), // Multiple inputs, multiple outputs
                (5, 3), // More inputs than outputs
                (2, 4), // More outputs than inputs
            ];

            for (input_count, output_count) in test_cases {
                let (tx, utxo_entries) = create_mock_tx(input_count, output_count);
                let tx = PopulatedTransaction::new(&tx, utxo_entries);
                let sig_cache = Cache::new(10_000);
                let reused_values = SigHashReusedValuesUnsync::new();
                let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);

                let mut vm = TxScriptEngine::from_transaction_input(
                    &tx,
                    &tx.inputs()[0], // Use first input
                    0,
                    tx.utxo(0).unwrap(),
                    ctx,
                    Default::default(),
                );

                let op_input_count = opcodes::OpTxInputCount::empty().expect("Should accept empty");
                let op_output_count = opcodes::OpTxOutputCount::empty().expect("Should accept empty");

                // Test input count
                op_input_count.execute(&mut vm).unwrap();
                assert_eq!(
                    vm.dstack.inner(),
                    vec![<StackEntry as OpcodeData<i64>>::serialize(&(input_count as i64)).unwrap()],
                    "Input count mismatch for {} inputs",
                    input_count
                );
                vm.dstack.clear();

                // Test output count
                op_output_count.execute(&mut vm).unwrap();
                assert_eq!(
                    vm.dstack.inner(),
                    vec![<StackEntry as OpcodeData<i64>>::serialize(&(output_count as i64)).unwrap()],
                    "Output count mismatch for {} outputs",
                    output_count
                );
                vm.dstack.clear();
            }
        }

        #[test]
        fn test_output_amount() {
            // Create script: 0 OP_OUTPUTAMOUNT 100 EQUAL
            let redeem_script = ScriptBuilder::new()
                .add_op(Op0)
                .unwrap()
                .add_op(OpTxOutputAmount)
                .unwrap()
                .add_i64(100)
                .unwrap()
                .add_op(OpEqual)
                .unwrap()
                .drain();

            let spk = pay_to_script_hash_script(&redeem_script);

            // Create transaction with output amount 100
            let input_mock = Kip10Mock { spk: spk.clone(), amount: 200 };
            let output_mock = Kip10Mock { spk: create_mock_spk(1), amount: 100 };

            let (tx, utxo_entries) = kip_10_tx_mock(vec![input_mock.clone()], vec![output_mock]);
            let mut tx = MutableTransaction::with_entries(tx, utxo_entries);

            // Set signature script to push redeem script
            tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

            let tx = tx.as_verifiable();
            let sig_cache = Cache::new(10_000);
            let reused_values = SigHashReusedValuesUnsync::new();
            let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);

            // Test success case
            {
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

                assert_eq!(vm.execute(), Ok(()));
            }

            // Test failure case with wrong amount
            {
                let output_mock = Kip10Mock {
                    spk: create_mock_spk(1),
                    amount: 99, // Wrong amount
                };
                let (tx, utxo_entries) = kip_10_tx_mock(vec![input_mock.clone()], vec![output_mock]);
                let mut tx = MutableTransaction::with_entries(tx, utxo_entries);
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

                assert_eq!(vm.execute(), Err(TxScriptError::EvalFalse));
            }
        }

        #[test]
        fn test_input_amount() {
            // Create script: 0 OP_INPUTAMOUNT 200 EQUAL
            let redeem_script = ScriptBuilder::new()
                .add_op(Op0)
                .unwrap()
                .add_op(OpTxInputAmount)
                .unwrap()
                .add_i64(200)
                .unwrap()
                .add_op(OpEqual)
                .unwrap()
                .drain();
            let sig_cache = Cache::new(10_000);
            let reused_values = SigHashReusedValuesUnsync::new();
            let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);
            let spk = pay_to_script_hash_script(&redeem_script);

            // Test success case
            {
                let input_mock = Kip10Mock { spk: spk.clone(), amount: 200 };
                let output_mock = Kip10Mock { spk: create_mock_spk(1), amount: 100 };

                let (tx, utxo_entries) = kip_10_tx_mock(vec![input_mock], vec![output_mock]);
                let mut tx = MutableTransaction::with_entries(tx, utxo_entries);
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();
                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

                assert_eq!(vm.execute(), Ok(()));
            }

            // Test failure case
            {
                let input_mock = Kip10Mock {
                    spk: spk.clone(),
                    amount: 199, // Wrong amount
                };
                let output_mock = Kip10Mock { spk: create_mock_spk(1), amount: 100 };

                let (tx, utxo_entries) = kip_10_tx_mock(vec![input_mock], vec![output_mock]);
                let mut tx = MutableTransaction::with_entries(tx, utxo_entries);
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

                assert_eq!(vm.execute(), Err(TxScriptError::EvalFalse));
            }
        }

        #[test]
        fn test_input_spk_basic() {
            let sig_cache = Cache::new(10_000);
            let reused_values = SigHashReusedValuesUnsync::new();
            let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);

            // Create script: 0 OP_INPUTSPK OpNop
            // Just verify that OpInputSpk pushes something onto stack
            let redeem_script = ScriptBuilder::new().add_ops(&[Op0, OpTxInputSpk, OpNop]).unwrap().drain();
            let spk = pay_to_script_hash_script(&redeem_script);

            let (tx, utxo_entries) = kip_10_tx_mock(vec![Kip10Mock { spk, amount: 100 }], vec![]);
            let mut tx = MutableTransaction::with_entries(tx, utxo_entries);
            tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

            let tx = tx.as_verifiable();
            let mut vm = TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

            // OpInputSpk should push input's SPK onto stack, making it non-empty
            assert_eq!(vm.execute(), Ok(()));
        }

        #[test]
        fn test_input_spk_different() {
            let sig_cache = Cache::new(10_000);
            let reused_values = SigHashReusedValuesUnsync::new();
            let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);

            // Create script: 0 OP_INPUTSPK 1 OP_INPUTSPK OP_EQUAL OP_NOT
            // Verifies that two different inputs have different SPKs
            let redeem_script = ScriptBuilder::new().add_ops(&[Op0, OpTxInputSpk, Op1, OpTxInputSpk, OpEqual, OpNot]).unwrap().drain();
            let spk = pay_to_script_hash_script(&redeem_script);
            let input_mock1 = Kip10Mock { spk, amount: 100 };
            let input_mock2 = Kip10Mock { spk: create_mock_spk(2), amount: 100 }; // Different SPK

            let (tx, utxo_entries) = kip_10_tx_mock(vec![input_mock1, input_mock2], vec![]);
            let mut tx = MutableTransaction::with_entries(tx, utxo_entries);
            tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

            let tx = tx.as_verifiable();
            let mut vm = TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

            // Should succeed because the SPKs are different
            assert_eq!(vm.execute(), Ok(()));
        }

        #[test]
        fn test_input_spk_same() {
            let sig_cache = Cache::new(10_000);
            let reused_values = SigHashReusedValuesUnsync::new();
            let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);

            // Create script: 0 OP_INPUTSPK 1 OP_INPUTSPK OP_EQUAL
            // Verifies that two inputs with same SPK are equal
            let redeem_script = ScriptBuilder::new().add_ops(&[Op0, OpTxInputSpk, Op1, OpTxInputSpk, OpEqual]).unwrap().drain();

            let spk = pay_to_script_hash_script(&redeem_script);
            let input_mock1 = Kip10Mock { spk: spk.clone(), amount: 100 };
            let input_mock2 = Kip10Mock { spk, amount: 100 };

            let (tx, utxo_entries) = kip_10_tx_mock(vec![input_mock1, input_mock2], vec![]);
            let mut tx = MutableTransaction::with_entries(tx, utxo_entries);
            tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

            let tx = tx.as_verifiable();
            let mut vm = TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

            // Should succeed because both SPKs are identical
            assert_eq!(vm.execute(), Ok(()));
        }

        #[test]
        fn test_output_spk() {
            // Create unique SPK to check
            let expected_spk = create_mock_spk(42);
            let expected_spk_bytes = expected_spk.to_bytes();
            let sig_cache = Cache::new(10_000);
            let reused_values = SigHashReusedValuesUnsync::new();
            let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);
            // Create script: 0 OP_OUTPUTSPK <expected_spk_bytes> EQUAL
            let redeem_script = ScriptBuilder::new()
                .add_op(Op0)
                .unwrap()
                .add_op(OpTxOutputSpk)
                .unwrap()
                .add_data(&expected_spk_bytes)
                .unwrap()
                .add_op(OpEqual)
                .unwrap()
                .drain();

            let spk = pay_to_script_hash_script(&redeem_script);

            // Test success case
            {
                let input_mock = Kip10Mock { spk: spk.clone(), amount: 200 };
                let output_mock = Kip10Mock { spk: expected_spk.clone(), amount: 100 };

                let (tx, utxo_entries) = kip_10_tx_mock(vec![input_mock], vec![output_mock]);
                let mut tx = MutableTransaction::with_entries(tx, utxo_entries);
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

                assert_eq!(vm.execute(), Ok(()));
            }

            // Test failure case
            {
                let input_mock = Kip10Mock { spk: spk.clone(), amount: 200 };
                let output_mock = Kip10Mock {
                    spk: create_mock_spk(43), // Different SPK
                    amount: 100,
                };

                let (tx, utxo_entries) = kip_10_tx_mock(vec![input_mock], vec![output_mock]);
                let mut tx = MutableTransaction::with_entries(tx, utxo_entries);
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

                assert_eq!(vm.execute(), Err(TxScriptError::EvalFalse));
            }
        }

        #[test]
        fn test_input_index() {
            // Create script: OP_INPUTINDEX 0 EQUAL
            let redeem_script =
                ScriptBuilder::new().add_op(OpTxInputIndex).unwrap().add_i64(0).unwrap().add_op(OpEqual).unwrap().drain();

            let spk = pay_to_script_hash_script(&redeem_script);
            let sig_cache = Cache::new(10_000);
            let reused_values = SigHashReusedValuesUnsync::new();
            let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);
            // Test first input (success case)
            {
                let input_mock = Kip10Mock { spk: spk.clone(), amount: 200 };
                let output_mock = Kip10Mock { spk: create_mock_spk(1), amount: 100 };

                let (tx, utxo_entries) = kip_10_tx_mock(vec![input_mock], vec![output_mock]);
                let mut tx = MutableTransaction::with_entries(tx, utxo_entries);
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

                assert_eq!(vm.execute(), Ok(()));
            }

            // Test second input (failure case)
            {
                let input_mock1 = Kip10Mock { spk: create_mock_spk(1), amount: 100 };
                let input_mock2 = Kip10Mock { spk: spk.clone(), amount: 200 };
                let output_mock = Kip10Mock { spk: create_mock_spk(2), amount: 100 };

                let (tx, utxo_entries) = kip_10_tx_mock(vec![input_mock1, input_mock2], vec![output_mock]);
                let mut tx = MutableTransaction::with_entries(tx, utxo_entries);
                tx.tx.inputs[1].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[1], 1, tx.utxo(1).unwrap(), ctx, Default::default());

                // Should fail because script expects index 0 but we're at index 1
                assert_eq!(vm.execute(), Err(TxScriptError::EvalFalse));
            }
        }

        #[test]
        fn test_counts() {
            let sig_cache = Cache::new(10_000);
            let reused_values = SigHashReusedValuesUnsync::new();
            let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);
            // Test OpInputCount: "OP_INPUTCOUNT 2 EQUAL"
            let input_count_script =
                ScriptBuilder::new().add_op(OpTxInputCount).unwrap().add_i64(2).unwrap().add_op(OpEqual).unwrap().drain();

            // Test OpOutputCount: "OP_OUTPUTCOUNT 3 EQUAL"
            let output_count_script =
                ScriptBuilder::new().add_op(OpTxOutputCount).unwrap().add_i64(3).unwrap().add_op(OpEqual).unwrap().drain();

            let input_spk = pay_to_script_hash_script(&input_count_script);
            let output_spk = pay_to_script_hash_script(&output_count_script);

            // Create transaction with 2 inputs and 3 outputs
            let input_mock1 = Kip10Mock { spk: input_spk.clone(), amount: 100 };
            let input_mock2 = Kip10Mock { spk: output_spk.clone(), amount: 200 };
            let output_mock1 = Kip10Mock { spk: create_mock_spk(1), amount: 50 };
            let output_mock2 = Kip10Mock { spk: create_mock_spk(2), amount: 100 };
            let output_mock3 = Kip10Mock { spk: create_mock_spk(3), amount: 150 };

            let (tx, utxo_entries) =
                kip_10_tx_mock(vec![input_mock1.clone(), input_mock2.clone()], vec![output_mock1, output_mock2, output_mock3]);

            // Test InputCount
            {
                let mut tx = MutableTransaction::with_entries(tx.clone(), utxo_entries.clone());
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&input_count_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

                assert_eq!(vm.execute(), Ok(()));
            }

            // Test OutputCount
            {
                let mut tx = MutableTransaction::with_entries(tx.clone(), utxo_entries.clone());
                tx.tx.inputs[1].signature_script = ScriptBuilder::new().add_data(&output_count_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[1], 1, tx.utxo(1).unwrap(), ctx, Default::default());

                assert_eq!(vm.execute(), Ok(()));
            }

            // Test failure cases with wrong counts
            {
                // Wrong input count script: "OP_INPUTCOUNT 3 EQUAL"
                let wrong_input_count_script =
                    ScriptBuilder::new().add_op(OpTxInputCount).unwrap().add_i64(3).unwrap().add_op(OpEqual).unwrap().drain();

                let mut tx = MutableTransaction::with_entries(tx.clone(), utxo_entries.clone());
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&wrong_input_count_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());

                assert_eq!(vm.execute(), Err(TxScriptError::EvalFalse));
            }

            {
                // Wrong output count script: "OP_OUTPUTCOUNT 2 EQUAL"
                let wrong_output_count_script =
                    ScriptBuilder::new().add_op(OpTxOutputCount).unwrap().add_i64(2).unwrap().add_op(OpEqual).unwrap().drain();

                let mut tx = MutableTransaction::with_entries(tx.clone(), utxo_entries.clone());
                tx.tx.inputs[1].signature_script = ScriptBuilder::new().add_data(&wrong_output_count_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[1], 1, tx.utxo(1).unwrap(), ctx, Default::default());

                assert_eq!(vm.execute(), Err(TxScriptError::EvalFalse));
            }
        }
    }

    #[cfg(test)]
    mod introspection {
        use super::*;
        use crate::covenants::CovenantsContext;
        use crate::script_builder::{ScriptBuilder, ScriptBuilderResult};
        use crate::{EngineCtx, MAX_SCRIPT_ELEMENT_SIZE, pay_to_script_hash_script};
        use crate::{SpkEncoding, opcodes::codes};
        use kaspa_consensus_core::hashing::sighash::SigHashReusedValuesUnsync;
        use kaspa_consensus_core::subnets::SubnetworkId;
        use kaspa_consensus_core::tx::{
            CovenantBinding, MutableTransaction, PopulatedTransaction, ScriptPublicKey, Transaction, TransactionInput,
            TransactionOutpoint, TransactionOutput, UtxoEntry,
        };
        use kaspa_hashes::{Hash, ZERO_HASH};
        use kaspa_txscript_errors::CovenantsError;

        fn payload_bytes(len: usize) -> Vec<u8> {
            (0..len).map(|i| (i % 256) as u8).collect()
        }

        fn base_transaction(payload_len: usize) -> (Transaction, Vec<UtxoEntry>) {
            let version: u16 = 5;
            let lock_time: u64 = 123;
            let subnetwork_id = SubnetworkId::from_bytes([9u8; 20]);
            let gas: u64 = 777;
            let payload = payload_bytes(payload_len);

            let sig_script_0 = ScriptBuilder::new().add_data(&[0xaa, 0xbb, 0xcc]).expect("sig script build").drain();
            let sig_script_1 = ScriptBuilder::new().add_data(&[0x11]).expect("sig script build").drain();

            let inputs = vec![
                TransactionInput::new(TransactionOutpoint::new(Hash::default(), 0), sig_script_0, 0x1122334455667788, 0),
                TransactionInput::new(TransactionOutpoint::new(Hash::default(), 1), sig_script_1, 0x0fedcba987654321, 0),
            ];

            let output_spk_0 = ScriptBuilder::new().add_ops(&[codes::OpTrue, codes::Op2, codes::Op3]).expect("spk build").drain();
            let output_spk_1 = ScriptBuilder::new().add_ops(&[codes::Op4, codes::Op5]).expect("spk build").drain();

            let outputs = vec![
                TransactionOutput::new(11, ScriptPublicKey::new(0, output_spk_0.into())),
                TransactionOutput::new(22, ScriptPublicKey::new(0, output_spk_1.into())),
            ];

            let mut tx = Transaction::new(version, inputs, outputs, lock_time, subnetwork_id, gas, payload);
            tx.finalize();

            let utxo_spk_0 = ScriptBuilder::new().add_ops(&[codes::OpTrue, codes::Op1]).expect("spk build").drain();
            let utxo_spk_1 = ScriptBuilder::new().add_ops(&[codes::Op2, codes::Op3]).expect("spk build").drain();

            let entries = vec![
                UtxoEntry::new(1000, ScriptPublicKey::new(0, utxo_spk_0.into()), 0, true, None),
                UtxoEntry::new(2000, ScriptPublicKey::new(0, utxo_spk_1.into()), 0, false, None),
            ];

            (tx, entries)
        }

        fn create_transaction_with_covenant() -> (Transaction, Vec<UtxoEntry>) {
            let version: u16 = 5;
            let lock_time: u64 = 0;
            let subnetwork_id = SubnetworkId::from_bytes([9u8; 20]);
            let gas: u64 = 0;
            let payload = payload_bytes(0);

            let sig_script = ScriptBuilder::new().add_op(codes::OpTrue).expect("sig script build").drain();
            let inputs = vec![
                TransactionInput::new(TransactionOutpoint::new(Hash::default(), 0), sig_script.clone(), 0, 0),
                TransactionInput::new(TransactionOutpoint::new(Hash::default(), 1), sig_script.clone(), 0, 0),
                TransactionInput::new(TransactionOutpoint::new(Hash::default(), 2), sig_script.clone(), 0, 0),
                TransactionInput::new(TransactionOutpoint::new(Hash::default(), 3), sig_script.clone(), 0, 0),
                TransactionInput::new(TransactionOutpoint::new(Hash::default(), 4), sig_script, 0, 0),
            ];

            let spk = ScriptBuilder::new().add_op(codes::OpTrue).expect("spk build").drain();
            let outputs = vec![
                TransactionOutput {
                    value: 11,
                    script_public_key: ScriptPublicKey::new(0, spk.clone().into()),
                    covenant: Some(CovenantBinding { authorizing_input: 0, covenant_id: Hash::from_u64_word(1) }),
                },
                TransactionOutput {
                    value: 22,
                    script_public_key: ScriptPublicKey::new(0, spk.clone().into()),
                    covenant: Some(CovenantBinding { authorizing_input: 3, covenant_id: Hash::from_u64_word(1) }),
                },
                TransactionOutput {
                    value: 33,
                    script_public_key: ScriptPublicKey::new(0, spk.clone().into()),
                    covenant: Some(CovenantBinding { authorizing_input: 1, covenant_id: Hash::from_u64_word(2) }),
                },
                TransactionOutput::new(44, ScriptPublicKey::new(0, spk.clone().into())),
                TransactionOutput {
                    value: 55,
                    script_public_key: ScriptPublicKey::new(0, spk.clone().into()),
                    covenant: Some(CovenantBinding { authorizing_input: 3, covenant_id: Hash::from_u64_word(1) }),
                },
                TransactionOutput {
                    value: 66,
                    script_public_key: ScriptPublicKey::new(0, spk.into()),
                    covenant: Some(CovenantBinding { authorizing_input: 4, covenant_id: Hash::from_u64_word(2) }),
                },
            ];

            let mut tx = Transaction::new(version, inputs, outputs, lock_time, subnetwork_id, gas, payload);
            tx.finalize();

            let utxo_spk = ScriptBuilder::new().add_op(codes::OpTrue).expect("spk build").drain();
            let entries = vec![
                UtxoEntry::new(1000, ScriptPublicKey::new(0, utxo_spk.clone().into()), 0, false, Some(Hash::from_u64_word(1))),
                UtxoEntry::new(1000, ScriptPublicKey::new(0, utxo_spk.clone().into()), 0, false, Some(Hash::from_u64_word(2))),
                UtxoEntry::new(1000, ScriptPublicKey::new(0, utxo_spk.clone().into()), 0, false, Some(Hash::from_u64_word(1))),
                UtxoEntry::new(1000, ScriptPublicKey::new(0, utxo_spk.clone().into()), 0, false, Some(Hash::from_u64_word(1))),
                UtxoEntry::new(1000, ScriptPublicKey::new(0, utxo_spk.into()), 0, false, Some(Hash::from_u64_word(2))),
            ];

            (tx, entries)
        }

        fn script<F>(build: F) -> Vec<u8>
        where
            F: FnOnce(&mut ScriptBuilder) -> ScriptBuilderResult<&mut ScriptBuilder>,
        {
            let mut sb = ScriptBuilder::new();
            // Add a drop at the start to remove the initial sigscript data
            sb.add_op(codes::OpDrop).expect("builder failure");
            build(&mut sb).expect("builder failure");
            sb.drain()
        }

        fn run_script(tx: &Transaction, mut entries: Vec<UtxoEntry>, idx: usize, script: Vec<u8>) -> Result<(), TxScriptError> {
            entries[idx].script_public_key = ScriptPublicKey::new(0, script.into());
            let populated_tx = PopulatedTransaction::new(tx, entries);
            let sig_cache = Cache::new(10_000);
            let reused_values = SigHashReusedValuesUnsync::new();
            let covenants_ctx = CovenantsContext::from_tx(&populated_tx)?;
            let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values).with_covenants_ctx(&covenants_ctx);
            let mut vm = TxScriptEngine::from_transaction_input(
                &populated_tx,
                &populated_tx.tx.inputs[idx],
                idx,
                &populated_tx.entries[idx],
                ctx,
                Default::default(),
            );
            vm.execute()
        }

        #[test]
        fn tx_level_introspection() {
            let (tx, entries) = base_transaction(100);
            let (tx_large, entries_large) = base_transaction(600);
            let expected_subnet: Vec<u8> = tx.subnetwork_id.into();

            let spk_version = script(|sb| sb.add_op(codes::OpTxVersion)?.add_i64(tx.version as i64)?.add_op(codes::OpEqual));
            run_script(&tx, entries.clone(), 0, spk_version).expect("tx version");

            let spk_lock_time = script(|sb| sb.add_op(codes::OpTxLockTime)?.add_i64(tx.lock_time as i64)?.add_op(codes::OpEqual));
            run_script(&tx, entries.clone(), 0, spk_lock_time).expect("tx locktime");

            let spk_subnet = script(|sb| sb.add_op(codes::OpTxSubnetId)?.add_data(&expected_subnet)?.add_op(codes::OpEqual));
            run_script(&tx, entries.clone(), 0, spk_subnet).expect("tx subnet id");

            let spk_gas = script(|sb| sb.add_op(codes::OpTxGas)?.add_i64(tx.gas as i64)?.add_op(codes::OpEqual));
            run_script(&tx, entries.clone(), 0, spk_gas).expect("tx gas");

            let spk_payload_len =
                script(|sb| sb.add_op(codes::OpTxPayloadLen)?.add_i64(tx.payload.len() as i64)?.add_op(codes::OpEqual));
            run_script(&tx, entries.clone(), 0, spk_payload_len).expect("tx payload len");

            let expected_payload_full = tx.payload.clone();
            let spk_payload_substr_full = script(|sb| {
                sb.add_i64(0)?
                    .add_op(codes::OpTxPayloadLen)?
                    .add_op(codes::OpTxPayloadSubstr)?
                    .add_data(&expected_payload_full)?
                    .add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_payload_substr_full).expect("payload substr full");

            let expected_substr = tx.payload[1..4].to_vec();
            let spk_payload_substr = script(|sb| {
                sb.add_i64(1)?.add_i64(4)?.add_op(codes::OpTxPayloadSubstr)?.add_data(&expected_substr)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_payload_substr).expect("payload substr ok");

            let spk_payload_substr_oob = script(|sb| sb.add_i64(1000)?.add_i64(1002)?.add_op(codes::OpTxPayloadSubstr));
            let err =
                run_script(&tx_large, entries_large.clone(), 0, spk_payload_substr_oob).expect_err("payload substr out of bounds");
            assert!(matches!(err, TxScriptError::OutOfBoundsSubstring(_, _, _)));

            let spk_payload_substr_too_long =
                script(|sb| sb.add_i64(0)?.add_i64(MAX_SCRIPT_ELEMENT_SIZE as i64 + 1)?.add_op(codes::OpTxPayloadSubstr));
            let err = run_script(&tx_large, entries_large.clone(), 0, spk_payload_substr_too_long).expect_err("payload substr >520");
            assert!(matches!(err, TxScriptError::ElementTooBig(_, _)));
        }

        #[test]
        fn input_input_output_introspection() {
            let (tx, entries) = base_transaction(40);
            let input_spk_bytes_1 = entries[1].script_public_key.to_bytes();
            let out_spk_bytes_0 = tx.outputs[0].script_public_key.to_bytes();
            let sig_script_0 = tx.inputs[0].signature_script.clone();

            let spk_input_spk_len = script(|sb| {
                sb.add_i64(1)?.add_op(codes::OpTxInputSpkLen)?.add_i64(input_spk_bytes_1.len() as i64)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_input_spk_len).expect("input spk len");

            let expected_spk_full = input_spk_bytes_1.clone();
            let spk_input_spk_substr_full = script(|sb| {
                sb.add_i64(1)?
                    .add_i64(0)?
                    .add_i64(1)?
                    .add_op(codes::OpTxInputSpkLen)?
                    .add_op(codes::OpTxInputSpkSubstr)?
                    .add_data(&expected_spk_full)?
                    .add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_input_spk_substr_full).expect("input spk substr full");

            let expected_spk_suffix = input_spk_bytes_1[1..].to_vec();
            let spk_input_spk_substr_suffix = script(|sb| {
                sb.add_i64(1)?
                    .add_i64(1)?
                    .add_i64(1)?
                    .add_op(codes::OpTxInputSpkLen)?
                    .add_op(codes::OpTxInputSpkSubstr)?
                    .add_data(&expected_spk_suffix)?
                    .add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_input_spk_substr_suffix).expect("input spk substr suffix");

            let spk_input_spk_substr_oob = script(|sb| sb.add_i64(1)?.add_i64(100)?.add_i64(101)?.add_op(codes::OpTxInputSpkSubstr));
            let err = run_script(&tx, entries.clone(), 0, spk_input_spk_substr_oob).expect_err("input spk substr oob");
            assert!(matches!(err, TxScriptError::OutOfBoundsSubstring(_, _, _)));

            let spk_output_spk_len = script(|sb| {
                sb.add_i64(0)?.add_op(codes::OpTxOutputSpkLen)?.add_i64(out_spk_bytes_0.len() as i64)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_output_spk_len).expect("output spk len");

            let expected_out_spk_full = out_spk_bytes_0.clone();
            let spk_output_spk_substr_full = script(|sb| {
                sb.add_i64(0)?
                    .add_i64(0)?
                    .add_i64(0)?
                    .add_op(codes::OpTxOutputSpkLen)?
                    .add_op(codes::OpTxOutputSpkSubstr)?
                    .add_data(&expected_out_spk_full)?
                    .add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_output_spk_substr_full).expect("output spk substr full");

            let expected_out_spk_tail = out_spk_bytes_0[1..3].to_vec();
            let spk_output_spk_substr_tail = script(|sb| {
                sb.add_i64(0)?
                    .add_i64(1)?
                    .add_i64(3)?
                    .add_op(codes::OpTxOutputSpkSubstr)?
                    .add_data(&expected_out_spk_tail)?
                    .add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_output_spk_substr_tail).expect("output spk substr tail");

            let spk_input_sig_len = script(|sb| {
                sb.add_i64(0)?.add_op(codes::OpTxInputScriptSigLen)?.add_i64(sig_script_0.len() as i64)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_input_sig_len).expect("input sig len");

            let expected_sig_full = sig_script_0.clone();
            let spk_input_sig_substr_full = script(|sb| {
                sb.add_i64(0)?
                    .add_i64(0)?
                    .add_i64(0)?
                    .add_op(codes::OpTxInputScriptSigLen)?
                    .add_op(codes::OpTxInputScriptSigSubstr)?
                    .add_data(&expected_sig_full)?
                    .add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_input_sig_substr_full).expect("input sig substr full");

            let expected_sig_substr = sig_script_0[1..3].to_vec();
            let spk_input_sig_substr = script(|sb| {
                sb.add_i64(0)?
                    .add_i64(1)?
                    .add_i64(3)?
                    .add_op(codes::OpTxInputScriptSigSubstr)?
                    .add_data(&expected_sig_substr)?
                    .add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_input_sig_substr).expect("input sig substr");

            let spk_outpoint_txid = script(|sb| {
                sb.add_i64(1)?
                    .add_op(codes::OpOutpointTxId)?
                    .add_data(&tx.inputs[1].previous_outpoint.transaction_id.as_bytes())?
                    .add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_outpoint_txid).expect("outpoint txid");

            let spk_outpoint_index = script(|sb| sb.add_i64(1)?.add_op(codes::OpOutpointIndex)?.add_i64(1)?.add_op(codes::OpEqual));
            run_script(&tx, entries.clone(), 0, spk_outpoint_index).expect("outpoint index");

            let seq_bytes = tx.inputs[0].sequence.to_le_bytes();
            let spk_seq = script(|sb| sb.add_i64(0)?.add_op(codes::OpTxInputSeq)?.add_data(&seq_bytes)?.add_op(codes::OpEqual));
            run_script(&tx, entries.clone(), 0, spk_seq).expect("input seq");

            let spk_is_coinbase_true =
                script(|sb| sb.add_i64(0)?.add_op(codes::OpTxInputIsCoinbase)?.add_i64(1)?.add_op(codes::OpEqual));
            run_script(&tx, entries.clone(), 0, spk_is_coinbase_true).expect("is coinbase true");

            let spk_is_coinbase_false =
                script(|sb| sb.add_i64(1)?.add_op(codes::OpTxInputIsCoinbase)?.add_i64(0)?.add_op(codes::OpEqual));
            run_script(&tx, entries, 0, spk_is_coinbase_false).expect("is coinbase false");
        }

        #[test]
        fn cov_output_count() {
            let (tx, entries) = create_transaction_with_covenant();

            for (input_idx, expected_count) in [(0, 1), (1, 1), (2, 0), (3, 2), (4, 1)] {
                let spk = script(|sb| {
                    sb.add_i64(input_idx)?.add_op(codes::OpAuthOutputCount)?.add_i64(expected_count)?.add_op(codes::OpEqual)
                });
                run_script(&tx, entries.clone(), 0, spk).expect("cov output count");
            }

            let spk_invalid = script(|sb| sb.add_i64(7)?.add_op(codes::OpAuthOutputCount));
            let err = run_script(&tx, entries, 0, spk_invalid).expect_err("cov output count invalid input");
            assert!(matches!(err, TxScriptError::InvalidInputIndex(7, 5)));
        }

        #[test]
        fn auth_output_idx() {
            let (tx, entries) = create_transaction_with_covenant();

            for (input_idx, authorized_idx, expected_output_idx) in [(0, 0, 0), (1, 0, 2), (3, 0, 1), (3, 1, 4), (4, 0, 5)] {
                let spk = script(|sb| {
                    sb.add_i64(input_idx)?
                        .add_i64(authorized_idx)?
                        .add_op(codes::OpAuthOutputIdx)?
                        .add_i64(expected_output_idx)?
                        .add_op(codes::OpEqual)
                });
                run_script(&tx, entries.clone(), 0, spk).unwrap();
            }

            let spk_missing = script(|sb| sb.add_i64(0)?.add_i64(2)?.add_op(codes::OpAuthOutputIdx));
            let err = run_script(&tx, entries, 0, spk_missing).expect_err("cov output idx missing");
            assert!(matches!(err, TxScriptError::CovenantsError(CovenantsError::InvalidAuthCovOutIndex(2, 0, 1))));
        }

        #[test]
        fn covenant_id_opcodes() {
            let (tx, entries) = create_transaction_with_covenant();
            let covenant_id_1 = Hash::from_u64_word(1);
            let covenant_id_2 = Hash::from_u64_word(2);
            let covenant_id_3 = Hash::from_u64_word(3);

            // OpInputCovenantId for inputs with covenant ids
            let spk_input_cov_id_0 = script(|sb| {
                sb.add_i64(0)?.add_op(codes::OpInputCovenantId)?.add_data(&covenant_id_1.as_bytes())?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_input_cov_id_0).unwrap();

            let spk_input_cov_id_1 = script(|sb| {
                sb.add_i64(1)?.add_op(codes::OpInputCovenantId)?.add_data(&covenant_id_2.as_bytes())?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_input_cov_id_1).unwrap();

            let spk_input_cov_id_3 = script(|sb| {
                sb.add_i64(3)?.add_op(codes::OpInputCovenantId)?.add_data(&covenant_id_1.as_bytes())?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_input_cov_id_3).unwrap();

            // OpOutputCovenantId for outputs with covenant ids
            let spk_output_cov_id_0 = script(|sb| {
                sb.add_i64(0)?.add_op(codes::OpOutputCovenantId)?.add_data(&covenant_id_1.as_bytes())?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_output_cov_id_0).unwrap();

            let spk_output_cov_id_2 = script(|sb| {
                sb.add_i64(2)?.add_op(codes::OpOutputCovenantId)?.add_data(&covenant_id_2.as_bytes())?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_output_cov_id_2).unwrap();

            // OpOutputAuthorizingInput for outputs with covenant bindings
            let spk_output_auth_input_0 =
                script(|sb| sb.add_i64(0)?.add_op(codes::OpOutputAuthorizingInput)?.add_i64(0)?.add_op(codes::OpEqual));
            run_script(&tx, entries.clone(), 0, spk_output_auth_input_0).unwrap();

            let spk_output_auth_input_1 =
                script(|sb| sb.add_i64(1)?.add_op(codes::OpOutputAuthorizingInput)?.add_i64(3)?.add_op(codes::OpEqual));
            run_script(&tx, entries.clone(), 0, spk_output_auth_input_1).unwrap();

            // OpCovInputCount
            let spk_cov_in_count_1 = script(|sb| {
                sb.add_data(&covenant_id_1.as_bytes())?.add_op(codes::OpCovInputCount)?.add_i64(3)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_cov_in_count_1).unwrap();

            let spk_cov_in_count_2 = script(|sb| {
                sb.add_data(&covenant_id_2.as_bytes())?.add_op(codes::OpCovInputCount)?.add_i64(2)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_cov_in_count_2).unwrap();

            let spk_cov_in_count_0 = script(|sb| {
                sb.add_data(&covenant_id_3.as_bytes())?.add_op(codes::OpCovInputCount)?.add_i64(0)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_cov_in_count_0).unwrap();

            // OpCovInputIdx
            let spk_cov_in_idx_0 = script(|sb| {
                sb.add_data(&covenant_id_1.as_bytes())?.add_i64(0)?.add_op(codes::OpCovInputIdx)?.add_i64(0)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_cov_in_idx_0).unwrap();

            let spk_cov_in_idx_3 = script(|sb| {
                sb.add_data(&covenant_id_1.as_bytes())?.add_i64(2)?.add_op(codes::OpCovInputIdx)?.add_i64(3)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_cov_in_idx_3).unwrap();

            let spk_cov_in_idx_oob = script(|sb| sb.add_data(&covenant_id_1.as_bytes())?.add_i64(3)?.add_op(codes::OpCovInputIdx));
            let err = run_script(&tx, entries.clone(), 0, spk_cov_in_idx_oob).expect_err("cov input idx oob");
            assert!(matches!(err, TxScriptError::CovenantsError(CovenantsError::InvalidCovInIndex(_, _))));

            // OpCovOutputCount
            let spk_cov_out_count_1 = script(|sb| {
                sb.add_data(&covenant_id_1.as_bytes())?.add_op(codes::OpCovOutputCount)?.add_i64(3)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_cov_out_count_1).unwrap();

            let spk_cov_out_count_2 = script(|sb| {
                sb.add_data(&covenant_id_2.as_bytes())?.add_op(codes::OpCovOutputCount)?.add_i64(2)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_cov_out_count_2).unwrap();
            let spk_cov_out_count_0 = script(|sb| {
                sb.add_data(&covenant_id_3.as_bytes())?.add_op(codes::OpCovOutputCount)?.add_i64(0)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_cov_out_count_0).unwrap();

            // OpCovOutputIdx
            let spk_cov_out_idx_0 = script(|sb| {
                sb.add_data(&covenant_id_1.as_bytes())?.add_i64(0)?.add_op(codes::OpCovOutputIdx)?.add_i64(0)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_cov_out_idx_0).unwrap();

            let spk_cov_out_idx_4 = script(|sb| {
                sb.add_data(&covenant_id_1.as_bytes())?.add_i64(2)?.add_op(codes::OpCovOutputIdx)?.add_i64(4)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_cov_out_idx_4).unwrap();

            let spk_cov_out_idx_5 = script(|sb| {
                sb.add_data(&covenant_id_2.as_bytes())?.add_i64(1)?.add_op(codes::OpCovOutputIdx)?.add_i64(5)?.add_op(codes::OpEqual)
            });
            run_script(&tx, entries.clone(), 0, spk_cov_out_idx_5).unwrap();

            let spk_cov_out_idx_oob = script(|sb| sb.add_data(&covenant_id_1.as_bytes())?.add_i64(3)?.add_op(codes::OpCovOutputIdx));
            let err = run_script(&tx, entries.clone(), 0, spk_cov_out_idx_oob).expect_err("cov out idx oob");
            assert!(matches!(err, TxScriptError::CovenantsError(CovenantsError::InvalidCovOutIndex(_, _))));

            let spk_output_cov_id_oob = script(|sb| sb.add_i64(6)?.add_op(codes::OpOutputCovenantId));
            let err = run_script(&tx, entries.clone(), 0, spk_output_cov_id_oob).expect_err("output covenant id oob");
            assert_eq!(err, TxScriptError::InvalidOutputIndex(6, 6));

            let spk_output_auth_input_oob = script(|sb| sb.add_i64(6)?.add_op(codes::OpOutputAuthorizingInput));
            let err = run_script(&tx, entries, 0, spk_output_auth_input_oob).expect_err("output authorizing input oob");
            assert_eq!(err, TxScriptError::InvalidOutputIndex(6, 6));

            // OpInputCovenantId when covenant id is None (returns zero hash)
            let (tx_no_cov, entries_no_cov) = base_transaction(0);
            let spk_input_cov_none =
                script(|sb| sb.add_i64(0)?.add_op(codes::OpInputCovenantId)?.add_data(&ZERO_HASH.as_bytes())?.add_op(codes::OpEqual));
            run_script(&tx_no_cov, entries_no_cov.clone(), 0, spk_input_cov_none).unwrap();

            // OpOutputCovenantId when covenant id is None (returns zero hash)
            let spk_output_cov_none =
                script(|sb| sb.add_i64(0)?.add_op(codes::OpOutputCovenantId)?.add_data(&ZERO_HASH.as_bytes())?.add_op(codes::OpEqual));
            run_script(&tx_no_cov, entries_no_cov.clone(), 0, spk_output_cov_none).unwrap();

            // OpOutputAuthorizingInput when covenant is None (returns -1)
            let spk_output_auth_none =
                script(|sb| sb.add_i64(0)?.add_op(codes::OpOutputAuthorizingInput)?.add_i64(-1)?.add_op(codes::OpEqual));
            run_script(&tx_no_cov, entries_no_cov.clone(), 0, spk_output_auth_none).unwrap();

            // OpInputCovenantId out-of-bounds
            let spk_input_cov_oob = script(|sb| sb.add_i64(5)?.add_op(codes::OpInputCovenantId));
            let err = run_script(&tx_no_cov, entries_no_cov, 0, spk_input_cov_oob).expect_err("input covenant id oob");
            assert!(matches!(err, TxScriptError::InvalidInputIndex(5, 2)));
        }

        #[test]
        fn error_paths_for_indices_and_sizes() {
            let (tx, entries) = base_transaction(600);

            let spk_bad_input_index = script(|sb| sb.add_i64(5)?.add_op(codes::OpTxInputSpkLen));
            let err = run_script(&tx, entries.clone(), 0, spk_bad_input_index).expect_err("invalid input index");
            assert!(matches!(err, TxScriptError::InvalidInputIndex(_, _)));

            let spk_bad_output_index = script(|sb| sb.add_i64(9)?.add_op(codes::OpTxOutputSpkLen));
            let err = run_script(&tx, entries.clone(), 0, spk_bad_output_index).expect_err("invalid output index");
            assert!(matches!(err, TxScriptError::InvalidOutputIndex(_, _)));

            // Large input SPK to trigger ElementTooBig via substring length
            let mut large_entries = entries.clone();
            large_entries[1].script_public_key = ScriptPublicKey::new(0, vec![0u8; MAX_SCRIPT_ELEMENT_SIZE + 1].into());
            let spk_large_spk_substr =
                script(|sb| sb.add_i64(1)?.add_i64(0)?.add_i64(MAX_SCRIPT_ELEMENT_SIZE as i64 + 1)?.add_op(codes::OpTxInputSpkSubstr));
            let err = run_script(&tx, large_entries.clone(), 0, spk_large_spk_substr).expect_err("input spk substr too long");
            assert!(matches!(err, TxScriptError::ElementTooBig(_, _)));
        }

        #[test]
        fn test_op_tx_input_daa_score() {
            // Test: Get DAA score for each input
            for (input_idx, expected_daa_score) in [(0, 12345), (1, 67890), (2, 99999)] {
                let mut redeem_script = ScriptBuilder::new();
                redeem_script
                    .add_i64(input_idx)
                    .unwrap()
                    .add_op(codes::OpTxInputDaaScore)
                    .unwrap()
                    .add_i64(expected_daa_score)
                    .unwrap()
                    .add_op(codes::OpEqual)
                    .unwrap();
                let redeem_script = redeem_script.drain();

                let spk = pay_to_script_hash_script(&redeem_script);

                let inputs = vec![
                    TransactionInput::new(TransactionOutpoint::new(Hash::default(), 0), vec![0xaa], 0, 0),
                    TransactionInput::new(TransactionOutpoint::new(Hash::default(), 1), vec![0xbb], 0, 0),
                    TransactionInput::new(TransactionOutpoint::new(Hash::default(), 2), vec![0xcc], 0, 0),
                ];

                let output_spk = ScriptBuilder::new().add_op(codes::OpTrue).expect("spk build").drain();
                let outputs = vec![TransactionOutput::new(100, ScriptPublicKey::new(0, output_spk.into()))];

                let mut tx = Transaction::new(1, inputs, outputs, 0, Default::default(), 0, vec![]);
                tx.finalize();

                let input_spk = ScriptBuilder::new().add_op(codes::OpTrue).expect("spk build").drain();
                let entries = vec![
                    UtxoEntry::new(1000, ScriptPublicKey::new(0, input_spk.clone().into()), 12345, false, None),
                    UtxoEntry::new(2000, ScriptPublicKey::new(0, input_spk.clone().into()), 67890, false, None),
                    UtxoEntry::new(3000, ScriptPublicKey::new(0, input_spk.into()), 99999, false, None),
                ];

                let mut tx = MutableTransaction::with_entries(tx, entries.clone());
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                // Update the SPK of input 0 to be P2SH
                tx.entries[0].as_mut().unwrap().script_public_key = spk;

                let tx = tx.as_verifiable();
                let sig_cache = Cache::new(10_000);
                let reused_values = SigHashReusedValuesUnsync::new();

                let mut vm = TxScriptEngine::from_transaction_input(
                    &tx,
                    &tx.inputs()[0],
                    0,
                    tx.utxo(0).unwrap(),
                    EngineCtx::new(&sig_cache).with_reused(&reused_values),
                    Default::default(),
                );

                vm.execute().unwrap_or_else(|_| panic!("input {} daa score", input_idx));
            }

            // Test: Invalid input index (negative)
            {
                let mut redeem_script = ScriptBuilder::new();
                redeem_script.add_i64(-1).unwrap().add_op(codes::OpTxInputDaaScore).unwrap();
                let redeem_script = redeem_script.drain();

                let spk = pay_to_script_hash_script(&redeem_script);

                let input = TransactionInput::new(TransactionOutpoint::new(Hash::default(), 0), vec![], 0, 0);
                let output = TransactionOutput::new(100, ScriptPublicKey::new(0, vec![codes::OpTrue].into()));
                let mut tx = Transaction::new(1, vec![input], vec![output], 0, Default::default(), 0, vec![]);
                tx.finalize();

                let utxo_entry = UtxoEntry::new(1000, spk, 12345, false, None);
                let mut tx = MutableTransaction::with_entries(tx, vec![utxo_entry]);
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let sig_cache = Cache::new(10_000);
                let reused_values = SigHashReusedValuesUnsync::new();

                let mut vm = TxScriptEngine::from_transaction_input(
                    &tx,
                    &tx.inputs()[0],
                    0,
                    tx.utxo(0).unwrap(),
                    EngineCtx::new(&sig_cache).with_reused(&reused_values),
                    Default::default(),
                );

                let err = vm.execute().expect_err("should fail with negative index");
                // Negative index fails at i32_to_usize conversion
                assert!(matches!(err, TxScriptError::InvalidIndex(-1)));
            }

            // Test: Invalid input index (out of bounds)
            {
                let mut redeem_script = ScriptBuilder::new();
                redeem_script.add_i64(3).unwrap().add_op(codes::OpTxInputDaaScore).unwrap();
                let redeem_script = redeem_script.drain();

                let spk = pay_to_script_hash_script(&redeem_script);

                let inputs = vec![
                    TransactionInput::new(TransactionOutpoint::new(Hash::default(), 0), vec![], 0, 0),
                    TransactionInput::new(TransactionOutpoint::new(Hash::default(), 1), vec![], 0, 0),
                    TransactionInput::new(TransactionOutpoint::new(Hash::default(), 2), vec![], 0, 0),
                ];
                let output = TransactionOutput::new(100, ScriptPublicKey::new(0, vec![codes::OpTrue].into()));
                let mut tx = Transaction::new(1, inputs, vec![output], 0, Default::default(), 0, vec![]);
                tx.finalize();

                let input_spk = ScriptBuilder::new().add_op(codes::OpTrue).expect("spk build").drain();
                let entries = vec![
                    UtxoEntry::new(1000, spk, 12345, false, None),
                    UtxoEntry::new(2000, ScriptPublicKey::new(0, input_spk.clone().into()), 67890, false, None),
                    UtxoEntry::new(3000, ScriptPublicKey::new(0, input_spk.into()), 99999, false, None),
                ];

                let mut tx = MutableTransaction::with_entries(tx, entries);
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let sig_cache = Cache::new(10_000);
                let reused_values = SigHashReusedValuesUnsync::new();

                let mut vm = TxScriptEngine::from_transaction_input(
                    &tx,
                    &tx.inputs()[0],
                    0,
                    tx.utxo(0).unwrap(),
                    EngineCtx::new(&sig_cache).with_reused(&reused_values),
                    Default::default(),
                );

                let err = vm.execute().expect_err("should fail with out of bounds index");
                assert!(matches!(err, TxScriptError::InvalidInputIndex(3, 3)));
            }

            // Test: Compare DAA scores between inputs
            {
                let mut redeem_script = ScriptBuilder::new();
                redeem_script
                    .add_i64(0)
                    .unwrap()
                    .add_op(codes::OpTxInputDaaScore)
                    .unwrap()
                    .add_i64(1)
                    .unwrap()
                    .add_op(codes::OpTxInputDaaScore)
                    .unwrap()
                    .add_op(codes::OpLessThan)
                    .unwrap(); // 12345 < 67890
                let redeem_script = redeem_script.drain();

                let spk = pay_to_script_hash_script(&redeem_script);

                let inputs = vec![
                    TransactionInput::new(TransactionOutpoint::new(Hash::default(), 0), vec![], 0, 0),
                    TransactionInput::new(TransactionOutpoint::new(Hash::default(), 1), vec![], 0, 0),
                ];
                let output = TransactionOutput::new(100, ScriptPublicKey::new(0, vec![codes::OpTrue].into()));
                let mut tx = Transaction::new(1, inputs, vec![output], 0, Default::default(), 0, vec![]);
                tx.finalize();

                let input_spk = ScriptBuilder::new().add_op(codes::OpTrue).expect("spk build").drain();
                let entries = vec![
                    UtxoEntry::new(1000, spk, 12345, false, None),
                    UtxoEntry::new(2000, ScriptPublicKey::new(0, input_spk.into()), 67890, false, None),
                ];

                let mut tx = MutableTransaction::with_entries(tx, entries);
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let sig_cache = Cache::new(10_000);
                let reused_values = SigHashReusedValuesUnsync::new();

                let mut vm = TxScriptEngine::from_transaction_input(
                    &tx,
                    &tx.inputs()[0],
                    0,
                    tx.utxo(0).unwrap(),
                    EngineCtx::new(&sig_cache).with_reused(&reused_values),
                    Default::default(),
                );

                vm.execute().expect("compare daa scores");
            }
        }
        #[test]
        fn test_op_tx_input_daa_score_in_script() {
            let sig_cache = Cache::new(10_000);
            let reused_values = SigHashReusedValuesUnsync::new();
            let ctx = EngineContext::new(&sig_cache).with_reused(&reused_values);

            // Script: Require that input 0 must be from block DAA score >= 50000
            let redeem_script = ScriptBuilder::new()
                .add_i64(0)
                .unwrap()
                .add_op(codes::OpTxInputDaaScore)
                .unwrap()
                .add_i64(50000)
                .unwrap()
                .add_op(codes::OpGreaterThanOrEqual)
                .unwrap()
                .drain();

            let spk = pay_to_script_hash_script(&redeem_script);

            // Test: Input with DAA score above threshold (should pass)
            {
                let input = TransactionInput::new(TransactionOutpoint::new(Hash::default(), 0), vec![], 0, 0);
                let output = TransactionOutput::new(100, ScriptPublicKey::new(0, vec![codes::OpTrue].into()));
                let mut tx = Transaction::new(1, vec![input.clone()], vec![output], 0, Default::default(), 0, vec![]);
                tx.finalize();

                let utxo_entry = UtxoEntry::new(1000, spk.clone(), 60000, false, None); // DAA score 60000
                let mut tx = MutableTransaction::with_entries(tx, vec![utxo_entry.clone()]);
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());
                assert_eq!(vm.execute(), Ok(()), "Should pass with DAA score 60000 >= 50000");
            }

            // Test: Input with DAA score below threshold (should fail)
            {
                let input = TransactionInput::new(TransactionOutpoint::new(Hash::default(), 0), vec![], 0, 0);
                let output = TransactionOutput::new(100, ScriptPublicKey::new(0, vec![codes::OpTrue].into()));
                let mut tx = Transaction::new(1, vec![input.clone()], vec![output], 0, Default::default(), 0, vec![]);
                tx.finalize();

                let utxo_entry = UtxoEntry::new(1000, spk.clone(), 40000, false, None); // DAA score 40000
                let mut tx = MutableTransaction::with_entries(tx, vec![utxo_entry.clone()]);
                tx.tx.inputs[0].signature_script = ScriptBuilder::new().add_data(&redeem_script).unwrap().drain();

                let tx = tx.as_verifiable();
                let mut vm =
                    TxScriptEngine::from_transaction_input(&tx, &tx.inputs()[0], 0, tx.utxo(0).unwrap(), ctx, Default::default());
                assert_eq!(vm.execute(), Err(TxScriptError::EvalFalse), "Should fail with DAA score 40000 < 50000");
            }
        }
    }
}