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
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
//! Pass 5: Stack Lower -- converts ANF IR to Stack IR.
//!
//! The fundamental challenge: ANF uses named temporaries but Bitcoin Script
//! operates on an anonymous stack. We maintain a "stack map" that tracks
//! which named value lives at which stack position, then emit PICK/ROLL/DUP
//! operations to shuttle values to the top when they are needed.
//!
//! This matches the TypeScript reference compiler and aligned Go compiler:
//! - Private methods are inlined at call sites rather than compiled separately
//! - Constructor is skipped
//! - @ref: aliases are handled via PICK (non-consuming copy)
//! - @this is a compile-time placeholder (push 0)
//! - super() is a no-op at stack level
use std::collections::{HashMap, HashSet};
use crate::ir::{ANFBinding, ANFMethod, ANFProgram, ANFProperty, ANFValue, ConstValue};
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const MAX_STACK_DEPTH: usize = 800;
// ---------------------------------------------------------------------------
// Stack IR types
// ---------------------------------------------------------------------------
/// A single stack-machine operation.
#[derive(Debug, Clone)]
pub enum StackOp {
Push(PushValue),
Dup,
Swap,
Roll { depth: usize },
Pick { depth: usize },
Drop,
Nip,
Over,
Rot,
Tuck,
Opcode(String),
If {
then_ops: Vec<StackOp>,
else_ops: Vec<StackOp>,
},
Placeholder {
param_index: usize,
param_name: String,
},
PushCodeSepIndex,
}
/// Typed value for push operations.
#[derive(Debug, Clone)]
pub enum PushValue {
Bool(bool),
Int(i128),
Bytes(Vec<u8>),
}
/// A stack-lowered method.
#[derive(Debug, Clone)]
pub struct StackMethod {
pub name: String,
pub ops: Vec<StackOp>,
pub max_stack_depth: usize,
/// Parallel to `ops`: optional source location for each stack operation.
/// Used for generating source maps in the emit phase.
pub source_locs: Vec<Option<crate::ir::SourceLocation>>,
}
// ---------------------------------------------------------------------------
// Builtin function -> opcode mapping
// ---------------------------------------------------------------------------
fn is_ec_builtin(name: &str) -> bool {
matches!(
name,
"ecAdd"
| "ecMul"
| "ecMulGen"
| "ecNegate"
| "ecOnCurve"
| "ecModReduce"
| "ecEncodeCompressed"
| "ecMakePoint"
| "ecPointX"
| "ecPointY"
)
}
fn builtin_opcodes(name: &str) -> Option<Vec<&'static str>> {
match name {
"sha256" => Some(vec!["OP_SHA256"]),
"ripemd160" => Some(vec!["OP_RIPEMD160"]),
"hash160" => Some(vec!["OP_HASH160"]),
"hash256" => Some(vec!["OP_HASH256"]),
"checkSig" => Some(vec!["OP_CHECKSIG"]),
"checkMultiSig" => Some(vec!["OP_CHECKMULTISIG"]),
"len" => Some(vec!["OP_SIZE"]),
"cat" => Some(vec!["OP_CAT"]),
"num2bin" => Some(vec!["OP_NUM2BIN"]),
"bin2num" => Some(vec!["OP_BIN2NUM"]),
"abs" => Some(vec!["OP_ABS"]),
"min" => Some(vec!["OP_MIN"]),
"max" => Some(vec!["OP_MAX"]),
"within" => Some(vec!["OP_WITHIN"]),
"split" => Some(vec!["OP_SPLIT"]),
"left" => Some(vec!["OP_SPLIT", "OP_DROP"]),
"int2str" => Some(vec!["OP_NUM2BIN"]),
"bool" => Some(vec!["OP_0NOTEQUAL"]),
"unpack" => Some(vec!["OP_BIN2NUM"]),
_ => None,
}
}
fn binop_opcodes(op: &str) -> Option<Vec<&'static str>> {
match op {
"+" => Some(vec!["OP_ADD"]),
"-" => Some(vec!["OP_SUB"]),
"*" => Some(vec!["OP_MUL"]),
"/" => Some(vec!["OP_DIV"]),
"%" => Some(vec!["OP_MOD"]),
"===" => Some(vec!["OP_NUMEQUAL"]),
"!==" => Some(vec!["OP_NUMEQUAL", "OP_NOT"]),
"<" => Some(vec!["OP_LESSTHAN"]),
">" => Some(vec!["OP_GREATERTHAN"]),
"<=" => Some(vec!["OP_LESSTHANOREQUAL"]),
">=" => Some(vec!["OP_GREATERTHANOREQUAL"]),
"&&" => Some(vec!["OP_BOOLAND"]),
"||" => Some(vec!["OP_BOOLOR"]),
"&" => Some(vec!["OP_AND"]),
"|" => Some(vec!["OP_OR"]),
"^" => Some(vec!["OP_XOR"]),
"<<" => Some(vec!["OP_LSHIFT"]),
">>" => Some(vec!["OP_RSHIFT"]),
_ => None,
}
}
fn unaryop_opcodes(op: &str) -> Option<Vec<&'static str>> {
match op {
"!" => Some(vec!["OP_NOT"]),
"-" => Some(vec!["OP_NEGATE"]),
"~" => Some(vec!["OP_INVERT"]),
_ => None,
}
}
// ---------------------------------------------------------------------------
// Stack map
// ---------------------------------------------------------------------------
/// Tracks named values on the stack. Index 0 is the bottom; last is the top.
/// Empty string means anonymous/consumed slot.
#[derive(Debug, Clone)]
struct StackMap {
slots: Vec<String>,
}
impl StackMap {
fn new(initial: &[String]) -> Self {
StackMap {
slots: initial.to_vec(),
}
}
fn depth(&self) -> usize {
self.slots.len()
}
fn push(&mut self, name: &str) {
self.slots.push(name.to_string());
}
fn pop(&mut self) -> String {
self.slots.pop().expect("stack underflow")
}
fn find_depth(&self, name: &str) -> Option<usize> {
for (i, slot) in self.slots.iter().enumerate().rev() {
if slot == name {
return Some(self.slots.len() - 1 - i);
}
}
None
}
fn has(&self, name: &str) -> bool {
self.slots.iter().any(|s| s == name)
}
fn remove_at_depth(&mut self, depth_from_top: usize) -> String {
let index = self.slots.len() - 1 - depth_from_top;
self.slots.remove(index)
}
fn peek_at_depth(&self, depth_from_top: usize) -> &str {
let index = self.slots.len() - 1 - depth_from_top;
&self.slots[index]
}
fn rename_at_depth(&mut self, depth_from_top: usize, new_name: &str) {
let idx = self.slots.len() - 1 - depth_from_top;
self.slots[idx] = new_name.to_string();
}
fn swap(&mut self) {
let n = self.slots.len();
assert!(n >= 2, "stack underflow on swap");
self.slots.swap(n - 1, n - 2);
}
fn dup(&mut self) {
assert!(!self.slots.is_empty(), "stack underflow on dup");
let top = self.slots.last().unwrap().clone();
self.slots.push(top);
}
/// Get the set of all non-empty slot names.
fn named_slots(&self) -> HashSet<String> {
self.slots.iter().filter(|s| !s.is_empty()).cloned().collect()
}
}
// ---------------------------------------------------------------------------
// Use analysis
// ---------------------------------------------------------------------------
fn compute_last_uses(bindings: &[ANFBinding]) -> HashMap<String, usize> {
let mut last_use = HashMap::new();
for (i, binding) in bindings.iter().enumerate() {
for r in collect_refs(&binding.value) {
last_use.insert(r, i);
}
}
last_use
}
fn collect_refs(value: &ANFValue) -> Vec<String> {
let mut refs = Vec::new();
match value {
ANFValue::LoadParam { name } => {
// Track param name so last-use analysis keeps the param on the stack
// (via PICK) until its final load_param, then consumes it (via ROLL).
refs.push(name.clone());
}
ANFValue::LoadProp { .. }
| ANFValue::GetStateScript { .. } => {}
ANFValue::LoadConst { value: v } => {
// load_const with @ref: values reference another binding
if let Some(s) = v.as_str() {
if s.len() > 5 && &s[..5] == "@ref:" {
refs.push(s[5..].to_string());
}
}
}
ANFValue::BinOp { left, right, .. } => {
refs.push(left.clone());
refs.push(right.clone());
}
ANFValue::UnaryOp { operand, .. } => {
refs.push(operand.clone());
}
ANFValue::Call { args, .. } => {
refs.extend(args.iter().cloned());
}
ANFValue::MethodCall { object, args, .. } => {
refs.push(object.clone());
refs.extend(args.iter().cloned());
}
ANFValue::If {
cond,
then,
else_branch,
} => {
refs.push(cond.clone());
for b in then {
refs.extend(collect_refs(&b.value));
}
for b in else_branch {
refs.extend(collect_refs(&b.value));
}
}
ANFValue::Loop { body, .. } => {
for b in body {
refs.extend(collect_refs(&b.value));
}
}
ANFValue::Assert { value } => {
refs.push(value.clone());
}
ANFValue::UpdateProp { value, .. } => {
refs.push(value.clone());
}
ANFValue::CheckPreimage { preimage } => {
refs.push(preimage.clone());
}
ANFValue::DeserializeState { preimage } => {
refs.push(preimage.clone());
}
ANFValue::AddOutput { satoshis, state_values, preimage } => {
refs.push(satoshis.clone());
refs.extend(state_values.iter().cloned());
if !preimage.is_empty() {
refs.push(preimage.clone());
}
}
ANFValue::AddRawOutput { satoshis, script_bytes } => {
refs.push(satoshis.clone());
refs.push(script_bytes.clone());
}
ANFValue::ArrayLiteral { elements } => {
refs.extend(elements.iter().cloned());
}
}
refs
}
// ---------------------------------------------------------------------------
// Lowering context
// ---------------------------------------------------------------------------
struct LoweringContext {
sm: StackMap,
ops: Vec<StackOp>,
/// Parallel to `ops`: source location for each emitted op.
source_locs: Vec<Option<crate::ir::SourceLocation>>,
max_depth: usize,
properties: Vec<ANFProperty>,
private_methods: HashMap<String, ANFMethod>,
/// Binding names defined in the current lowerBindings scope.
/// Used by @ref: handler to decide whether to consume (local) or copy (outer-scope).
local_bindings: HashSet<String>,
/// Parent-scope refs that must not be consumed (used after current if-branch).
outer_protected_refs: Option<HashSet<String>>,
/// True when executing inside an if-branch. update_prop skips old-value
/// removal so that the same-property detection in lower_if can handle it.
inside_branch: bool,
/// Current source location from the ANF binding being lowered.
current_source_loc: Option<crate::ir::SourceLocation>,
}
impl LoweringContext {
fn new(params: &[String], properties: &[ANFProperty]) -> Self {
let mut ctx = LoweringContext {
sm: StackMap::new(params),
ops: Vec::new(),
source_locs: Vec::new(),
max_depth: 0,
properties: properties.to_vec(),
private_methods: HashMap::new(),
local_bindings: HashSet::new(),
outer_protected_refs: None,
inside_branch: false,
current_source_loc: None,
};
ctx.track_depth();
ctx
}
fn track_depth(&mut self) {
if self.sm.depth() > self.max_depth {
self.max_depth = self.sm.depth();
}
}
fn emit_op(&mut self, op: StackOp) {
self.ops.push(op);
self.source_locs.push(self.current_source_loc.clone());
self.track_depth();
}
/// Emit a Bitcoin varint encoding of the length on top of the stack.
///
/// Expects stack: `[..., script, len]`
/// Leaves stack: `[..., script, varint_bytes]`
///
/// OP_NUM2BIN uses sign-magnitude encoding where values 128-255 need 2 bytes
/// (sign bit). To produce a correct 1-byte unsigned varint, we use
/// OP_NUM2BIN 2 then SPLIT to extract only the low byte.
/// Similarly for 2-byte unsigned varint, we use OP_NUM2BIN 4 then SPLIT.
fn emit_varint_encoding(&mut self) {
// Stack: [..., script, len]
self.emit_op(StackOp::Dup); // [script, len, len]
self.sm.dup();
self.emit_op(StackOp::Push(PushValue::Int(253))); // [script, len, len, 253]
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_LESSTHAN".into())); // [script, len, isSmall]
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_IF".into()));
self.sm.pop(); // pop condition
// Then: 1-byte varint (len < 253)
// Use NUM2BIN 2 to avoid sign-magnitude issue for values 128-252,
// then take only the first (low) byte via SPLIT.
self.emit_op(StackOp::Push(PushValue::Int(2))); // [script, len, 2]
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".into())); // [script, len_2bytes]
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(1))); // [script, len_2bytes, 1]
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into())); // [script, lowByte, highByte]
self.sm.pop();
self.sm.pop();
self.sm.push(""); // lowByte
self.sm.push(""); // highByte
self.emit_op(StackOp::Drop); // [script, lowByte]
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_ELSE".into()));
// Else: 0xfd + 2-byte LE varint (len >= 253)
// Use NUM2BIN 4 to avoid sign-magnitude issue for values >= 32768,
// then take only the first 2 (low) bytes via SPLIT.
self.emit_op(StackOp::Push(PushValue::Int(4))); // [script, len, 4]
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".into())); // [script, len_4bytes]
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(2))); // [script, len_4bytes, 2]
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into())); // [script, low2bytes, high2bytes]
self.sm.pop();
self.sm.pop();
self.sm.push(""); // low2bytes
self.sm.push(""); // high2bytes
self.emit_op(StackOp::Drop); // [script, low2bytes]
self.sm.pop();
self.emit_op(StackOp::Push(PushValue::Bytes(vec![0xfd])));
self.sm.push("");
self.emit_op(StackOp::Swap);
self.sm.swap();
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_ENDIF".into()));
// --- Stack: [..., script, varint] ---
}
/// Emit push-data encoding for a ByteString value on top of the stack.
///
/// Expects stack: [..., bs_value]
/// Leaves stack: [..., pushdata_encoded_value]
fn emit_push_data_encode(&mut self) {
self.emit_op(StackOp::Opcode("OP_SIZE".into()));
self.sm.push("");
self.emit_op(StackOp::Dup);
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(76)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_LESSTHAN".into()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_IF".into()));
self.sm.pop();
let sm_after_outer_if = self.sm.clone();
// THEN: len <= 75
self.emit_op(StackOp::Push(PushValue::Int(2)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".into()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(1)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Drop); self.sm.pop();
self.emit_op(StackOp::Swap); self.sm.swap();
self.sm.pop(); self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.push("");
let sm_end_target = self.sm.clone();
self.emit_op(StackOp::Opcode("OP_ELSE".into()));
self.sm = sm_after_outer_if.clone();
self.emit_op(StackOp::Dup);
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(256)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_LESSTHAN".into()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_IF".into()));
self.sm.pop();
let sm_after_inner_if = self.sm.clone();
// THEN: 76-255 → 0x4c + 1-byte
self.emit_op(StackOp::Push(PushValue::Int(2)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".into()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(1)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Drop); self.sm.pop();
self.emit_op(StackOp::Push(PushValue::Bytes(vec![0x4c])));
self.sm.push("");
self.emit_op(StackOp::Swap); self.sm.swap();
self.sm.pop(); self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.push("");
self.emit_op(StackOp::Swap); self.sm.swap();
self.sm.pop(); self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_ELSE".into()));
self.sm = sm_after_inner_if;
// ELSE: >= 256 → 0x4d + 2-byte LE
self.emit_op(StackOp::Push(PushValue::Int(4)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".into()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(2)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Drop); self.sm.pop();
self.emit_op(StackOp::Push(PushValue::Bytes(vec![0x4d])));
self.sm.push("");
self.emit_op(StackOp::Swap); self.sm.swap();
self.sm.pop(); self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.push("");
self.emit_op(StackOp::Swap); self.sm.swap();
self.sm.pop(); self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_ENDIF".into()));
self.emit_op(StackOp::Opcode("OP_ENDIF".into()));
self.sm = sm_end_target;
}
/// Emit push-data decoding for a ByteString state field.
///
/// Expects stack: [..., state_bytes]
/// Leaves stack: [..., data, remaining_state]
fn emit_push_data_decode(&mut self) {
self.emit_op(StackOp::Push(PushValue::Int(1)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Swap); self.sm.swap();
self.emit_op(StackOp::Opcode("OP_BIN2NUM".into()));
self.emit_op(StackOp::Dup);
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(76)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_LESSTHAN".into()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_IF".into()));
self.sm.pop();
let sm_after_outer_if = self.sm.clone();
// THEN: fb < 76 → direct length
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
let sm_end_target = self.sm.clone();
self.emit_op(StackOp::Opcode("OP_ELSE".into()));
self.sm = sm_after_outer_if.clone();
self.emit_op(StackOp::Dup);
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(77)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUMEQUAL".into()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_IF".into()));
self.sm.pop();
let sm_after_inner_if = self.sm.clone();
// THEN: fb == 77 → 2-byte LE
self.emit_op(StackOp::Drop); self.sm.pop();
self.emit_op(StackOp::Push(PushValue::Int(2)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Swap); self.sm.swap();
self.emit_op(StackOp::Opcode("OP_BIN2NUM".into()));
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Opcode("OP_ELSE".into()));
self.sm = sm_after_inner_if;
// ELSE: fb == 76 → 1-byte
self.emit_op(StackOp::Drop); self.sm.pop();
self.emit_op(StackOp::Push(PushValue::Int(1)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Swap); self.sm.swap();
self.emit_op(StackOp::Opcode("OP_BIN2NUM".into()));
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Opcode("OP_ENDIF".into()));
self.emit_op(StackOp::Opcode("OP_ENDIF".into()));
self.sm = sm_end_target;
}
fn is_last_use(&self, name: &str, current_index: usize, last_uses: &HashMap<String, usize>) -> bool {
match last_uses.get(name) {
None => true,
Some(&last) => last <= current_index,
}
}
fn bring_to_top(&mut self, name: &str, consume: bool) {
let depth = self
.sm
.find_depth(name)
.unwrap_or_else(|| panic!("value '{}' not found on stack", name));
if depth == 0 {
if !consume {
self.emit_op(StackOp::Dup);
self.sm.dup();
}
return;
}
if depth == 1 && consume {
self.emit_op(StackOp::Swap);
self.sm.swap();
return;
}
if consume {
if depth == 2 {
self.emit_op(StackOp::Rot);
let removed = self.sm.remove_at_depth(2);
self.sm.push(&removed);
} else {
self.emit_op(StackOp::Push(PushValue::Int(depth as i128)));
self.sm.push(""); // temporary depth literal
self.emit_op(StackOp::Roll { depth });
self.sm.pop(); // remove depth literal
let rolled = self.sm.remove_at_depth(depth);
self.sm.push(&rolled);
}
} else {
if depth == 1 {
self.emit_op(StackOp::Over);
let picked = self.sm.peek_at_depth(1).to_string();
self.sm.push(&picked);
} else {
self.emit_op(StackOp::Push(PushValue::Int(depth as i128)));
self.sm.push(""); // temporary
self.emit_op(StackOp::Pick { depth });
self.sm.pop(); // remove depth literal
let picked = self.sm.peek_at_depth(depth).to_string();
self.sm.push(&picked);
}
}
self.track_depth();
}
/// Drain branch-private residue from below TOS at the end of a branch
/// body, so both branches converge to a layout the parent stack model can
/// faithfully describe before OP_ENDIF (issue #36).
///
/// A slot is residue when its name is NOT in `pre_if_names` (the snapshot
/// of the parent's named slots taken before the branch ran). This catches
/// both anonymous slots (empty-named, pushed by intrinsics like substr's
/// OP_SPLIT residue) and named branch-local bindings that lingered past
/// their last-use (e.g. dead-code load_const intermediates the optimizer
/// didn't fold).
///
/// Slots whose name was already in `pre_if_names` are kept — including
/// duplicates created by reassigning an outer-scope local from inside the
/// branch. The TOS slot is also kept regardless.
fn drain_branch_private_residue(&mut self, pre_if_names: &HashSet<String>) {
let mut drain_depths: Vec<usize> = Vec::new();
for d in 1..self.sm.depth() {
let name = self.sm.peek_at_depth(d);
if name.is_empty() {
drain_depths.push(d);
} else if !pre_if_names.contains(name) {
drain_depths.push(d);
}
}
if drain_depths.is_empty() {
return;
}
drain_depths.sort_by(|a, b| b.cmp(a));
for depth in drain_depths {
if depth == 1 {
self.emit_op(StackOp::Nip);
self.sm.remove_at_depth(1);
} else {
self.emit_op(StackOp::Push(PushValue::Int(depth as i128)));
self.sm.push("");
self.emit_op(StackOp::Roll { depth });
self.sm.pop();
let rolled = self.sm.remove_at_depth(depth);
self.sm.push(&rolled);
self.emit_op(StackOp::Drop);
self.sm.pop();
}
}
}
// -----------------------------------------------------------------------
// Lower bindings
// -----------------------------------------------------------------------
fn lower_bindings(&mut self, bindings: &[ANFBinding], terminal_assert: bool) {
self.local_bindings = bindings.iter().map(|b| b.name.clone()).collect();
let mut last_uses = compute_last_uses(bindings);
// Protect parent-scope refs that are still needed after this scope
if let Some(ref protected) = self.outer_protected_refs {
for r in protected {
last_uses.insert(r.clone(), bindings.len());
}
}
// Find the terminal binding index (if terminal_assert is set).
// If the last binding is an 'if' whose branches end in asserts,
// that 'if' is the terminal point (not an earlier standalone assert).
let mut last_assert_idx: isize = -1;
let mut terminal_if_idx: isize = -1;
if terminal_assert {
let last_binding = bindings.last();
if let Some(b) = last_binding {
if matches!(&b.value, ANFValue::If { .. }) {
terminal_if_idx = (bindings.len() - 1) as isize;
} else {
for i in (0..bindings.len()).rev() {
if matches!(&bindings[i].value, ANFValue::Assert { .. }) {
last_assert_idx = i as isize;
break;
}
}
}
}
}
for (i, binding) in bindings.iter().enumerate() {
// Propagate source location from ANF binding to StackOps
self.current_source_loc = binding.source_loc.clone();
if matches!(&binding.value, ANFValue::Assert { .. }) && i as isize == last_assert_idx {
// Terminal assert: leave value on stack instead of OP_VERIFY
if let ANFValue::Assert { value } = &binding.value {
self.lower_assert(value, i, &last_uses, true);
}
} else if matches!(&binding.value, ANFValue::If { .. }) && i as isize == terminal_if_idx {
// Terminal if: propagate terminalAssert into both branches
if let ANFValue::If { cond, then, else_branch } = &binding.value {
self.lower_if(&binding.name, cond, then, else_branch, i, &last_uses, true);
}
} else {
self.lower_binding(binding, i, &last_uses);
}
}
}
fn lower_binding(
&mut self,
binding: &ANFBinding,
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
let name = &binding.name;
match &binding.value {
ANFValue::LoadParam {
name: param_name, ..
} => {
self.lower_load_param(name, param_name, binding_index, last_uses);
}
ANFValue::LoadProp {
name: prop_name, ..
} => {
self.lower_load_prop(name, prop_name);
}
ANFValue::LoadConst { .. } => {
self.lower_load_const(name, &binding.value, binding_index, last_uses);
}
ANFValue::BinOp {
op, left, right, result_type, ..
} => {
self.lower_bin_op(name, op, left, right, binding_index, last_uses, result_type.as_deref());
}
ANFValue::UnaryOp { op, operand, .. } => {
self.lower_unary_op(name, op, operand, binding_index, last_uses);
}
ANFValue::Call {
func: func_name,
args,
} => {
self.lower_call(name, func_name, args, binding_index, last_uses);
}
ANFValue::MethodCall {
object,
method,
args,
} => {
self.lower_method_call(name, object, method, args, binding_index, last_uses);
}
ANFValue::If {
cond,
then,
else_branch,
} => {
self.lower_if(name, cond, then, else_branch, binding_index, last_uses, false);
}
ANFValue::Loop {
count,
body,
iter_var,
} => {
self.lower_loop(name, *count, body, iter_var);
}
ANFValue::Assert { value } => {
self.lower_assert(value, binding_index, last_uses, false);
}
ANFValue::UpdateProp {
name: prop_name,
value,
} => {
self.lower_update_prop(prop_name, value, binding_index, last_uses);
}
ANFValue::GetStateScript {} => {
self.lower_get_state_script(name);
}
ANFValue::CheckPreimage { preimage } => {
self.lower_check_preimage(name, preimage, binding_index, last_uses);
}
ANFValue::DeserializeState { preimage } => {
self.lower_deserialize_state(preimage, binding_index, last_uses);
}
ANFValue::AddOutput { satoshis, state_values, preimage } => {
self.lower_add_output(name, satoshis, state_values, preimage, binding_index, last_uses);
}
ANFValue::AddRawOutput { satoshis, script_bytes } => {
self.lower_add_raw_output(name, satoshis, script_bytes, binding_index, last_uses);
}
ANFValue::ArrayLiteral { elements } => {
self.lower_array_literal(name, elements, binding_index, last_uses);
}
}
}
// -----------------------------------------------------------------------
// Individual lowering methods
// -----------------------------------------------------------------------
fn lower_load_param(
&mut self,
binding_name: &str,
param_name: &str,
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
if self.sm.has(param_name) {
let is_last = self.is_last_use(param_name, binding_index, last_uses);
self.bring_to_top(param_name, is_last);
self.sm.pop();
self.sm.push(binding_name);
} else {
self.emit_op(StackOp::Push(PushValue::Int(0)));
self.sm.push(binding_name);
}
}
fn lower_load_prop(&mut self, binding_name: &str, prop_name: &str) {
let prop = self.properties.iter().find(|p| p.name == prop_name).cloned();
if self.sm.has(prop_name) {
// Property has been updated (via update_prop) — use the stack value.
// Must check this BEFORE initial_value — after update_prop, we need the
// updated value, not the original constant.
self.bring_to_top(prop_name, false);
self.sm.pop();
} else if let Some(ref p) = prop {
if let Some(ref val) = p.initial_value {
self.push_json_value(val);
} else {
// Property value will be provided at deployment time; emit a placeholder.
// The emitter records byte offsets so the SDK can splice in real values.
let param_index = self
.properties
.iter()
.position(|p2| p2.name == prop_name)
.unwrap_or(0);
self.emit_op(StackOp::Placeholder {
param_index,
param_name: prop_name.to_string(),
});
}
} else {
// Property not found and not on stack — emit placeholder with index 0.
let param_index = self
.properties
.iter()
.position(|p2| p2.name == prop_name)
.unwrap_or(0);
self.emit_op(StackOp::Placeholder {
param_index,
param_name: prop_name.to_string(),
});
}
self.sm.push(binding_name);
}
fn push_json_value(&mut self, val: &serde_json::Value) {
match val {
serde_json::Value::Bool(b) => {
self.emit_op(StackOp::Push(PushValue::Bool(*b)));
}
serde_json::Value::Number(n) => {
let i = n.as_i64().map(|v| v as i128).unwrap_or(0);
self.emit_op(StackOp::Push(PushValue::Int(i)));
}
serde_json::Value::String(s) => {
let bytes = hex_to_bytes(s);
self.emit_op(StackOp::Push(PushValue::Bytes(bytes)));
}
_ => {
self.emit_op(StackOp::Push(PushValue::Int(0)));
}
}
}
fn lower_load_const(&mut self, binding_name: &str, value: &ANFValue, binding_index: usize, last_uses: &HashMap<String, usize>) {
// Handle @ref: aliases (ANF variable aliasing)
// When a load_const has a string value starting with "@ref:", it's an alias
// to another binding. We bring that value to the top via PICK (non-consuming)
// unless this is the last use, in which case we consume it via ROLL.
if let Some(ConstValue::Str(ref s)) = value.const_value() {
if s.len() > 5 && &s[..5] == "@ref:" {
let ref_name = &s[5..];
if self.sm.has(ref_name) {
// Only consume (ROLL) if the ref target is a local binding in the
// current scope. Outer-scope refs must be copied (PICK) so that the
// parent stackMap stays in sync (critical for IfElse branches and
// BoundedLoop iterations).
let consume = self.local_bindings.contains(ref_name)
&& self.is_last_use(ref_name, binding_index, last_uses);
self.bring_to_top(ref_name, consume);
self.sm.pop();
self.sm.push(binding_name);
} else {
// Referenced value not on stack -- push a placeholder
self.emit_op(StackOp::Push(PushValue::Int(0)));
self.sm.push(binding_name);
}
return;
}
// Handle @this marker -- compile-time concept, not a runtime value
if s == "@this" {
self.emit_op(StackOp::Push(PushValue::Int(0)));
self.sm.push(binding_name);
return;
}
}
match value.const_value() {
Some(ConstValue::Bool(b)) => {
self.emit_op(StackOp::Push(PushValue::Bool(b)));
}
Some(ConstValue::Int(n)) => {
self.emit_op(StackOp::Push(PushValue::Int(n)));
}
Some(ConstValue::Str(s)) => {
let bytes = hex_to_bytes(&s);
self.emit_op(StackOp::Push(PushValue::Bytes(bytes)));
}
None => {
self.emit_op(StackOp::Push(PushValue::Int(0)));
}
}
self.sm.push(binding_name);
}
fn lower_bin_op(
&mut self,
binding_name: &str,
op: &str,
left: &str,
right: &str,
binding_index: usize,
last_uses: &HashMap<String, usize>,
result_type: Option<&str>,
) {
let left_is_last = self.is_last_use(left, binding_index, last_uses);
self.bring_to_top(left, left_is_last);
let right_is_last = self.is_last_use(right, binding_index, last_uses);
self.bring_to_top(right, right_is_last);
self.sm.pop();
self.sm.pop();
// For equality operators, choose OP_EQUAL vs OP_NUMEQUAL based on operand type.
// For addition, choose OP_CAT vs OP_ADD based on operand type.
if result_type == Some("bytes") && op == "+" {
self.emit_op(StackOp::Opcode("OP_CAT".to_string()));
} else if result_type == Some("bytes") && (op == "===" || op == "!==") {
self.emit_op(StackOp::Opcode("OP_EQUAL".to_string()));
if op == "!==" {
self.emit_op(StackOp::Opcode("OP_NOT".to_string()));
}
} else {
let codes = binop_opcodes(op)
.unwrap_or_else(|| panic!("unknown binary operator: {}", op));
for code in codes {
self.emit_op(StackOp::Opcode(code.to_string()));
}
}
self.sm.push(binding_name);
self.track_depth();
}
fn lower_unary_op(
&mut self,
binding_name: &str,
op: &str,
operand: &str,
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
let is_last = self.is_last_use(operand, binding_index, last_uses);
self.bring_to_top(operand, is_last);
self.sm.pop();
let codes = unaryop_opcodes(op)
.unwrap_or_else(|| panic!("unknown unary operator: {}", op));
for code in codes {
self.emit_op(StackOp::Opcode(code.to_string()));
}
self.sm.push(binding_name);
self.track_depth();
}
fn lower_call(
&mut self,
binding_name: &str,
func_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
// Special handling for assert
if func_name == "assert" {
if !args.is_empty() {
let is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], is_last);
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_VERIFY".to_string()));
self.sm.push(binding_name);
}
return;
}
// super() in constructor -- no opcode emission needed.
// Constructor args are already on the stack.
if func_name == "super" {
self.sm.push(binding_name);
return;
}
// checkMultiSig(sigs, pks) — special handling for OP_CHECKMULTISIG.
if func_name == "checkMultiSig" && args.len() == 2 {
self.lower_check_multi_sig(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "__array_access" {
self.lower_array_access(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "reverseBytes" {
self.lower_reverse_bytes(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "substr" {
self.lower_substr(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "verifyRabinSig" {
self.lower_verify_rabin_sig(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "verifyWOTS" {
self.lower_verify_wots(binding_name, args, binding_index, last_uses);
return;
}
if func_name.starts_with("verifySLHDSA_") {
let param_key = func_name.trim_start_matches("verifySLHDSA_");
self.lower_verify_slh_dsa(binding_name, param_key, args, binding_index, last_uses);
return;
}
if func_name == "sha256Compress" {
self.lower_sha256_compress(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "sha256Finalize" {
self.lower_sha256_finalize(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "blake3Compress" {
self.lower_blake3_compress(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "blake3Hash" {
self.lower_blake3_hash(binding_name, args, binding_index, last_uses);
return;
}
if is_ec_builtin(func_name) {
self.lower_ec_builtin(binding_name, func_name, args, binding_index, last_uses);
return;
}
if func_name == "safediv" {
self.lower_safediv(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "safemod" {
self.lower_safemod(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "clamp" {
self.lower_clamp(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "pow" {
self.lower_pow(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "mulDiv" {
self.lower_mul_div(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "percentOf" {
self.lower_percent_of(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "sqrt" {
self.lower_sqrt(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "gcd" {
self.lower_gcd(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "divmod" {
self.lower_divmod(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "log2" {
self.lower_log2(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "sign" {
self.lower_sign(binding_name, args, binding_index, last_uses);
return;
}
if func_name == "right" {
self.lower_right(binding_name, args, binding_index, last_uses);
return;
}
// pack and toByteString are no-ops: the value is already on the stack in
// the correct representation. We just consume the arg and rename.
if func_name == "pack" || func_name == "toByteString" {
if !args.is_empty() {
let is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], is_last);
self.sm.pop();
}
self.sm.push(binding_name);
return;
}
// computeStateOutputHash(preimage, stateBytes) — builds full BIP-143 output
// serialization for single-output stateful continuation, then hashes it.
if func_name == "computeStateOutputHash" {
self.lower_compute_state_output_hash(binding_name, args, binding_index, last_uses);
return;
}
// computeStateOutput(preimage, stateBytes) — same as computeStateOutputHash
// but returns raw output bytes WITHOUT hashing. Used when the output bytes
// need to be concatenated with a change output before hashing.
if func_name == "computeStateOutput" {
self.lower_compute_state_output(binding_name, args, binding_index, last_uses);
return;
}
// buildChangeOutput(pkh, amount) — builds a P2PKH output serialization:
// amount(8LE) + varint(25) + OP_DUP OP_HASH160 OP_PUSHBYTES_20 <pkh> OP_EQUALVERIFY OP_CHECKSIG
// = amount(8LE) + 0x19 + 76a914 <pkh:20> 88ac
if func_name == "buildChangeOutput" {
self.lower_build_change_output(binding_name, args, binding_index, last_uses);
return;
}
// Preimage field extractors — each needs a custom OP_SPLIT sequence
// because OP_SPLIT produces two stack values and the intermediate stack
// management cannot be expressed in the simple builtin_opcodes table.
if func_name.starts_with("extract") {
self.lower_extractor(binding_name, func_name, args, binding_index, last_uses);
return;
}
// General builtin: push args in order, then emit opcodes
for arg in args {
let is_last = self.is_last_use(arg, binding_index, last_uses);
self.bring_to_top(arg, is_last);
}
for _ in args {
self.sm.pop();
}
if let Some(codes) = builtin_opcodes(func_name) {
for code in codes {
self.emit_op(StackOp::Opcode(code.to_string()));
}
} else {
// Unknown function -- push a placeholder
self.emit_op(StackOp::Push(PushValue::Int(0)));
self.sm.push(binding_name);
return;
}
if func_name == "split" {
self.sm.push("");
self.sm.push(binding_name);
} else if func_name == "len" {
self.sm.push("");
self.sm.push(binding_name);
} else {
self.sm.push(binding_name);
}
self.track_depth();
}
fn lower_method_call(
&mut self,
binding_name: &str,
object: &str,
method: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
// Consume the @this object reference — it's a compile-time concept,
// not a runtime value. Without this, 0n stays on the stack.
if self.sm.has(object) {
self.bring_to_top(object, true);
self.emit_op(StackOp::Drop);
self.sm.pop();
}
if method == "getStateScript" {
self.lower_get_state_script(binding_name);
return;
}
// Check if this is a private method call that should be inlined
if let Some(private_method) = self.private_methods.get(method).cloned() {
self.inline_method_call(binding_name, &private_method, args, binding_index, last_uses);
return;
}
// For other method calls, treat like a function call
self.lower_call(binding_name, method, args, binding_index, last_uses);
}
/// Inline a private method by lowering its body in the current context.
/// The method's parameters are bound to the call arguments.
fn inline_method_call(
&mut self,
binding_name: &str,
method: &ANFMethod,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
// Track shadowed names so we can restore them after the body runs.
// When a param name already exists on the stack, temporarily rename
// the existing entry to avoid duplicate names which break Set-based
// branch reconciliation in lower_if.
let mut shadowed: Vec<(String, String)> = Vec::new();
// Bind call arguments to private method params.
for (i, arg) in args.iter().enumerate() {
if i < method.params.len() {
let is_last = self.is_last_use(arg, binding_index, last_uses);
self.bring_to_top(arg, is_last);
self.sm.pop();
let param_name = &method.params[i].name;
// If param_name already exists on the stack, shadow it by renaming
// the existing entry to prevent duplicate-name issues.
if self.sm.has(param_name) {
let existing_depth = self.sm.find_depth(param_name).unwrap();
let shadowed_name = format!("__shadowed_{}_{}", binding_index, param_name);
self.sm.rename_at_depth(existing_depth, &shadowed_name);
shadowed.push((param_name.clone(), shadowed_name));
}
// Rename to param name
self.sm.push(param_name);
}
}
// Lower the method body
self.lower_bindings(&method.body, false);
// Restore shadowed names so the caller's scope sees its original entries.
for (param_name, shadowed_name) in &shadowed {
if self.sm.has(shadowed_name) {
let depth = self.sm.find_depth(shadowed_name).unwrap();
self.sm.rename_at_depth(depth, param_name);
}
}
// The last binding's result should be on top of the stack.
// Rename it to the calling binding name.
if !method.body.is_empty() {
let last_binding_name = &method.body[method.body.len() - 1].name;
if self.sm.depth() > 0 {
let top_name = self.sm.peek_at_depth(0).to_string();
if top_name == *last_binding_name {
self.sm.pop();
self.sm.push(binding_name);
}
}
}
}
fn lower_if(
&mut self,
binding_name: &str,
cond: &str,
then_bindings: &[ANFBinding],
else_bindings: &[ANFBinding],
binding_index: usize,
last_uses: &HashMap<String, usize>,
terminal_assert: bool,
) {
let is_last = self.is_last_use(cond, binding_index, last_uses);
self.bring_to_top(cond, is_last);
self.sm.pop(); // OP_IF consumes condition
// Identify parent-scope items still needed after this if-expression.
let mut protected_refs = HashSet::new();
for (ref_name, &last_idx) in last_uses.iter() {
if last_idx > binding_index && self.sm.has(ref_name) {
protected_refs.insert(ref_name.clone());
}
}
// Snapshot parent stackMap names before branches run
let pre_if_names = self.sm.named_slots();
// Lower then-branch
let mut then_ctx = LoweringContext::new(&[], &self.properties);
then_ctx.sm = self.sm.clone();
then_ctx.outer_protected_refs = Some(protected_refs.clone());
then_ctx.inside_branch = true;
then_ctx.lower_bindings(then_bindings, terminal_assert);
then_ctx.drain_branch_private_residue(&pre_if_names);
if terminal_assert && then_ctx.sm.depth() > 1 {
let excess = then_ctx.sm.depth() - 1;
for _ in 0..excess {
then_ctx.emit_op(StackOp::Nip);
then_ctx.sm.remove_at_depth(1);
}
}
// Lower else-branch
let mut else_ctx = LoweringContext::new(&[], &self.properties);
else_ctx.sm = self.sm.clone();
else_ctx.outer_protected_refs = Some(protected_refs);
else_ctx.inside_branch = true;
else_ctx.lower_bindings(else_bindings, terminal_assert);
else_ctx.drain_branch_private_residue(&pre_if_names);
if terminal_assert && else_ctx.sm.depth() > 1 {
let excess = else_ctx.sm.depth() - 1;
for _ in 0..excess {
else_ctx.emit_op(StackOp::Nip);
else_ctx.sm.remove_at_depth(1);
}
}
// Balance stack between branches so both end at the same depth.
// When addOutput is inside an if-then with no else, the then-branch
// consumes stack items and pushes a serialized output, while the
// else-branch leaves the stack unchanged. Both must end at the same
// depth for correct execution after OP_ENDIF.
//
// Fix: identify items consumed by the then-branch (present in parent
// but gone after then). Emit targeted ROLL+DROP in the else-branch
// to remove those same items, then push empty bytes as placeholder.
// OP_CAT with empty bytes is identity (no-op for output hashing).
// Identify items consumed asymmetrically between branches.
// Phase 1: collect consumed names from both directions.
let post_then_names = then_ctx.sm.named_slots();
let mut consumed_names: Vec<String> = Vec::new();
for name in &pre_if_names {
if !post_then_names.contains(name) && else_ctx.sm.has(name) {
consumed_names.push(name.clone());
}
}
let post_else_names = else_ctx.sm.named_slots();
let mut else_consumed_names: Vec<String> = Vec::new();
for name in &pre_if_names {
if !post_else_names.contains(name) && then_ctx.sm.has(name) {
else_consumed_names.push(name.clone());
}
}
// Phase 2: perform ALL drops before any placeholder pushes.
// This prevents double-placeholder when bilateral drops balance each other.
if !consumed_names.is_empty() {
let mut depths: Vec<usize> = consumed_names
.iter()
.map(|n| else_ctx.sm.find_depth(n).unwrap())
.collect();
depths.sort_by(|a, b| b.cmp(a));
for depth in depths {
if depth == 0 {
else_ctx.emit_op(StackOp::Drop);
else_ctx.sm.pop();
} else if depth == 1 {
else_ctx.emit_op(StackOp::Nip);
else_ctx.sm.remove_at_depth(1);
} else {
else_ctx.emit_op(StackOp::Push(PushValue::Int(depth as i128)));
else_ctx.sm.push("");
else_ctx.emit_op(StackOp::Roll { depth });
else_ctx.sm.pop();
let rolled = else_ctx.sm.remove_at_depth(depth);
else_ctx.sm.push(&rolled);
else_ctx.emit_op(StackOp::Drop);
else_ctx.sm.pop();
}
}
}
if !else_consumed_names.is_empty() {
let mut depths: Vec<usize> = else_consumed_names
.iter()
.map(|n| then_ctx.sm.find_depth(n).unwrap())
.collect();
depths.sort_by(|a, b| b.cmp(a));
for depth in depths {
if depth == 0 {
then_ctx.emit_op(StackOp::Drop);
then_ctx.sm.pop();
} else if depth == 1 {
then_ctx.emit_op(StackOp::Nip);
then_ctx.sm.remove_at_depth(1);
} else {
then_ctx.emit_op(StackOp::Push(PushValue::Int(depth as i128)));
then_ctx.sm.push("");
then_ctx.emit_op(StackOp::Roll { depth });
then_ctx.sm.pop();
let rolled = then_ctx.sm.remove_at_depth(depth);
then_ctx.sm.push(&rolled);
then_ctx.emit_op(StackOp::Drop);
then_ctx.sm.pop();
}
}
}
// Phase 3: single depth-balance check after ALL drops.
// Push placeholder only if one branch is still deeper than the other.
if then_ctx.sm.depth() > else_ctx.sm.depth() {
// When the then-branch reassigned a local variable (if-without-else),
// push a COPY of that variable in the else-branch instead of a generic
// placeholder.
let then_top_p3 = then_ctx.sm.peek_at_depth(0).to_string();
if else_bindings.is_empty() && !then_top_p3.is_empty() && else_ctx.sm.has(&then_top_p3) {
let var_depth = else_ctx.sm.find_depth(&then_top_p3).unwrap();
if var_depth == 0 {
else_ctx.emit_op(StackOp::Dup);
} else {
else_ctx.emit_op(StackOp::Push(PushValue::Int(var_depth as i128)));
else_ctx.sm.push("");
else_ctx.emit_op(StackOp::Pick { depth: var_depth });
else_ctx.sm.pop();
}
else_ctx.sm.push(&then_top_p3);
} else {
else_ctx.emit_op(StackOp::Push(PushValue::Bytes(Vec::new())));
else_ctx.sm.push("");
}
} else if else_ctx.sm.depth() > then_ctx.sm.depth() {
then_ctx.emit_op(StackOp::Push(PushValue::Bytes(Vec::new())));
then_ctx.sm.push("");
}
let then_ops = then_ctx.ops;
let else_ops = else_ctx.ops;
self.emit_op(StackOp::If {
then_ops,
else_ops: if else_ops.is_empty() {
Vec::new()
} else {
else_ops
},
});
// Reconcile parent stackMap: remove items consumed by the branches.
let post_branch_names = then_ctx.sm.named_slots();
for name in &pre_if_names {
if !post_branch_names.contains(name) && self.sm.has(name) {
if let Some(depth) = self.sm.find_depth(name) {
self.sm.remove_at_depth(depth);
}
}
}
// The if expression may produce a result value on top.
if then_ctx.sm.depth() > self.sm.depth() {
let then_top = then_ctx.sm.peek_at_depth(0).to_string();
let else_top = if else_ctx.sm.depth() > 0 {
else_ctx.sm.peek_at_depth(0).to_string()
} else {
String::new()
};
let is_property = self.properties.iter().any(|p| p.name == then_top);
if is_property && !then_top.is_empty() && then_top == else_top
&& then_top != binding_name && self.sm.has(&then_top)
{
// Both branches did update_prop for the same property
self.sm.push(&then_top);
for d in 1..self.sm.depth() {
if self.sm.peek_at_depth(d) == then_top {
if d == 1 {
self.emit_op(StackOp::Nip);
self.sm.remove_at_depth(1);
} else {
self.emit_op(StackOp::Push(PushValue::Int(d as i128)));
self.sm.push("");
self.emit_op(StackOp::Roll { depth: d + 1 });
self.sm.pop();
let rolled = self.sm.remove_at_depth(d);
self.sm.push(&rolled);
self.emit_op(StackOp::Drop);
self.sm.pop();
}
break;
}
}
} else if !then_top.is_empty() && !is_property && else_bindings.is_empty()
&& then_top != binding_name && self.sm.has(&then_top)
{
// If-without-else: then-branch reassigned a local variable that
// was PICKed (outer-protected), leaving a stale copy on the stack.
// Push the local name and remove the stale entry.
self.sm.push(&then_top);
for d in 1..self.sm.depth() {
if self.sm.peek_at_depth(d) == then_top {
if d == 1 {
self.emit_op(StackOp::Nip);
self.sm.remove_at_depth(1);
} else {
self.emit_op(StackOp::Push(PushValue::Int(d as i128)));
self.sm.push("");
self.emit_op(StackOp::Roll { depth: d + 1 });
self.sm.pop();
let rolled = self.sm.remove_at_depth(d);
self.sm.push(&rolled);
self.emit_op(StackOp::Drop);
self.sm.pop();
}
break;
}
}
} else {
self.sm.push(binding_name);
}
} else if else_ctx.sm.depth() > self.sm.depth() {
self.sm.push(binding_name);
} else {
// Void if — don't push phantom
}
self.track_depth();
if then_ctx.max_depth > self.max_depth {
self.max_depth = then_ctx.max_depth;
}
if else_ctx.max_depth > self.max_depth {
self.max_depth = else_ctx.max_depth;
}
}
fn lower_loop(
&mut self,
_binding_name: &str,
count: usize,
body: &[ANFBinding],
iter_var: &str,
) {
// Collect outer-scope names referenced in the loop body.
// These must not be consumed in non-final iterations.
let body_binding_names: HashSet<String> = body.iter().map(|b| b.name.clone()).collect();
let mut outer_refs = HashSet::new();
for b in body {
if let ANFValue::LoadParam { name } = &b.value {
if name != iter_var {
outer_refs.insert(name.clone());
}
}
// Also protect @ref: targets from outer scope (not redefined in body)
if let ANFValue::LoadConst { value: v } = &b.value {
if let Some(s) = v.as_str() {
if s.len() > 5 && &s[..5] == "@ref:" {
let ref_name = &s[5..];
if !body_binding_names.contains(ref_name) {
outer_refs.insert(ref_name.to_string());
}
}
}
}
}
// Temporarily extend localBindings with body binding names so
// @ref: to body-internal values can consume on last use.
let prev_local_bindings = self.local_bindings.clone();
self.local_bindings = self.local_bindings.union(&body_binding_names).cloned().collect();
for i in 0..count {
self.emit_op(StackOp::Push(PushValue::Int(i as i128)));
self.sm.push(iter_var);
let mut last_uses = compute_last_uses(body);
// In non-final iterations, prevent outer-scope refs from being
// consumed by setting their last-use beyond any body binding index.
if i < count - 1 {
for ref_name in &outer_refs {
last_uses.insert(ref_name.clone(), body.len());
}
}
for (j, binding) in body.iter().enumerate() {
self.lower_binding(binding, j, &last_uses);
}
// Clean up the iteration variable if it was not consumed by the body.
// The body may not reference iter_var at all, leaving it on the stack.
if self.sm.has(iter_var) {
let depth = self.sm.find_depth(iter_var);
if let Some(0) = depth {
self.emit_op(StackOp::Drop);
self.sm.pop();
}
}
}
// Restore localBindings
self.local_bindings = prev_local_bindings;
// Note: loops are statements, not expressions — they don't produce a
// physical stack value. Do NOT push a dummy stackMap entry, as it would
// desync the stackMap depth from the physical stack.
}
fn lower_assert(
&mut self,
value_ref: &str,
binding_index: usize,
last_uses: &HashMap<String, usize>,
terminal: bool,
) {
let is_last = self.is_last_use(value_ref, binding_index, last_uses);
self.bring_to_top(value_ref, is_last);
if terminal {
// Terminal assert: leave value on stack for Bitcoin Script's
// final truthiness check (no OP_VERIFY).
} else {
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_VERIFY".to_string()));
}
self.track_depth();
}
fn lower_update_prop(
&mut self,
prop_name: &str,
value_ref: &str,
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
let is_last = self.is_last_use(value_ref, binding_index, last_uses);
self.bring_to_top(value_ref, is_last);
self.sm.pop();
self.sm.push(prop_name);
// When NOT inside an if-branch, remove the old property entry from
// the stack. After liftBranchUpdateProps transforms conditional
// property updates into flat if-expressions + top-level update_prop,
// the old value is dead and must be removed to keep stack depth correct.
// Inside branches, the old value is kept for lower_if's same-property
// detection to handle correctly.
if !self.inside_branch {
for d in 1..self.sm.depth() {
if self.sm.peek_at_depth(d) == prop_name {
if d == 1 {
self.emit_op(StackOp::Nip);
self.sm.remove_at_depth(1);
} else {
self.emit_op(StackOp::Push(PushValue::Int(d as i128)));
self.sm.push("");
self.emit_op(StackOp::Roll { depth: d + 1 });
self.sm.pop();
let rolled = self.sm.remove_at_depth(d);
self.sm.push(&rolled);
self.emit_op(StackOp::Drop);
self.sm.pop();
}
break;
}
}
}
self.track_depth();
}
fn lower_get_state_script(&mut self, binding_name: &str) {
let state_props: Vec<ANFProperty> = self
.properties
.iter()
.filter(|p| !p.readonly)
.cloned()
.collect();
if state_props.is_empty() {
self.emit_op(StackOp::Push(PushValue::Bytes(Vec::new())));
self.sm.push(binding_name);
return;
}
let mut first = true;
for prop in &state_props {
if self.sm.has(&prop.name) {
self.bring_to_top(&prop.name, true); // consume: raw value dead after serialization
} else if let Some(ref val) = prop.initial_value {
self.push_json_value(val);
self.sm.push("");
} else {
self.emit_op(StackOp::Push(PushValue::Int(0)));
self.sm.push("");
}
// Convert numeric/boolean values to fixed-width bytes via OP_NUM2BIN
if prop.prop_type == "bigint" {
self.emit_op(StackOp::Push(PushValue::Int(8)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".to_string()));
self.sm.pop(); // pop the width
} else if prop.prop_type == "boolean" {
self.emit_op(StackOp::Push(PushValue::Int(1)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".to_string()));
self.sm.pop(); // pop the width
} else if prop.prop_type == "ByteString" {
// Prepend push-data length prefix (matching SDK format)
self.emit_push_data_encode();
}
// Other byte types (PubKey, Sig, Sha256, etc.) need no conversion
if !first {
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".to_string()));
self.sm.push("");
}
first = false;
}
self.sm.pop();
self.sm.push(binding_name);
self.track_depth();
}
/// Builds the full BIP-143 output serialization for a single-output stateful
/// continuation and hashes it with SHA256d. Uses _codePart implicit parameter
/// for the code portion and extracts the amount from the preimage.
fn lower_compute_state_output_hash(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &std::collections::HashMap<String, usize>,
) {
let preimage_ref = &args[0];
let state_bytes_ref = &args[1];
// Bring stateBytes to stack first.
let sb_last = self.is_last_use(state_bytes_ref, binding_index, last_uses);
self.bring_to_top(state_bytes_ref, sb_last);
// Extract amount from preimage for the continuation output.
let pre_last = self.is_last_use(preimage_ref, binding_index, last_uses);
self.bring_to_top(preimage_ref, pre_last);
// Extract amount: last 52 bytes, take 8 bytes at offset 0.
self.emit_op(StackOp::Opcode("OP_SIZE".into()));
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(52))); // 8 (amount) + 44 (tail)
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SUB".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into())); // [prefix, amountAndTail]
self.sm.pop();
self.sm.pop();
self.sm.push(""); // prefix
self.sm.push(""); // amountAndTail
self.emit_op(StackOp::Nip); // drop prefix
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(8)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into())); // [amount(8), tail(44)]
self.sm.pop();
self.sm.pop();
self.sm.push(""); // amount
self.sm.push(""); // tail
self.emit_op(StackOp::Drop); // drop tail
self.sm.pop();
// --- Stack: [..., stateBytes, amount(8LE)] ---
// Save amount to altstack
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into()));
self.sm.pop();
// Bring _codePart to top (PICK — never consume, reused across outputs)
self.bring_to_top("_codePart", false);
// --- Stack: [..., stateBytes, codePart] ---
// Append OP_RETURN + stateBytes
self.emit_op(StackOp::Push(PushValue::Bytes(vec![0x6a])));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
// --- Stack: [..., stateBytes, codePart+OP_RETURN] ---
self.emit_op(StackOp::Swap);
self.sm.swap();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
// --- Stack: [..., codePart+OP_RETURN+stateBytes] ---
// Compute varint prefix for script length
self.emit_op(StackOp::Opcode("OP_SIZE".into()));
self.sm.push("");
self.emit_varint_encoding();
// Prepend varint to script
self.emit_op(StackOp::Swap);
self.sm.swap();
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.push("");
// Prepend amount from altstack
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
self.sm.push("");
self.emit_op(StackOp::Swap);
self.sm.swap();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
// Hash with SHA256d
self.emit_op(StackOp::Opcode("OP_HASH256".into()));
self.sm.pop();
self.sm.push(binding_name);
self.track_depth();
}
/// `computeStateOutput(preimage, stateBytes, newAmount)` — builds the continuation
/// output using _newAmount and _codePart instead of extracting from preimage.
/// Returns raw output bytes WITHOUT the final OP_HASH256.
fn lower_compute_state_output(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &std::collections::HashMap<String, usize>,
) {
let preimage_ref = &args[0];
let state_bytes_ref = &args[1];
let new_amount_ref = &args[2];
// Consume preimage ref (no longer needed — we use _codePart and _newAmount).
let pre_last = self.is_last_use(preimage_ref, binding_index, last_uses);
self.bring_to_top(preimage_ref, pre_last);
self.emit_op(StackOp::Drop);
self.sm.pop();
// Step 1: Convert _newAmount to 8-byte LE and save to altstack.
let amount_last = self.is_last_use(new_amount_ref, binding_index, last_uses);
self.bring_to_top(new_amount_ref, amount_last);
self.emit_op(StackOp::Push(PushValue::Int(8)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into()));
self.sm.pop();
// Step 2: Bring stateBytes to stack.
let sb_last = self.is_last_use(state_bytes_ref, binding_index, last_uses);
self.bring_to_top(state_bytes_ref, sb_last);
// Step 3: Bring _codePart to top (PICK — never consume, reused across outputs)
self.bring_to_top("_codePart", false);
// --- Stack: [..., stateBytes, codePart] ---
// Step 4: Append OP_RETURN + stateBytes
self.emit_op(StackOp::Push(PushValue::Bytes(vec![0x6a])));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
// --- Stack: [..., stateBytes, codePart+OP_RETURN] ---
self.emit_op(StackOp::Swap);
self.sm.swap();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
// --- Stack: [..., codePart+OP_RETURN+stateBytes] ---
// Step 5: Compute varint prefix for script length
self.emit_op(StackOp::Opcode("OP_SIZE".into()));
self.sm.push("");
self.emit_varint_encoding();
// Step 6: Prepend varint to script
self.emit_op(StackOp::Swap);
self.sm.swap();
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.push("");
// Step 7: Prepend _newAmount (8-byte LE) from altstack.
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
self.sm.push("");
self.emit_op(StackOp::Swap);
self.sm.swap();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
// --- Stack: [..., fullOutputSerialization] --- (NO hash)
self.sm.pop();
self.sm.push(binding_name);
self.track_depth();
}
/// `buildChangeOutput(pkh, amount)` — builds a P2PKH output serialization:
/// amount(8LE) + 0x19 + 76a914 <pkh:20bytes> 88ac
/// Total: 34 bytes (8 + 1 + 25).
fn lower_build_change_output(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &std::collections::HashMap<String, usize>,
) {
let pkh_ref = &args[0];
let amount_ref = &args[1];
// Step 1: Build the P2PKH locking script with length prefix.
// Push prefix: varint(25) + OP_DUP + OP_HASH160 + OP_PUSHBYTES_20 = 0x1976a914
self.emit_op(StackOp::Push(PushValue::Bytes(vec![0x19, 0x76, 0xa9, 0x14])));
self.sm.push("");
// Push the 20-byte PKH
let pkh_last = self.is_last_use(pkh_ref, binding_index, last_uses);
self.bring_to_top(pkh_ref, pkh_last);
// CAT: prefix || pkh
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
// Push suffix: OP_EQUALVERIFY + OP_CHECKSIG = 0x88ac
self.emit_op(StackOp::Push(PushValue::Bytes(vec![0x88, 0xac])));
self.sm.push("");
// CAT: (prefix || pkh) || suffix
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
// --- Stack: [..., 0x1976a914{pkh}88ac] ---
// Step 2: Prepend amount as 8-byte LE.
let amount_last = self.is_last_use(amount_ref, binding_index, last_uses);
self.bring_to_top(amount_ref, amount_last);
self.emit_op(StackOp::Push(PushValue::Int(8)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".into()));
self.sm.pop(); // pop width
// Stack: [..., script, amount(8LE)]
self.emit_op(StackOp::Swap);
self.sm.swap();
// Stack: [..., amount(8LE), script]
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
// --- Stack: [..., amount(8LE)+0x1976a914{pkh}88ac] ---
self.sm.pop();
self.sm.push(binding_name);
self.track_depth();
}
fn lower_add_output(
&mut self,
binding_name: &str,
satoshis: &str,
state_values: &[String],
_preimage: &str,
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
// Build a full BIP-143 output serialization:
// amount(8LE) + varint(scriptLen) + codePart + OP_RETURN + stateBytes
// Uses _codePart implicit parameter (passed by SDK) instead of extracting
// codePart from the preimage. This is simpler and works with OP_CODESEPARATOR.
let state_props: Vec<ANFProperty> = self
.properties
.iter()
.filter(|p| !p.readonly)
.cloned()
.collect();
// Step 1: Bring _codePart to top (PICK — never consume, reused across outputs)
self.bring_to_top("_codePart", false);
// --- Stack: [..., codePart] ---
// Step 2: Append OP_RETURN byte (0x6a).
self.emit_op(StackOp::Push(PushValue::Bytes(vec![0x6a])));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
// --- Stack: [..., codePart+OP_RETURN] ---
// Step 3: Serialize each state value and concatenate.
for (i, value_ref) in state_values.iter().enumerate() {
if i >= state_props.len() {
break;
}
let prop = &state_props[i];
let is_last = self.is_last_use(value_ref, binding_index, last_uses);
self.bring_to_top(value_ref, is_last);
if prop.prop_type == "bigint" {
self.emit_op(StackOp::Push(PushValue::Int(8)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".to_string()));
self.sm.pop();
} else if prop.prop_type == "boolean" {
self.emit_op(StackOp::Push(PushValue::Int(1)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".to_string()));
self.sm.pop();
} else if prop.prop_type == "ByteString" {
// Prepend push-data length prefix (matching SDK format)
self.emit_push_data_encode();
}
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".to_string()));
self.sm.push("");
}
// --- Stack: [..., codePart+OP_RETURN+stateBytes] ---
// Step 4: Compute varint prefix for the full script length.
self.emit_op(StackOp::Opcode("OP_SIZE".into())); // [script, len]
self.sm.push("");
self.emit_varint_encoding();
// --- Stack: [..., script, varint] ---
// Step 5: Prepend varint to script: SWAP CAT
self.emit_op(StackOp::Swap);
self.sm.swap();
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.push("");
// --- Stack: [..., varint+script] ---
// Step 6: Prepend satoshis as 8-byte LE.
let is_last_satoshis = self.is_last_use(satoshis, binding_index, last_uses);
self.bring_to_top(satoshis, is_last_satoshis);
self.emit_op(StackOp::Push(PushValue::Int(8)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".to_string()));
self.sm.pop(); // pop the width
// Stack: [..., varint+script, satoshis(8LE)]
self.emit_op(StackOp::Swap);
self.sm.swap();
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".to_string())); // satoshis || varint+script
self.sm.push("");
// --- Stack: [..., amount(8LE)+varint+scriptPubKey] ---
// Rename top to binding name
self.sm.pop();
self.sm.push(binding_name);
self.track_depth();
}
/// `add_raw_output(satoshis, scriptBytes)` — builds a raw output serialization:
/// amount(8LE) + varint(scriptLen) + scriptBytes
/// The scriptBytes are used as-is (no codePart/state insertion).
fn lower_add_raw_output(
&mut self,
binding_name: &str,
satoshis: &str,
script_bytes: &str,
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
// Step 1: Bring scriptBytes to top
let script_is_last = self.is_last_use(script_bytes, binding_index, last_uses);
self.bring_to_top(script_bytes, script_is_last);
// Step 2: Compute varint prefix for script length
self.emit_op(StackOp::Opcode("OP_SIZE".to_string())); // [script, len]
self.sm.push("");
self.emit_varint_encoding();
// --- Stack: [..., script, varint] ---
// Step 3: Prepend varint to script: SWAP CAT
self.emit_op(StackOp::Swap); // [varint, script]
self.sm.swap();
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".to_string())); // [varint+script]
self.sm.push("");
// Step 4: Prepend satoshis as 8-byte LE
let sat_is_last = self.is_last_use(satoshis, binding_index, last_uses);
self.bring_to_top(satoshis, sat_is_last);
self.emit_op(StackOp::Push(PushValue::Int(8)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_NUM2BIN".to_string()));
self.sm.pop(); // pop width
// Stack: [..., varint+script, satoshis(8LE)]
self.emit_op(StackOp::Swap);
self.sm.swap();
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_CAT".to_string())); // satoshis || varint+script
self.sm.push("");
// Rename top to binding name
self.sm.pop();
self.sm.push(binding_name);
self.track_depth();
}
fn lower_array_literal(
&mut self,
binding_name: &str,
elements: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
// An array_literal brings each element to the top of the stack.
// The elements remain as individual stack entries; the binding name tracks
// the last element so that callers (e.g. checkMultiSig) can find them.
for elem in elements {
let is_last = self.is_last_use(elem, binding_index, last_uses);
self.bring_to_top(elem, is_last);
self.sm.pop();
self.sm.push(""); // anonymous stack entry for intermediate elements
}
// Rename the topmost entry to the binding name
if !elements.is_empty() {
self.sm.pop();
}
self.sm.push(binding_name);
self.track_depth();
}
fn lower_check_multi_sig(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
// checkMultiSig(sigs, pks) — emits the OP_CHECKMULTISIG sequence.
// Bitcoin Script stack layout:
// OP_0 <sig1> ... <sigN> <nSigs> <pk1> ... <pkM> <nPKs> OP_CHECKMULTISIG
//
// The two args reference array_literal bindings whose individual elements
// are already on the stack.
// Push OP_0 dummy (Bitcoin CHECKMULTISIG off-by-one bug workaround)
self.emit_op(StackOp::Push(PushValue::Int(0)));
self.sm.push("");
// Bring sigs array ref to top
let sigs_is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], sigs_is_last);
// Bring pks array ref to top
let pks_is_last = self.is_last_use(&args[1], binding_index, last_uses);
self.bring_to_top(&args[1], pks_is_last);
// Pop all args + dummy
self.sm.pop(); // pks
self.sm.pop(); // sigs
self.sm.pop(); // OP_0 dummy
self.emit_op(StackOp::Opcode("OP_CHECKMULTISIG".to_string()));
self.sm.push(binding_name);
self.track_depth();
}
fn lower_check_preimage(
&mut self,
binding_name: &str,
preimage: &str,
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
// OP_PUSH_TX: verify the sighash preimage matches the current spending
// transaction. See https://wiki.bitcoinsv.io/index.php/OP_PUSH_TX
//
// The technique uses a well-known ECDSA keypair where private key = 1
// (so the public key is the secp256k1 generator point G, compressed:
// 0279BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798).
//
// At spending time the SDK must:
// 1. Serialise the BIP-143 sighash preimage for the current input.
// 2. Compute sighash = SHA256(SHA256(preimage)).
// 3. Derive an ECDSA signature (r, s) with privkey = 1:
// r = Gx (x-coordinate of the generator point, constant)
// s = (sighash + r) mod n
// 4. DER-encode (r, s) and append the SIGHASH_ALL|FORKID byte (0x41).
// 5. Push <sig> <preimage> (plus any other method args) as the
// unlocking script.
//
// The locking script sequence:
// [bring preimage to top] -- via PICK or ROLL
// [bring _opPushTxSig to top] -- via ROLL (consuming)
// <G> -- push compressed generator point
// OP_CHECKSIG -- verify sig over SHA256(SHA256(preimage))
// OP_VERIFY -- abort if invalid
// -- preimage remains on stack for field extractors
//
// Stack map trace:
// After bring_to_top(preimage): [..., preimage]
// After bring_to_top(sig, true): [..., preimage, _opPushTxSig]
// After push G: [..., preimage, _opPushTxSig, null(G)]
// After OP_CHECKSIG: [..., preimage, null(result)]
// After OP_VERIFY: [..., preimage]
// Step 0: Emit OP_CODESEPARATOR so that the scriptCode in the BIP-143
// preimage is only the code after this point. This reduces preimage size
// for large scripts and is required for scripts > ~32KB.
self.emit_op(StackOp::Opcode("OP_CODESEPARATOR".to_string()));
// Step 1: Bring preimage to top.
let is_last = self.is_last_use(preimage, binding_index, last_uses);
self.bring_to_top(preimage, is_last);
// Step 2: Bring the implicit _opPushTxSig to top (consuming).
self.bring_to_top("_opPushTxSig", true);
// Step 3: Push compressed secp256k1 generator point G (33 bytes).
let g: Vec<u8> = vec![
0x02, 0x79, 0xBE, 0x66, 0x7E, 0xF9, 0xDC, 0xBB,
0xAC, 0x55, 0xA0, 0x62, 0x95, 0xCE, 0x87, 0x0B,
0x07, 0x02, 0x9B, 0xFC, 0xDB, 0x2D, 0xCE, 0x28,
0xD9, 0x59, 0xF2, 0x81, 0x5B, 0x16, 0xF8, 0x17,
0x98,
];
self.emit_op(StackOp::Push(PushValue::Bytes(g)));
self.sm.push(""); // G on stack
// Step 4: OP_CHECKSIG -- pops pubkey (G) and sig, pushes boolean result.
self.emit_op(StackOp::Opcode("OP_CHECKSIG".to_string()));
self.sm.pop(); // G consumed
self.sm.pop(); // _opPushTxSig consumed
self.sm.push(""); // boolean result
// Step 5: OP_VERIFY -- abort if false, removes result from stack.
self.emit_op(StackOp::Opcode("OP_VERIFY".to_string()));
self.sm.pop(); // result consumed
// The preimage is now on top (from Step 1). Rename to binding name
// so field extractors can reference it.
self.sm.pop();
self.sm.push(binding_name);
self.track_depth();
}
/// Lower `deserialize_state(preimage)` — extracts mutable property values
/// from the BIP-143 preimage's scriptCode field. The state is stored as the
/// last `stateLen` bytes of the scriptCode (after OP_RETURN).
///
/// For each mutable property, the value is extracted, converted to the
/// correct type (BIN2NUM for bigint/boolean), and pushed onto the stack
/// with the property name in the stackMap. This allows `load_prop` to
/// find the deserialized values instead of using hardcoded initial values.
fn lower_deserialize_state(
&mut self,
preimage_ref: &str,
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
let mut prop_names: Vec<String> = Vec::new();
let mut prop_types: Vec<String> = Vec::new();
let mut prop_sizes: Vec<i128> = Vec::new();
let mut has_variable_length = false;
for p in &self.properties {
if p.readonly {
continue;
}
prop_names.push(p.name.clone());
prop_types.push(p.prop_type.clone());
let sz: i128 = match p.prop_type.as_str() {
"bigint" => 8,
"boolean" => 1,
"PubKey" => 33,
"Addr" => 20,
"Sha256" => 32,
"Point" => 64,
"ByteString" => { has_variable_length = true; -1 },
_ => panic!("deserialize_state: unsupported type: {}", p.prop_type),
};
prop_sizes.push(sz);
}
if prop_names.is_empty() {
return;
}
let is_last = self.is_last_use(preimage_ref, binding_index, last_uses);
self.bring_to_top(preimage_ref, is_last);
// 1. Skip first 104 bytes (header), drop prefix.
self.emit_op(StackOp::Push(PushValue::Int(104)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop(); self.sm.pop();
self.sm.push("");
// 2. Drop tail 44 bytes.
self.emit_op(StackOp::Opcode("OP_SIZE".to_string()));
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(44)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SUB".to_string()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
// 3. Drop amount (last 8 bytes).
self.emit_op(StackOp::Opcode("OP_SIZE".to_string()));
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(8)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SUB".to_string()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
if !has_variable_length {
let state_len: i128 = prop_sizes.iter().sum();
// 4. Extract last stateLen bytes.
self.emit_op(StackOp::Opcode("OP_SIZE".to_string()));
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(state_len)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SUB".to_string()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop(); self.sm.pop();
self.sm.push("");
// 5. Split fixed-size state fields.
self.split_fixed_state_fields(&prop_names, &prop_types, &prop_sizes);
} else if !self.sm.has("_codePart") {
// Variable-length state but _codePart not available (terminal method).
self.emit_op(StackOp::Drop);
self.sm.pop();
} else {
// Variable-length path: strip varint, use _codePart to find state
self.emit_op(StackOp::Push(PushValue::Int(1)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Swap);
self.sm.swap();
self.emit_op(StackOp::Dup);
self.sm.push("");
// Zero-pad before BIN2NUM to prevent sign-bit misinterpretation (0xfd → -125 without pad)
self.emit_op(StackOp::Push(PushValue::Bytes(vec![0])));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_BIN2NUM".into()));
self.emit_op(StackOp::Push(PushValue::Int(253)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_LESSTHAN".into()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_IF".into()));
self.sm.pop();
let sm_at_varint_if = self.sm.clone();
self.emit_op(StackOp::Drop);
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_ELSE".into()));
self.sm = sm_at_varint_if.clone();
self.emit_op(StackOp::Drop);
self.sm.pop();
self.emit_op(StackOp::Push(PushValue::Int(2)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_ENDIF".into()));
// Compute skip = SIZE(_codePart) - codeSepIdx
self.bring_to_top("_codePart", false);
self.emit_op(StackOp::Opcode("OP_SIZE".into()));
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop(); self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::PushCodeSepIndex);
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SUB".into()));
self.sm.pop(); self.sm.pop();
self.sm.push("");
// Split scriptCode at skip to get state
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop(); self.sm.pop();
self.sm.push("");
// Parse variable-length state fields
self.parse_variable_length_state_fields(&prop_names, &prop_types, &prop_sizes);
}
self.track_depth();
}
fn split_fixed_state_fields(
&mut self,
prop_names: &[String],
prop_types: &[String],
prop_sizes: &[i128],
) {
let num_props = prop_names.len();
if num_props == 1 {
if prop_types[0] == "bigint" || prop_types[0] == "boolean" {
self.emit_op(StackOp::Opcode("OP_BIN2NUM".to_string()));
}
self.sm.pop();
self.sm.push(&prop_names[0]);
} else {
for i in 0..num_props {
let sz = prop_sizes[i];
if i < num_props - 1 {
self.emit_op(StackOp::Push(PushValue::Int(sz)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Swap);
self.sm.swap();
if prop_types[i] == "bigint" || prop_types[i] == "boolean" {
self.emit_op(StackOp::Opcode("OP_BIN2NUM".to_string()));
}
self.emit_op(StackOp::Swap);
self.sm.swap();
self.sm.pop(); self.sm.pop();
self.sm.push(&prop_names[i]);
self.sm.push("");
} else {
if prop_types[i] == "bigint" || prop_types[i] == "boolean" {
self.emit_op(StackOp::Opcode("OP_BIN2NUM".to_string()));
}
self.sm.pop();
self.sm.push(&prop_names[i]);
}
}
}
}
fn parse_variable_length_state_fields(
&mut self,
prop_names: &[String],
prop_types: &[String],
prop_sizes: &[i128],
) {
let num_props = prop_names.len();
if num_props == 1 {
if prop_types[0] == "ByteString" {
// Single ByteString field: decode push-data prefix, drop trailing empty
self.emit_push_data_decode(); // [..., data, remaining]
self.emit_op(StackOp::Drop); self.sm.pop();
} else if prop_types[0] == "bigint" || prop_types[0] == "boolean" {
self.emit_op(StackOp::Opcode("OP_BIN2NUM".into()));
}
self.sm.pop();
self.sm.push(&prop_names[0]);
} else {
for i in 0..num_props {
if i < num_props - 1 {
if prop_types[i] == "ByteString" {
// ByteString: decode push-data prefix, extract data
self.emit_push_data_decode(); // [..., data, rest]
self.sm.pop(); self.sm.pop();
self.sm.push(&prop_names[i]);
self.sm.push(""); // rest on top
} else {
self.emit_op(StackOp::Push(PushValue::Int(prop_sizes[i])));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.sm.pop(); self.sm.pop();
self.sm.push(""); self.sm.push("");
self.emit_op(StackOp::Swap); self.sm.swap();
if prop_types[i] == "bigint" || prop_types[i] == "boolean" {
self.emit_op(StackOp::Opcode("OP_BIN2NUM".into()));
}
self.emit_op(StackOp::Swap); self.sm.swap();
self.sm.pop(); self.sm.pop();
self.sm.push(&prop_names[i]);
self.sm.push("");
}
} else {
if prop_types[i] == "ByteString" {
// Last ByteString: decode push-data prefix, drop trailing empty
self.emit_push_data_decode(); // [..., data, remaining]
self.emit_op(StackOp::Drop); self.sm.pop();
} else if prop_types[i] == "bigint" || prop_types[i] == "boolean" {
self.emit_op(StackOp::Opcode("OP_BIN2NUM".into()));
}
self.sm.pop();
self.sm.push(&prop_names[i]);
}
}
}
}
/// Lower a preimage field extractor call.
///
/// The SigHashPreimage follows BIP-143 format:
/// Offset Bytes Field
/// 0 4 nVersion (LE uint32)
/// 4 32 hashPrevouts
/// 36 32 hashSequence
/// 68 36 outpoint (txid 32 + vout 4)
/// 104 var scriptCode (varint-prefixed)
/// var 8 amount (satoshis, LE int64)
/// var 4 nSequence
/// var 32 hashOutputs
/// var 4 nLocktime
/// var 4 sighashType
///
/// Fixed-offset fields use absolute OP_SPLIT positions.
/// Variable-offset fields use end-relative positions via OP_SIZE.
fn lower_extractor(
&mut self,
binding_name: &str,
func_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(!args.is_empty(), "{} requires 1 argument", func_name);
let is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], is_last);
// The preimage is now on top of the stack.
self.sm.pop(); // consume the preimage from stack map
match func_name {
"extractVersion" => {
// <preimage> 4 OP_SPLIT OP_DROP OP_BIN2NUM
self.emit_op(StackOp::Push(PushValue::Int(4)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_BIN2NUM".to_string()));
}
"extractHashPrevouts" => {
// <preimage> 4 OP_SPLIT OP_NIP 32 OP_SPLIT OP_DROP
self.emit_op(StackOp::Push(PushValue::Int(4)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(32)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); // pop position (32)
self.sm.pop(); // pop data being split
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
}
"extractHashSequence" => {
// <preimage> 36 OP_SPLIT OP_NIP 32 OP_SPLIT OP_DROP
self.emit_op(StackOp::Push(PushValue::Int(36)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(32)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); // pop position (32)
self.sm.pop(); // pop data being split
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
}
"extractOutpoint" => {
// <preimage> 68 OP_SPLIT OP_NIP 36 OP_SPLIT OP_DROP
self.emit_op(StackOp::Push(PushValue::Int(68)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(36)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); // pop position (36)
self.sm.pop(); // pop data being split
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
}
"extractSigHashType" => {
// End-relative: last 4 bytes, converted to number.
// <preimage> OP_SIZE 4 OP_SUB OP_SPLIT OP_NIP OP_BIN2NUM
self.emit_op(StackOp::Opcode("OP_SIZE".to_string()));
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(4)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SUB".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_BIN2NUM".to_string()));
}
"extractLocktime" => {
// End-relative: 4 bytes before the last 4 (sighashType).
// <preimage> OP_SIZE 8 OP_SUB OP_SPLIT OP_NIP 4 OP_SPLIT OP_DROP OP_BIN2NUM
self.emit_op(StackOp::Opcode("OP_SIZE".to_string()));
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(8)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SUB".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(4)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); // pop position (4)
self.sm.pop(); // pop value being split
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_BIN2NUM".to_string()));
}
"extractOutputHash" | "extractOutputs" => {
// End-relative: 32 bytes before the last 8 (nLocktime 4 + sighashType 4).
// <preimage> OP_SIZE 40 OP_SUB OP_SPLIT OP_NIP 32 OP_SPLIT OP_DROP
self.emit_op(StackOp::Opcode("OP_SIZE".to_string()));
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(40)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SUB".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(32)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); // pop position (32)
self.sm.pop(); // pop value being split (last40)
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
}
"extractAmount" => {
// End-relative: 8 bytes at offset -(52) from end.
// <preimage> OP_SIZE 52 OP_SUB OP_SPLIT OP_NIP 8 OP_SPLIT OP_DROP OP_BIN2NUM
self.emit_op(StackOp::Opcode("OP_SIZE".to_string()));
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(52)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SUB".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(8)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); // pop position (8)
self.sm.pop(); // pop value being split
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_BIN2NUM".to_string()));
}
"extractSequence" => {
// End-relative: 4 bytes (nSequence) at offset -(44) from end.
// <preimage> OP_SIZE 44 OP_SUB OP_SPLIT OP_NIP 4 OP_SPLIT OP_DROP OP_BIN2NUM
self.emit_op(StackOp::Opcode("OP_SIZE".to_string()));
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(44)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SUB".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(4)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); // pop position (4)
self.sm.pop(); // pop value being split
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_BIN2NUM".to_string()));
}
"extractScriptCode" => {
// Variable-length field at offset 104. End-relative tail = 52 bytes.
// <preimage> 104 OP_SPLIT OP_NIP OP_SIZE 52 OP_SUB OP_SPLIT OP_DROP
self.emit_op(StackOp::Push(PushValue::Int(104)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SIZE".to_string()));
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(52)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SUB".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
}
"extractInputIndex" => {
// Input index = vout field of outpoint, at offset 100, 4 bytes.
// <preimage> 100 OP_SPLIT OP_NIP 4 OP_SPLIT OP_DROP OP_BIN2NUM
self.emit_op(StackOp::Push(PushValue::Int(100)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop();
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop();
self.sm.pop();
self.sm.push("");
self.emit_op(StackOp::Push(PushValue::Int(4)));
self.sm.push("");
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.pop(); // pop position (4)
self.sm.pop(); // pop value being split
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_BIN2NUM".to_string()));
}
_ => panic!("unknown extractor: {}", func_name),
}
// Rename top of stack to the binding name
self.sm.pop();
self.sm.push(binding_name);
self.track_depth();
}
/// Lower `__array_access(data, index)` — ByteString byte-level indexing.
///
/// Compiled to:
/// `<data> <index> OP_SPLIT OP_NIP 1 OP_SPLIT OP_DROP OP_BIN2NUM`
///
/// Stack trace:
/// `[..., data, index]`
/// `OP_SPLIT → [..., left, right]` (split at index)
/// `OP_NIP → [..., right]` (discard left)
/// `push 1 → [..., right, 1]`
/// `OP_SPLIT → [..., firstByte, rest]` (split off first byte)
/// `OP_DROP → [..., firstByte]` (discard rest)
/// `OP_BIN2NUM → [..., numericValue]` (convert byte to bigint)
fn lower_array_access(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 2, "__array_access requires 2 arguments (object, index)");
let obj = &args[0];
let index = &args[1];
// Push the data (ByteString) onto the stack
let obj_is_last = self.is_last_use(obj, binding_index, last_uses);
self.bring_to_top(obj, obj_is_last);
// Push the index onto the stack
let index_is_last = self.is_last_use(index, binding_index, last_uses);
self.bring_to_top(index, index_is_last);
// OP_SPLIT at index: stack = [..., left, right]
self.sm.pop(); // index consumed
self.sm.pop(); // data consumed
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.push(""); // left part (discard)
self.sm.push(""); // right part (keep)
// OP_NIP: discard left, keep right: stack = [..., right]
self.emit_op(StackOp::Nip);
self.sm.pop();
let right_part = self.sm.pop();
self.sm.push(&right_part);
// Push 1 for the next split (extract 1 byte)
self.emit_op(StackOp::Push(PushValue::Int(1)));
self.sm.push("");
// OP_SPLIT: split off first byte: stack = [..., firstByte, rest]
self.sm.pop(); // 1 consumed
self.sm.pop(); // right consumed
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.push(""); // first byte (keep)
self.sm.push(""); // rest (discard)
// OP_DROP: discard rest: stack = [..., firstByte]
self.emit_op(StackOp::Drop);
self.sm.pop();
self.sm.pop();
self.sm.push("");
// OP_BIN2NUM: convert single byte to numeric value
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_BIN2NUM".to_string()));
self.sm.push(binding_name);
self.track_depth();
}
fn lower_reverse_bytes(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(!args.is_empty(), "reverseBytes requires 1 argument");
let is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], is_last);
// Variable-length byte reversal using bounded unrolled loop.
// Each iteration peels off the first byte and prepends it to the result.
// 520 iterations covers the maximum BSV element size.
self.sm.pop();
// Push empty result (OP_0), swap so data is on top
self.emit_op(StackOp::Push(PushValue::Int(0)));
self.emit_op(StackOp::Swap);
// 520 iterations (max BSV element size)
for _ in 0..520 {
// Stack: [result, data]
self.emit_op(StackOp::Opcode("OP_DUP".to_string()));
self.emit_op(StackOp::Opcode("OP_SIZE".to_string()));
self.emit_op(StackOp::Nip);
self.emit_op(StackOp::If {
then_ops: vec![
StackOp::Push(PushValue::Int(1)),
StackOp::Opcode("OP_SPLIT".to_string()),
StackOp::Swap,
StackOp::Rot,
StackOp::Opcode("OP_CAT".to_string()),
StackOp::Swap,
],
else_ops: vec![],
});
}
// Drop empty remainder
self.emit_op(StackOp::Drop);
self.sm.push(binding_name);
self.track_depth();
}
fn lower_substr(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 3, "substr requires 3 arguments");
let data = &args[0];
let start = &args[1];
let length = &args[2];
let data_is_last = self.is_last_use(data, binding_index, last_uses);
self.bring_to_top(data, data_is_last);
let start_is_last = self.is_last_use(start, binding_index, last_uses);
self.bring_to_top(start, start_is_last);
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Nip);
self.sm.pop();
let right_part = self.sm.pop();
self.sm.push(&right_part);
let len_is_last = self.is_last_use(length, binding_index, last_uses);
self.bring_to_top(length, len_is_last);
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string()));
self.sm.push("");
self.sm.push("");
self.emit_op(StackOp::Drop);
self.sm.pop();
self.sm.pop();
self.sm.push(binding_name);
self.track_depth();
}
fn lower_verify_rabin_sig(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 4, "verifyRabinSig requires 4 arguments");
// Stack input: <msg> <sig> <padding> <pubKey>
// Computation: (sig^2 + padding) mod pubKey == SHA256(msg)
// Opcode sequence: OP_SWAP OP_ROT OP_DUP OP_MUL OP_ADD OP_SWAP OP_MOD OP_SWAP OP_SHA256 OP_EQUAL
let msg = &args[0];
let sig = &args[1];
let padding = &args[2];
let pub_key = &args[3];
let msg_is_last = self.is_last_use(msg, binding_index, last_uses);
self.bring_to_top(msg, msg_is_last);
let sig_is_last = self.is_last_use(sig, binding_index, last_uses);
self.bring_to_top(sig, sig_is_last);
let padding_is_last = self.is_last_use(padding, binding_index, last_uses);
self.bring_to_top(padding, padding_is_last);
let pub_key_is_last = self.is_last_use(pub_key, binding_index, last_uses);
self.bring_to_top(pub_key, pub_key_is_last);
// Pop all 4 args from stack map
self.sm.pop();
self.sm.pop();
self.sm.pop();
self.sm.pop();
// Emit the Rabin signature verification opcode sequence
// Stack: msg(3) sig(2) padding(1) pubKey(0)
self.emit_op(StackOp::Opcode("OP_SWAP".to_string())); // msg sig pubKey padding
self.emit_op(StackOp::Opcode("OP_ROT".to_string())); // msg pubKey padding sig
self.emit_op(StackOp::Opcode("OP_DUP".to_string()));
self.emit_op(StackOp::Opcode("OP_MUL".to_string())); // msg pubKey padding sig^2
self.emit_op(StackOp::Opcode("OP_ADD".to_string())); // msg pubKey (sig^2+padding)
self.emit_op(StackOp::Opcode("OP_SWAP".to_string())); // msg (sig^2+padding) pubKey
self.emit_op(StackOp::Opcode("OP_MOD".to_string())); // msg ((sig^2+padding) mod pubKey)
self.emit_op(StackOp::Opcode("OP_SWAP".to_string())); // ((sig^2+padding) mod pubKey) msg
self.emit_op(StackOp::Opcode("OP_SHA256".to_string()));
self.emit_op(StackOp::Opcode("OP_EQUAL".to_string()));
self.sm.push(binding_name);
self.track_depth();
}
/// Lower sign(x) to Script that avoids division by zero for x == 0.
/// OP_DUP OP_IF OP_DUP OP_ABS OP_SWAP OP_DIV OP_ENDIF
fn lower_sign(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(!args.is_empty(), "sign requires 1 argument");
let x = &args[0];
let x_is_last = self.is_last_use(x, binding_index, last_uses);
self.bring_to_top(x, x_is_last);
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_DUP".to_string()));
self.emit_op(StackOp::If {
then_ops: vec![
StackOp::Opcode("OP_DUP".to_string()),
StackOp::Opcode("OP_ABS".to_string()),
StackOp::Swap,
StackOp::Opcode("OP_DIV".to_string()),
],
else_ops: vec![],
});
self.sm.push(binding_name);
self.track_depth();
}
/// Lower right(data, len) to Script.
/// OP_SWAP OP_SIZE OP_ROT OP_SUB OP_SPLIT OP_NIP
fn lower_right(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 2, "right requires 2 arguments");
let data = &args[0];
let length = &args[1];
let data_is_last = self.is_last_use(data, binding_index, last_uses);
self.bring_to_top(data, data_is_last);
let length_is_last = self.is_last_use(length, binding_index, last_uses);
self.bring_to_top(length, length_is_last);
self.sm.pop(); // len
self.sm.pop(); // data
self.emit_op(StackOp::Swap); // <len> <data>
self.emit_op(StackOp::Opcode("OP_SIZE".to_string())); // <len> <data> <size>
self.emit_op(StackOp::Rot); // <data> <size> <len>
self.emit_op(StackOp::Opcode("OP_SUB".to_string())); // <data> <size-len>
self.emit_op(StackOp::Opcode("OP_SPLIT".to_string())); // <left> <right>
self.emit_op(StackOp::Nip); // <right>
self.sm.push(binding_name);
self.track_depth();
}
/// Emit one WOTS+ chain with RFC 8391 tweakable hash.
/// Stack entry: pubSeed(bottom) sig csum endpt digit(top)
/// Stack exit: pubSeed(bottom) sigRest newCsum newEndpt
fn emit_wots_one_chain(&mut self, chain_index: usize) {
// Save steps_copy = 15 - digit to alt (for checksum accumulation later)
self.emit_op(StackOp::Opcode("OP_DUP".into()));
self.emit_op(StackOp::Push(PushValue::Int(15)));
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Opcode("OP_SUB".into()));
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into())); // push#1: steps_copy
// Save endpt, csum to alt. Leave pubSeed+sig+digit on main.
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into())); // push#2: endpt
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into())); // push#3: csum
// main: pubSeed sig digit
// Split 32B sig element
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Push(PushValue::Int(32)));
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into())); // push#4: sigRest
self.emit_op(StackOp::Swap);
// main: pubSeed sigElem digit
// Hash loop: skip first `digit` iterations, then apply F for the rest.
// When digit > 0: decrement (skip). When digit == 0: hash at step j.
// Stack: pubSeed(depth2) sigElem(depth1) digit(depth0=top)
for j in 0..15usize {
let adrs_bytes = vec![chain_index as u8, j as u8];
self.emit_op(StackOp::Opcode("OP_DUP".into()));
self.emit_op(StackOp::Opcode("OP_0NOTEQUAL".into()));
self.emit_op(StackOp::If {
then_ops: vec![
StackOp::Opcode("OP_1SUB".into()), // skip: digit--
],
else_ops: vec![
StackOp::Swap, // pubSeed digit X
StackOp::Push(PushValue::Int(2)),
StackOp::Opcode("OP_PICK".into()), // copy pubSeed
StackOp::Push(PushValue::Bytes(adrs_bytes)), // ADRS [chainIndex, j]
StackOp::Opcode("OP_CAT".into()), // pubSeed || adrs
StackOp::Swap, // bring X to top
StackOp::Opcode("OP_CAT".into()), // pubSeed || adrs || X
StackOp::Opcode("OP_SHA256".into()), // F result
StackOp::Swap, // pubSeed new_X digit(=0)
],
});
}
self.emit_op(StackOp::Drop); // drop digit (now 0)
// main: pubSeed endpoint
// Restore from alt (LIFO): sigRest, csum, endpt_acc, steps_copy
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
// csum += steps_copy
self.emit_op(StackOp::Rot);
self.emit_op(StackOp::Opcode("OP_ADD".into()));
// Concat endpoint to endpt_acc
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Push(PushValue::Int(3)));
self.emit_op(StackOp::Opcode("OP_ROLL".into()));
self.emit_op(StackOp::Opcode("OP_CAT".into()));
}
/// WOTS+ signature verification with RFC 8391 tweakable hash (post-quantum).
/// Parameters: w=16, n=32 (SHA-256), len=67 chains.
/// pubkey is 64 bytes: pubSeed(32) || pkRoot(32).
fn lower_verify_wots(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 3, "verifyWOTS requires 3 arguments: msg, sig, pubkey");
for arg in args.iter() {
let is_last = self.is_last_use(arg, binding_index, last_uses);
self.bring_to_top(arg, is_last);
}
for _ in 0..3 { self.sm.pop(); }
// main: msg sig pubkey(64B: pubSeed||pkRoot)
// Split 64-byte pubkey into pubSeed(32) and pkRoot(32)
self.emit_op(StackOp::Push(PushValue::Int(32)));
self.emit_op(StackOp::Opcode("OP_SPLIT".into())); // msg sig pubSeed pkRoot
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into())); // pkRoot → alt
// Rearrange: put pubSeed at bottom, hash msg
self.emit_op(StackOp::Rot); // sig pubSeed msg
self.emit_op(StackOp::Rot); // pubSeed msg sig
self.emit_op(StackOp::Swap); // pubSeed sig msg
self.emit_op(StackOp::Opcode("OP_SHA256".into())); // pubSeed sig msgHash
// Canonical layout: pubSeed(bottom) sig csum=0 endptAcc=empty hashRem(top)
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Push(PushValue::Int(0)));
self.emit_op(StackOp::Opcode("OP_0".into()));
self.emit_op(StackOp::Push(PushValue::Int(3)));
self.emit_op(StackOp::Opcode("OP_ROLL".into()));
// Process 32 bytes → 64 message chains
for byte_idx in 0..32 {
if byte_idx < 31 {
self.emit_op(StackOp::Push(PushValue::Int(1)));
self.emit_op(StackOp::Opcode("OP_SPLIT".into()));
self.emit_op(StackOp::Swap);
}
// Unsigned byte conversion
self.emit_op(StackOp::Push(PushValue::Int(0)));
self.emit_op(StackOp::Push(PushValue::Int(1)));
self.emit_op(StackOp::Opcode("OP_NUM2BIN".into()));
self.emit_op(StackOp::Opcode("OP_CAT".into()));
self.emit_op(StackOp::Opcode("OP_BIN2NUM".into()));
// Extract nibbles
self.emit_op(StackOp::Opcode("OP_DUP".into()));
self.emit_op(StackOp::Push(PushValue::Int(16)));
self.emit_op(StackOp::Opcode("OP_DIV".into()));
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Push(PushValue::Int(16)));
self.emit_op(StackOp::Opcode("OP_MOD".into()));
if byte_idx < 31 {
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into()));
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into()));
} else {
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into()));
}
self.emit_wots_one_chain(byte_idx * 2); // high nibble chain
if byte_idx < 31 {
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into()));
} else {
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
}
self.emit_wots_one_chain(byte_idx * 2 + 1); // low nibble chain
if byte_idx < 31 {
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
}
}
// Checksum digits
self.emit_op(StackOp::Swap);
// d66
self.emit_op(StackOp::Opcode("OP_DUP".into()));
self.emit_op(StackOp::Push(PushValue::Int(16)));
self.emit_op(StackOp::Opcode("OP_MOD".into()));
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into()));
// d65
self.emit_op(StackOp::Opcode("OP_DUP".into()));
self.emit_op(StackOp::Push(PushValue::Int(16)));
self.emit_op(StackOp::Opcode("OP_DIV".into()));
self.emit_op(StackOp::Push(PushValue::Int(16)));
self.emit_op(StackOp::Opcode("OP_MOD".into()));
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into()));
// d64
self.emit_op(StackOp::Push(PushValue::Int(256)));
self.emit_op(StackOp::Opcode("OP_DIV".into()));
self.emit_op(StackOp::Push(PushValue::Int(16)));
self.emit_op(StackOp::Opcode("OP_MOD".into()));
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into()));
// 3 checksum chains (indices 64, 65, 66)
for ci in 0..3 {
self.emit_op(StackOp::Opcode("OP_TOALTSTACK".into()));
self.emit_op(StackOp::Push(PushValue::Int(0)));
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into()));
self.emit_wots_one_chain(64 + ci);
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Drop);
}
// Final comparison
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Drop);
// main: pubSeed endptAcc
self.emit_op(StackOp::Opcode("OP_SHA256".into()));
self.emit_op(StackOp::Opcode("OP_FROMALTSTACK".into())); // pkRoot
self.emit_op(StackOp::Opcode("OP_EQUAL".into()));
// Clean up pubSeed
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Drop);
self.sm.push(binding_name);
self.track_depth();
}
/// SLH-DSA (FIPS 205) signature verification.
/// Brings all 3 args to the top, pops them, delegates to slh_dsa::emit_verify_slh_dsa,
/// and pushes the boolean result.
fn lower_verify_slh_dsa(
&mut self,
binding_name: &str,
param_key: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(
args.len() >= 3,
"verifySLHDSA requires 3 arguments: msg, sig, pubkey"
);
// Bring args to top in order: msg, sig, pubkey
for arg in args.iter() {
let is_last = self.is_last_use(arg, binding_index, last_uses);
self.bring_to_top(arg, is_last);
}
for _ in 0..3 {
self.sm.pop();
}
// Delegate to slh_dsa module
super::slh_dsa::emit_verify_slh_dsa(&mut |op| self.ops.push(op), param_key);
self.sm.push(binding_name);
self.track_depth();
}
// =========================================================================
// SHA-256 compression -- delegates to sha256.rs
// =========================================================================
fn lower_sha256_compress(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(
args.len() >= 2,
"sha256Compress requires 2 arguments: state, block"
);
for arg in args.iter() {
let is_last = self.is_last_use(arg, binding_index, last_uses);
self.bring_to_top(arg, is_last);
}
for _ in 0..2 {
self.sm.pop();
}
super::sha256::emit_sha256_compress(&mut |op| self.ops.push(op));
self.sm.push(binding_name);
self.track_depth();
}
fn lower_sha256_finalize(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(
args.len() >= 3,
"sha256Finalize requires 3 arguments: state, remaining, msgBitLen"
);
for arg in args.iter() {
let is_last = self.is_last_use(arg, binding_index, last_uses);
self.bring_to_top(arg, is_last);
}
for _ in 0..3 {
self.sm.pop();
}
super::sha256::emit_sha256_finalize(&mut |op| self.ops.push(op));
self.sm.push(binding_name);
self.track_depth();
}
fn lower_blake3_compress(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(
args.len() >= 2,
"blake3Compress requires 2 arguments: chainingValue, block"
);
for arg in args.iter() {
let is_last = self.is_last_use(arg, binding_index, last_uses);
self.bring_to_top(arg, is_last);
}
for _ in 0..2 {
self.sm.pop();
}
super::blake3::emit_blake3_compress(&mut |op| self.ops.push(op));
self.sm.push(binding_name);
self.track_depth();
}
fn lower_blake3_hash(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(
args.len() >= 1,
"blake3Hash requires 1 argument: message"
);
for arg in args.iter() {
let is_last = self.is_last_use(arg, binding_index, last_uses);
self.bring_to_top(arg, is_last);
}
for _ in 0..1 {
self.sm.pop();
}
super::blake3::emit_blake3_hash(&mut |op| self.ops.push(op));
self.sm.push(binding_name);
self.track_depth();
}
fn lower_ec_builtin(
&mut self,
binding_name: &str,
func_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
// Bring args to top in order
for arg in args.iter() {
let is_last = self.is_last_use(arg, binding_index, last_uses);
self.bring_to_top(arg, is_last);
}
for _ in args {
self.sm.pop();
}
let emit = &mut |op: StackOp| self.ops.push(op);
match func_name {
"ecAdd" => super::ec::emit_ec_add(emit),
"ecMul" => super::ec::emit_ec_mul(emit),
"ecMulGen" => super::ec::emit_ec_mul_gen(emit),
"ecNegate" => super::ec::emit_ec_negate(emit),
"ecOnCurve" => super::ec::emit_ec_on_curve(emit),
"ecModReduce" => super::ec::emit_ec_mod_reduce(emit),
"ecEncodeCompressed" => super::ec::emit_ec_encode_compressed(emit),
"ecMakePoint" => super::ec::emit_ec_make_point(emit),
"ecPointX" => super::ec::emit_ec_point_x(emit),
"ecPointY" => super::ec::emit_ec_point_y(emit),
_ => panic!("unknown EC builtin: {}", func_name),
}
self.sm.push(binding_name);
self.track_depth();
}
/// safediv(a, b): a / b with division-by-zero check.
/// Stack: a b -> OP_DUP OP_0NOTEQUAL OP_VERIFY OP_DIV -> result
fn lower_safediv(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 2, "safediv requires 2 arguments");
let a_is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], a_is_last);
let b_is_last = self.is_last_use(&args[1], binding_index, last_uses);
self.bring_to_top(&args[1], b_is_last);
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_DUP".to_string()));
self.emit_op(StackOp::Opcode("OP_0NOTEQUAL".to_string()));
self.emit_op(StackOp::Opcode("OP_VERIFY".to_string()));
self.emit_op(StackOp::Opcode("OP_DIV".to_string()));
self.sm.push(binding_name);
self.track_depth();
}
/// safemod(a, b): a % b with division-by-zero check.
/// Stack: a b -> OP_DUP OP_0NOTEQUAL OP_VERIFY OP_MOD -> result
fn lower_safemod(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 2, "safemod requires 2 arguments");
let a_is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], a_is_last);
let b_is_last = self.is_last_use(&args[1], binding_index, last_uses);
self.bring_to_top(&args[1], b_is_last);
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_DUP".to_string()));
self.emit_op(StackOp::Opcode("OP_0NOTEQUAL".to_string()));
self.emit_op(StackOp::Opcode("OP_VERIFY".to_string()));
self.emit_op(StackOp::Opcode("OP_MOD".to_string()));
self.sm.push(binding_name);
self.track_depth();
}
/// clamp(val, lo, hi): clamp val to [lo, hi].
/// Stack: val lo hi -> val lo OP_MAX hi OP_MIN -> result
fn lower_clamp(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 3, "clamp requires 3 arguments");
let val_is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], val_is_last);
let lo_is_last = self.is_last_use(&args[1], binding_index, last_uses);
self.bring_to_top(&args[1], lo_is_last);
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_MAX".to_string()));
self.sm.push(""); // intermediate result
let hi_is_last = self.is_last_use(&args[2], binding_index, last_uses);
self.bring_to_top(&args[2], hi_is_last);
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_MIN".to_string()));
self.sm.push(binding_name);
self.track_depth();
}
/// pow(base, exp): base^exp via 32-iteration bounded conditional multiply.
/// Strategy: swap to get exp base, push 1 (acc), then 32 rounds of:
/// 2 OP_PICK (get exp), push(i+1), OP_GREATERTHAN, OP_IF, OP_OVER, OP_MUL, OP_ENDIF
/// After iterations: OP_NIP OP_NIP to get result.
fn lower_pow(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 2, "pow requires 2 arguments");
let base_is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], base_is_last);
let exp_is_last = self.is_last_use(&args[1], binding_index, last_uses);
self.bring_to_top(&args[1], exp_is_last);
self.sm.pop();
self.sm.pop();
// Stack: base exp
self.emit_op(StackOp::Swap); // exp base
self.emit_op(StackOp::Push(PushValue::Int(1))); // exp base 1(acc)
// Runtime guard: <exp> <MAX> OP_LESSTHANOREQUAL OP_VERIFY.
// Bitcoin Script can't loop, so the iteration count is fixed at
// compile time. Without this guard, `exp > 32` would silently
// saturate at base^32 (issue #34). Script aborts cleanly now.
const MAX_POW_ITERATIONS: i128 = 32;
self.emit_op(StackOp::Push(PushValue::Int(2)));
self.emit_op(StackOp::Opcode("OP_PICK".to_string())); // exp base acc exp
self.emit_op(StackOp::Push(PushValue::Int(MAX_POW_ITERATIONS)));
self.emit_op(StackOp::Opcode("OP_LESSTHANOREQUAL".to_string())); // exp base acc (exp <= MAX)
self.emit_op(StackOp::Opcode("OP_VERIFY".to_string()));
for i in 0..MAX_POW_ITERATIONS {
// Stack: exp base acc
self.emit_op(StackOp::Push(PushValue::Int(2)));
self.emit_op(StackOp::Opcode("OP_PICK".to_string())); // exp base acc exp
self.emit_op(StackOp::Push(PushValue::Int(i)));
self.emit_op(StackOp::Opcode("OP_GREATERTHAN".to_string())); // exp base acc (exp > i)
self.emit_op(StackOp::If {
then_ops: vec![
StackOp::Over, // exp base acc base
StackOp::Opcode("OP_MUL".to_string()), // exp base (acc*base)
],
else_ops: vec![],
});
}
// Stack: exp base result
self.emit_op(StackOp::Nip); // exp result
self.emit_op(StackOp::Nip); // result
self.sm.push(binding_name);
self.track_depth();
}
/// mulDiv(a, b, c): (a * b) / c
/// Stack: a b c -> a b OP_MUL c OP_DIV -> result
fn lower_mul_div(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 3, "mulDiv requires 3 arguments");
let a_is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], a_is_last);
let b_is_last = self.is_last_use(&args[1], binding_index, last_uses);
self.bring_to_top(&args[1], b_is_last);
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_MUL".to_string()));
self.sm.push(""); // a*b
let c_is_last = self.is_last_use(&args[2], binding_index, last_uses);
self.bring_to_top(&args[2], c_is_last);
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_DIV".to_string()));
self.sm.push(binding_name);
self.track_depth();
}
/// percentOf(amount, bps): (amount * bps) / 10000
/// Stack: amount bps -> OP_MUL 10000 OP_DIV -> result
fn lower_percent_of(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 2, "percentOf requires 2 arguments");
let amount_is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], amount_is_last);
let bps_is_last = self.is_last_use(&args[1], binding_index, last_uses);
self.bring_to_top(&args[1], bps_is_last);
self.sm.pop();
self.sm.pop();
self.emit_op(StackOp::Opcode("OP_MUL".to_string()));
self.emit_op(StackOp::Push(PushValue::Int(10000)));
self.emit_op(StackOp::Opcode("OP_DIV".to_string()));
self.sm.push(binding_name);
self.track_depth();
}
/// sqrt(n): integer square root via Newton's method, 16 iterations.
/// Uses: guess = n, then 16x: guess = (guess + n/guess) / 2
/// Guards against n == 0 to avoid division by zero.
fn lower_sqrt(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(!args.is_empty(), "sqrt requires 1 argument");
let n_is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], n_is_last);
self.sm.pop();
// Stack: n
// Guard: if n == 0, skip Newton iteration entirely (result is 0).
self.emit_op(StackOp::Opcode("OP_DUP".to_string()));
// Stack: n n
// Build the Newton iteration ops inside the OP_IF branch
let mut newton_ops = Vec::new();
// Stack inside IF: n (the DUP'd copy was consumed by OP_IF)
// DUP to get initial guess = n
newton_ops.push(StackOp::Opcode("OP_DUP".to_string()));
// Stack: n guess
// 16 iterations of Newton's method: guess = (guess + n/guess) / 2
for _ in 0..16 {
// Stack: n guess
newton_ops.push(StackOp::Over); // n guess n
newton_ops.push(StackOp::Over); // n guess n guess
newton_ops.push(StackOp::Opcode("OP_DIV".to_string())); // n guess (n/guess)
newton_ops.push(StackOp::Opcode("OP_ADD".to_string())); // n (guess + n/guess)
newton_ops.push(StackOp::Push(PushValue::Int(2))); // n (guess + n/guess) 2
newton_ops.push(StackOp::Opcode("OP_DIV".to_string())); // n new_guess
}
// Stack: n guess
// Drop n, keep guess
newton_ops.push(StackOp::Opcode("OP_NIP".to_string()));
self.emit_op(StackOp::If {
then_ops: newton_ops,
else_ops: vec![], // n == 0, result is already 0 on stack
});
self.sm.push(binding_name);
self.track_depth();
}
/// gcd(a, b): Euclidean algorithm, 256 iterations with conditional OP_IF.
/// Each iteration: if b != 0 then (b, a % b) else (a, 0)
fn lower_gcd(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 2, "gcd requires 2 arguments");
let a_is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], a_is_last);
let b_is_last = self.is_last_use(&args[1], binding_index, last_uses);
self.bring_to_top(&args[1], b_is_last);
self.sm.pop();
self.sm.pop();
// Stack: a b
// Both should be absolute values
self.emit_op(StackOp::Opcode("OP_ABS".to_string()));
self.emit_op(StackOp::Swap);
self.emit_op(StackOp::Opcode("OP_ABS".to_string()));
self.emit_op(StackOp::Swap);
// Stack: |a| |b|
// 256 iterations of Euclidean algorithm
for _ in 0..256 {
// Stack: a b
// Check if b != 0
self.emit_op(StackOp::Opcode("OP_DUP".to_string())); // a b b
self.emit_op(StackOp::Opcode("OP_0NOTEQUAL".to_string())); // a b (b!=0)
self.emit_op(StackOp::If {
then_ops: vec![
// Stack: a b (b != 0)
// Compute a % b, then swap: new a = b, new b = a%b
StackOp::Opcode("OP_TUCK".to_string()), // b a b
StackOp::Opcode("OP_MOD".to_string()), // b (a%b)
],
else_ops: vec![
// Stack: a b (b == 0), just keep as-is
],
});
}
// Stack: a b (where b should be 0)
// Drop b, keep a (the GCD)
self.emit_op(StackOp::Drop);
self.sm.push(binding_name);
self.track_depth();
}
/// divmod(a, b): computes both a/b and a%b, returns a/b (drops a%b).
/// Stack: a b -> OP_2DUP OP_DIV OP_ROT OP_ROT OP_MOD OP_DROP -> quotient
fn lower_divmod(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(args.len() >= 2, "divmod requires 2 arguments");
let a_is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], a_is_last);
let b_is_last = self.is_last_use(&args[1], binding_index, last_uses);
self.bring_to_top(&args[1], b_is_last);
self.sm.pop();
self.sm.pop();
// Stack: a b
self.emit_op(StackOp::Opcode("OP_2DUP".to_string())); // a b a b
self.emit_op(StackOp::Opcode("OP_DIV".to_string())); // a b (a/b)
self.emit_op(StackOp::Opcode("OP_ROT".to_string())); // a (a/b) b
self.emit_op(StackOp::Opcode("OP_ROT".to_string())); // (a/b) b a
self.emit_op(StackOp::Opcode("OP_MOD".to_string())); // (a/b) (a%b) -- wait
// ROT ROT on a b (a/b): ROT -> b (a/b) a, ROT -> (a/b) a b
// Then MOD -> (a/b) (a%b)
// DROP -> (a/b)
self.emit_op(StackOp::Drop);
self.sm.push(binding_name);
self.track_depth();
}
/// log2(n): exact floor(log2(n)) via bit-scanning.
///
/// Uses a bounded unrolled loop (64 iterations for bigint range):
/// counter = 0
/// while input > 1: input >>= 1, counter++
/// result = counter
///
/// Stack layout during loop: <input> <counter>
/// Each iteration: OP_SWAP OP_DUP 1 OP_GREATERTHAN OP_IF 2 OP_DIV OP_SWAP OP_1ADD OP_SWAP OP_ENDIF OP_SWAP
fn lower_log2(
&mut self,
binding_name: &str,
args: &[String],
binding_index: usize,
last_uses: &HashMap<String, usize>,
) {
assert!(!args.is_empty(), "log2 requires 1 argument");
let n_is_last = self.is_last_use(&args[0], binding_index, last_uses);
self.bring_to_top(&args[0], n_is_last);
self.sm.pop();
// Stack: <n>
// Push counter = 0
self.emit_op(StackOp::Push(PushValue::Int(0))); // n 0
// 64 iterations (sufficient for Bitcoin Script bigint range)
const LOG2_ITERATIONS: usize = 64;
for _ in 0..LOG2_ITERATIONS {
// Stack: input counter
self.emit_op(StackOp::Swap); // counter input
self.emit_op(StackOp::Opcode("OP_DUP".to_string())); // counter input input
self.emit_op(StackOp::Push(PushValue::Int(1))); // counter input input 1
self.emit_op(StackOp::Opcode("OP_GREATERTHAN".to_string())); // counter input (input>1)
self.emit_op(StackOp::If {
then_ops: vec![
StackOp::Push(PushValue::Int(2)), // counter input 2
StackOp::Opcode("OP_DIV".to_string()), // counter (input/2)
StackOp::Swap, // (input/2) counter
StackOp::Opcode("OP_1ADD".to_string()), // (input/2) (counter+1)
StackOp::Swap, // (counter+1) (input/2)
],
else_ops: vec![],
});
// Stack: counter input (or input counter if swapped back)
// After the if: stack is counter input (swap at start, then if-branch swaps back)
self.emit_op(StackOp::Swap); // input counter
}
// Stack: input counter
// Drop input, keep counter
self.emit_op(StackOp::Nip); // counter
self.sm.push(binding_name);
self.track_depth();
}
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
/// Lower an ANF program to Stack IR.
/// Private methods are inlined at call sites rather than compiled separately.
/// The constructor is skipped since it's not emitted to Bitcoin Script.
pub fn lower_to_stack(program: &ANFProgram) -> Result<Vec<StackMethod>, String> {
// Wrap the inner implementation with catch_unwind to convert any panics
// (from stack underflow, unknown operators, type mismatches, etc.) into
// proper error returns instead of crashing the process.
std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
lower_to_stack_inner(program)
}))
.unwrap_or_else(|e| {
if let Some(s) = e.downcast_ref::<String>() {
Err(format!("stack lowering: {}", s))
} else if let Some(s) = e.downcast_ref::<&str>() {
Err(format!("stack lowering: {}", s))
} else {
Err("stack lowering: internal error".to_string())
}
})
}
fn lower_to_stack_inner(program: &ANFProgram) -> Result<Vec<StackMethod>, String> {
// Build map of private methods for inlining
let mut private_methods: HashMap<String, ANFMethod> = HashMap::new();
for method in &program.methods {
if !method.is_public && method.name != "constructor" {
private_methods.insert(method.name.clone(), method.clone());
}
}
let mut methods = Vec::new();
for method in &program.methods {
// Skip constructor and private methods
if method.name == "constructor" || (!method.is_public && method.name != "constructor") {
continue;
}
let sm = lower_method_with_private_methods(method, &program.properties, &private_methods)?;
methods.push(sm);
}
Ok(methods)
}
/// Check whether a method's body contains a CheckPreimage binding.
/// If found, the unlocking script will push an implicit <sig> parameter before
/// all declared parameters (OP_PUSH_TX pattern).
fn method_uses_check_preimage(bindings: &[ANFBinding]) -> bool {
bindings.iter().any(|b| matches!(&b.value, ANFValue::CheckPreimage { .. }))
}
/// Check whether a method has add_output, add_raw_output, or computeStateOutput/
/// computeStateOutputHash calls (recursively). Only methods that construct
/// continuation outputs need the _codePart implicit parameter.
fn method_uses_code_part(bindings: &[ANFBinding]) -> bool {
bindings.iter().any(|b| match &b.value {
ANFValue::AddOutput { .. } | ANFValue::AddRawOutput { .. } => true,
ANFValue::Call { func, .. } if func == "computeStateOutput" || func == "computeStateOutputHash" => true,
ANFValue::If { then, else_branch, .. } => method_uses_code_part(then) || method_uses_code_part(else_branch),
ANFValue::Loop { body, .. } => method_uses_code_part(body),
_ => false,
})
}
fn lower_method_with_private_methods(
method: &ANFMethod,
properties: &[ANFProperty],
private_methods: &HashMap<String, ANFMethod>,
) -> Result<StackMethod, String> {
let mut param_names: Vec<String> = method.params.iter().map(|p| p.name.clone()).collect();
// If the method uses checkPreimage, the unlocking script pushes implicit
// params before all declared parameters (OP_PUSH_TX pattern).
// _codePart: full code script (locking script minus state) as ByteString
// _opPushTxSig: ECDSA signature for OP_PUSH_TX verification
// These are inserted at the base of the stack so they can be consumed later.
if method_uses_check_preimage(&method.body) {
param_names.insert(0, "_opPushTxSig".to_string());
// _codePart is needed when the method has add_output or add_raw_output
// (it provides the code script for continuation output construction),
// or when deserializing variable-length (ByteString) state fields.
if method_uses_code_part(&method.body) {
param_names.insert(0, "_codePart".to_string());
}
}
let mut ctx = LoweringContext::new(¶m_names, properties);
ctx.private_methods = private_methods.clone();
// Pass terminal_assert=true for public methods so the last assert leaves
// its value on the stack (Bitcoin Script requires a truthy top-of-stack).
ctx.lower_bindings(&method.body, method.is_public);
// Clean up excess stack items left by deserialize_state.
let has_deserialize_state = method.body.iter().any(|b| matches!(&b.value, ANFValue::DeserializeState { .. }));
if method.is_public && has_deserialize_state && ctx.sm.depth() > 1 {
let excess = ctx.sm.depth() - 1;
for _ in 0..excess {
ctx.emit_op(StackOp::Nip);
ctx.sm.remove_at_depth(1);
}
}
if ctx.max_depth > MAX_STACK_DEPTH {
return Err(format!(
"method '{}' exceeds maximum stack depth of {} (actual: {}). Simplify the contract logic.",
method.name, MAX_STACK_DEPTH, ctx.max_depth
));
}
Ok(StackMethod {
name: method.name.clone(),
source_locs: ctx.source_locs,
ops: ctx.ops,
max_stack_depth: ctx.max_depth,
})
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn hex_to_bytes(hex_str: &str) -> Vec<u8> {
if hex_str.is_empty() {
return Vec::new();
}
assert!(
hex_str.len() % 2 == 0,
"invalid hex string length: {}",
hex_str.len()
);
(0..hex_str.len())
.step_by(2)
.map(|i| u8::from_str_radix(&hex_str[i..i + 2], 16).unwrap_or(0))
.collect()
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
use super::*;
use crate::ir::{ANFBinding, ANFMethod, ANFParam, ANFProgram, ANFProperty, ANFValue};
/// Build a minimal P2PKH IR program for testing stack lowering.
fn p2pkh_program() -> ANFProgram {
ANFProgram {
contract_name: "P2PKH".to_string(),
properties: vec![ANFProperty {
name: "pubKeyHash".to_string(),
prop_type: "Addr".to_string(),
readonly: true,
initial_value: None,
}],
methods: vec![ANFMethod {
name: "unlock".to_string(),
params: vec![
ANFParam {
name: "sig".to_string(),
param_type: "Sig".to_string(),
},
ANFParam {
name: "pubKey".to_string(),
param_type: "PubKey".to_string(),
},
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam {
name: "sig".to_string(),
},
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::LoadParam {
name: "pubKey".to_string(),
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::LoadProp {
name: "pubKeyHash".to_string(),
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::Call {
func: "hash160".to_string(),
args: vec!["t1".to_string()],
},
source_loc: None,
},
ANFBinding {
name: "t4".to_string(),
value: ANFValue::BinOp {
op: "===".to_string(),
left: "t3".to_string(),
right: "t2".to_string(),
result_type: None,
},
source_loc: None,
},
ANFBinding {
name: "t5".to_string(),
value: ANFValue::Assert {
value: "t4".to_string(),
},
source_loc: None,
},
ANFBinding {
name: "t6".to_string(),
value: ANFValue::Call {
func: "checkSig".to_string(),
args: vec!["t0".to_string(), "t1".to_string()],
},
source_loc: None,
},
ANFBinding {
name: "t7".to_string(),
value: ANFValue::Assert {
value: "t6".to_string(),
},
source_loc: None,
},
],
is_public: true,
}],
}
}
#[test]
fn test_p2pkh_stack_lowering_produces_placeholder_ops() {
let program = p2pkh_program();
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
assert_eq!(methods.len(), 1);
assert_eq!(methods[0].name, "unlock");
// There should be at least one Placeholder op (for the pubKeyHash property)
let has_placeholder = methods[0].ops.iter().any(|op| {
matches!(op, StackOp::Placeholder { .. })
});
assert!(
has_placeholder,
"P2PKH should have Placeholder ops for constructor params, ops: {:?}",
methods[0].ops
);
}
#[test]
fn test_placeholder_has_correct_param_index() {
let program = p2pkh_program();
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
// Find the Placeholder op and check its param_index
let placeholders: Vec<&StackOp> = methods[0]
.ops
.iter()
.filter(|op| matches!(op, StackOp::Placeholder { .. }))
.collect();
assert!(
!placeholders.is_empty(),
"should have at least one Placeholder"
);
// pubKeyHash is the only property at index 0
if let StackOp::Placeholder {
param_index,
param_name,
} = placeholders[0]
{
assert_eq!(*param_index, 0);
assert_eq!(param_name, "pubKeyHash");
} else {
panic!("expected Placeholder op");
}
}
#[test]
fn test_with_initial_values_no_placeholder_ops() {
let mut program = p2pkh_program();
// Set an initial value for the property -- this bakes it in
program.properties[0].initial_value =
Some(serde_json::Value::String("aabbccdd".to_string()));
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let has_placeholder = methods[0].ops.iter().any(|op| {
matches!(op, StackOp::Placeholder { .. })
});
assert!(
!has_placeholder,
"with initial values, there should be no Placeholder ops"
);
}
#[test]
fn test_stack_lowering_produces_standard_opcodes() {
let program = p2pkh_program();
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
// Collect all Opcode strings
let opcodes: Vec<&str> = methods[0]
.ops
.iter()
.filter_map(|op| match op {
StackOp::Opcode(code) => Some(code.as_str()),
_ => None,
})
.collect();
// P2PKH should contain OP_HASH160, OP_NUMEQUAL (from ===), OP_VERIFY, OP_CHECKSIG
assert!(
opcodes.contains(&"OP_HASH160"),
"expected OP_HASH160 in opcodes: {:?}",
opcodes
);
assert!(
opcodes.contains(&"OP_CHECKSIG"),
"expected OP_CHECKSIG in opcodes: {:?}",
opcodes
);
}
#[test]
fn test_max_stack_depth_is_tracked() {
let program = p2pkh_program();
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
assert!(
methods[0].max_stack_depth > 0,
"max_stack_depth should be > 0"
);
// P2PKH has 2 params + some intermediates, so depth should be reasonable
assert!(
methods[0].max_stack_depth <= 10,
"max_stack_depth should be reasonable for P2PKH, got: {}",
methods[0].max_stack_depth
);
}
// -----------------------------------------------------------------------
// Helper: collect all opcodes from a StackOp list (including inside If)
// -----------------------------------------------------------------------
fn collect_all_opcodes(ops: &[StackOp]) -> Vec<String> {
let mut result = Vec::new();
for op in ops {
match op {
StackOp::Opcode(code) => result.push(code.clone()),
StackOp::If { then_ops, else_ops } => {
result.push("OP_IF".to_string());
result.extend(collect_all_opcodes(then_ops));
result.push("OP_ELSE".to_string());
result.extend(collect_all_opcodes(else_ops));
result.push("OP_ENDIF".to_string());
}
StackOp::Push(PushValue::Int(n)) => {
result.push(format!("PUSH({})", n));
}
StackOp::Drop => result.push("OP_DROP".to_string()),
StackOp::Swap => result.push("OP_SWAP".to_string()),
StackOp::Dup => result.push("OP_DUP".to_string()),
StackOp::Over => result.push("OP_OVER".to_string()),
StackOp::Rot => result.push("OP_ROT".to_string()),
StackOp::Nip => result.push("OP_NIP".to_string()),
_ => {}
}
}
result
}
fn collect_opcodes_in_if_branches(ops: &[StackOp]) -> (Vec<String>, Vec<String>) {
for op in ops {
if let StackOp::If { then_ops, else_ops } = op {
return (collect_all_opcodes(then_ops), collect_all_opcodes(else_ops));
}
}
(vec![], vec![])
}
// -----------------------------------------------------------------------
// Fix #1: extractOutputHash offset must be 40, not 44
// -----------------------------------------------------------------------
#[test]
fn test_extract_output_hash_uses_offset_40() {
// Build a stateful contract that calls extractOutputHash on a preimage
let program = ANFProgram {
contract_name: "TestExtract".to_string(),
properties: vec![ANFProperty {
name: "val".to_string(),
prop_type: "bigint".to_string(),
readonly: false,
initial_value: Some(serde_json::Value::Number(serde_json::Number::from(0))),
}],
methods: vec![ANFMethod {
name: "check".to_string(),
params: vec![
ANFParam { name: "preimage".to_string(), param_type: "SigHashPreimage".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "preimage".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::Call {
func: "extractOutputHash".to_string(),
args: vec!["t0".to_string()],
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::LoadConst { value: serde_json::Value::Bool(true) },
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::Assert { value: "t2".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let opcodes = collect_all_opcodes(&methods[0].ops);
// The offset 40 should appear as PUSH(40), not PUSH(44)
assert!(
opcodes.contains(&"PUSH(40)".to_string()),
"extractOutputHash should use offset 40 (BIP-143 hashOutputs starts at size-40), ops: {:?}",
opcodes
);
assert!(
!opcodes.contains(&"PUSH(44)".to_string()),
"extractOutputHash should NOT use offset 44, ops: {:?}",
opcodes
);
}
// -----------------------------------------------------------------------
// Fix #3: Terminal-if propagation
// -----------------------------------------------------------------------
#[test]
fn test_terminal_if_propagates_terminal_assert() {
// A public method ending with if/else where both branches have asserts.
// The terminal asserts in both branches should NOT emit OP_VERIFY.
let program = ANFProgram {
contract_name: "TerminalIf".to_string(),
properties: vec![],
methods: vec![ANFMethod {
name: "check".to_string(),
params: vec![
ANFParam { name: "mode".to_string(), param_type: "boolean".to_string() },
ANFParam { name: "x".to_string(), param_type: "bigint".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "mode".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::LoadParam { name: "x".to_string() },
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::If {
cond: "t0".to_string(),
then: vec![
ANFBinding {
name: "t3".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Number(serde_json::Number::from(10)),
},
source_loc: None,
},
ANFBinding {
name: "t4".to_string(),
value: ANFValue::BinOp {
op: ">".to_string(),
left: "t1".to_string(),
right: "t3".to_string(),
result_type: None,
},
source_loc: None,
},
ANFBinding {
name: "t5".to_string(),
value: ANFValue::Assert { value: "t4".to_string() },
source_loc: None,
},
],
else_branch: vec![
ANFBinding {
name: "t6".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Number(serde_json::Number::from(5)),
},
source_loc: None,
},
ANFBinding {
name: "t7".to_string(),
value: ANFValue::BinOp {
op: ">".to_string(),
left: "t1".to_string(),
right: "t6".to_string(),
result_type: None,
},
source_loc: None,
},
ANFBinding {
name: "t8".to_string(),
value: ANFValue::Assert { value: "t7".to_string() },
source_loc: None,
},
],
},
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
// Get the opcodes inside the if branches
let (then_opcodes, else_opcodes) = collect_opcodes_in_if_branches(&methods[0].ops);
// Neither branch should contain OP_VERIFY — the asserts are terminal
assert!(
!then_opcodes.contains(&"OP_VERIFY".to_string()),
"then branch should not contain OP_VERIFY (terminal assert), got: {:?}",
then_opcodes
);
assert!(
!else_opcodes.contains(&"OP_VERIFY".to_string()),
"else branch should not contain OP_VERIFY (terminal assert), got: {:?}",
else_opcodes
);
}
// -----------------------------------------------------------------------
// Fix #8: pack/unpack/toByteString builtins
// -----------------------------------------------------------------------
#[test]
fn test_unpack_emits_bin2num() {
let program = ANFProgram {
contract_name: "TestUnpack".to_string(),
properties: vec![],
methods: vec![ANFMethod {
name: "check".to_string(),
params: vec![
ANFParam { name: "data".to_string(), param_type: "ByteString".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "data".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::Call {
func: "unpack".to_string(),
args: vec!["t0".to_string()],
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Number(serde_json::Number::from(42)),
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::BinOp {
op: "===".to_string(),
left: "t1".to_string(),
right: "t2".to_string(),
result_type: None,
},
source_loc: None,
},
ANFBinding {
name: "t4".to_string(),
value: ANFValue::Assert { value: "t3".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let opcodes = collect_all_opcodes(&methods[0].ops);
assert!(
opcodes.contains(&"OP_BIN2NUM".to_string()),
"unpack should emit OP_BIN2NUM, got: {:?}",
opcodes
);
}
#[test]
fn test_pack_is_noop() {
let program = ANFProgram {
contract_name: "TestPack".to_string(),
properties: vec![],
methods: vec![ANFMethod {
name: "check".to_string(),
params: vec![
ANFParam { name: "x".to_string(), param_type: "bigint".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "x".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::Call {
func: "pack".to_string(),
args: vec!["t0".to_string()],
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Bool(true),
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::Assert { value: "t2".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let opcodes = collect_all_opcodes(&methods[0].ops);
// pack should NOT emit any conversion opcode — just pass through
assert!(
!opcodes.contains(&"OP_BIN2NUM".to_string()),
"pack should not emit OP_BIN2NUM, got: {:?}",
opcodes
);
assert!(
!opcodes.contains(&"OP_NUM2BIN".to_string()),
"pack should not emit OP_NUM2BIN, got: {:?}",
opcodes
);
}
#[test]
fn test_to_byte_string_is_noop() {
let program = ANFProgram {
contract_name: "TestToByteString".to_string(),
properties: vec![],
methods: vec![ANFMethod {
name: "check".to_string(),
params: vec![
ANFParam { name: "x".to_string(), param_type: "bigint".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "x".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::Call {
func: "toByteString".to_string(),
args: vec!["t0".to_string()],
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Bool(true),
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::Assert { value: "t2".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let opcodes = collect_all_opcodes(&methods[0].ops);
// toByteString should NOT emit any conversion opcode — just pass through
assert!(
!opcodes.contains(&"OP_BIN2NUM".to_string()),
"toByteString should not emit OP_BIN2NUM, got: {:?}",
opcodes
);
}
// -----------------------------------------------------------------------
// Fix #25: sqrt(0) guard
// -----------------------------------------------------------------------
#[test]
fn test_sqrt_has_zero_guard() {
let program = ANFProgram {
contract_name: "TestSqrt".to_string(),
properties: vec![],
methods: vec![ANFMethod {
name: "check".to_string(),
params: vec![
ANFParam { name: "n".to_string(), param_type: "bigint".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "n".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::Call {
func: "sqrt".to_string(),
args: vec!["t0".to_string()],
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Number(serde_json::Number::from(0)),
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::BinOp {
op: ">=".to_string(),
left: "t1".to_string(),
right: "t2".to_string(),
result_type: None,
},
source_loc: None,
},
ANFBinding {
name: "t4".to_string(),
value: ANFValue::Assert { value: "t3".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let opcodes = collect_all_opcodes(&methods[0].ops);
// The sqrt implementation should have OP_DUP followed by OP_IF (the zero guard).
// The DUP duplicates n, then IF checks if n != 0 before Newton iteration.
let dup_idx = opcodes.iter().position(|o| o == "OP_DUP");
let if_idx = opcodes.iter().position(|o| o == "OP_IF");
assert!(
dup_idx.is_some() && if_idx.is_some(),
"sqrt should have OP_DUP and OP_IF for zero guard, got: {:?}",
opcodes
);
assert!(
dup_idx.unwrap() < if_idx.unwrap(),
"OP_DUP should come before OP_IF in sqrt zero guard, got: {:?}",
opcodes
);
}
// -----------------------------------------------------------------------
// Fix #28: Loop cleanup of unused iteration variables
// -----------------------------------------------------------------------
#[test]
fn test_loop_cleans_up_unused_iter_var() {
// A loop whose body has only asserts (which consume stack values).
// After the body, the iter var ends up on top of the stack (depth 0),
// so it should be dropped. The TS reference does this cleanup.
let program = ANFProgram {
contract_name: "TestLoopCleanup".to_string(),
properties: vec![],
methods: vec![ANFMethod {
name: "check".to_string(),
params: vec![
ANFParam { name: "x".to_string(), param_type: "bigint".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "x".to_string() },
source_loc: None,
},
ANFBinding {
name: "t_loop".to_string(),
value: ANFValue::Loop {
count: 3,
body: vec![
// Body uses x but not iter var __i, and asserts consume
ANFBinding {
name: "t1".to_string(),
value: ANFValue::LoadParam { name: "x".to_string() },
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::Assert { value: "t1".to_string() },
source_loc: None,
},
],
iter_var: "__i".to_string(),
},
source_loc: None,
},
ANFBinding {
name: "t_final".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Bool(true),
},
source_loc: None,
},
ANFBinding {
name: "t_assert".to_string(),
value: ANFValue::Assert { value: "t_final".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let opcodes = collect_all_opcodes(&methods[0].ops);
// Each iteration pushes __i, then the body asserts (consuming its value).
// After each iteration, __i is on top (depth 0) and should be dropped.
// With 3 iterations, we expect at least 3 OP_DROP ops (one per iter var cleanup).
let drop_count = opcodes.iter().filter(|o| o.as_str() == "OP_DROP").count();
assert!(
drop_count >= 3,
"unused iter var should be dropped after each iteration; expected >= 3 OP_DROPs, got {}: {:?}",
drop_count,
opcodes
);
}
// -----------------------------------------------------------------------
// Fix #29: PushValue::Int uses i128 (no overflow for large values)
// -----------------------------------------------------------------------
#[test]
fn test_push_value_int_large_values() {
// Verify that PushValue::Int can hold values larger than i64::MAX
let large_val: i128 = (i64::MAX as i128) + 1;
let push = PushValue::Int(large_val);
if let PushValue::Int(v) = push {
assert_eq!(v, large_val, "PushValue::Int should store values > i64::MAX without truncation");
} else {
panic!("expected PushValue::Int");
}
// Also test negative extreme
let neg_val: i128 = (i64::MIN as i128) - 1;
let push_neg = PushValue::Int(neg_val);
if let PushValue::Int(v) = push_neg {
assert_eq!(v, neg_val, "PushValue::Int should store values < i64::MIN without truncation");
} else {
panic!("expected PushValue::Int");
}
}
#[test]
fn test_push_value_int_encodes_large_number() {
// Verify that a large number (> i64::MAX) can be pushed and encoded
use crate::codegen::emit::encode_push_int;
let large_val: i128 = 1i128 << 100;
let (hex, _asm) = encode_push_int(large_val);
// Should produce a valid hex encoding, not panic or truncate
assert!(!hex.is_empty(), "encoding of 2^100 should produce non-empty hex");
// Verify the encoding length is reasonable for a 13-byte number
// 2^100 needs 13 bytes in script number encoding (sign-magnitude)
// Push data: 0x0d (length 13) + 13 bytes = 14 bytes = 28 hex chars
assert!(
hex.len() >= 26,
"2^100 should need at least 13 bytes of push data, got hex length {}: {}",
hex.len(),
hex
);
}
// -----------------------------------------------------------------------
// log2 uses bit-scanning (OP_DIV + OP_GREATERTHAN), not byte approx
// -----------------------------------------------------------------------
#[test]
fn test_log2_uses_bit_scanning_not_byte_approx() {
let program = ANFProgram {
contract_name: "TestLog2".to_string(),
properties: vec![],
methods: vec![ANFMethod {
name: "check".to_string(),
params: vec![
ANFParam { name: "n".to_string(), param_type: "bigint".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "n".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::Call {
func: "log2".to_string(),
args: vec!["t0".to_string()],
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Number(serde_json::Number::from(0)),
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::BinOp {
op: ">=".to_string(),
left: "t1".to_string(),
right: "t2".to_string(),
result_type: None,
},
source_loc: None,
},
ANFBinding {
name: "t4".to_string(),
value: ANFValue::Assert { value: "t3".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let opcodes = collect_all_opcodes(&methods[0].ops);
// The bit-scanning implementation must use OP_DIV and OP_GREATERTHAN
assert!(
opcodes.contains(&"OP_DIV".to_string()),
"log2 should use OP_DIV (bit-scanning), got: {:?}",
opcodes
);
assert!(
opcodes.contains(&"OP_GREATERTHAN".to_string()),
"log2 should use OP_GREATERTHAN (bit-scanning), got: {:?}",
opcodes
);
// The old byte-approximation used OP_SIZE and OP_MUL — must NOT be present
assert!(
!opcodes.contains(&"OP_SIZE".to_string()),
"log2 should NOT use OP_SIZE (old byte approximation), got: {:?}",
opcodes
);
assert!(
!opcodes.contains(&"OP_MUL".to_string()),
"log2 should NOT use OP_MUL (old byte approximation), got: {:?}",
opcodes
);
// Should have OP_1ADD for counter increment
assert!(
opcodes.contains(&"OP_1ADD".to_string()),
"log2 should use OP_1ADD (counter increment), got: {:?}",
opcodes
);
}
// -----------------------------------------------------------------------
// reverseBytes uses OP_SPLIT + OP_CAT (not non-existent OP_REVERSE)
// -----------------------------------------------------------------------
#[test]
fn test_reverse_bytes_uses_split_cat_not_op_reverse() {
let program = ANFProgram {
contract_name: "TestReverse".to_string(),
properties: vec![],
methods: vec![ANFMethod {
name: "check".to_string(),
params: vec![
ANFParam { name: "data".to_string(), param_type: "ByteString".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "data".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::Call {
func: "reverseBytes".to_string(),
args: vec!["t0".to_string()],
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Bool(true),
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::Assert { value: "t2".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let opcodes = collect_all_opcodes(&methods[0].ops);
// Must NOT contain the non-existent OP_REVERSE
assert!(
!opcodes.contains(&"OP_REVERSE".to_string()),
"reverseBytes must NOT emit OP_REVERSE (does not exist), got: {:?}",
opcodes
);
// Must use OP_SPLIT and OP_CAT for byte-by-byte reversal
assert!(
opcodes.contains(&"OP_SPLIT".to_string()),
"reverseBytes should emit OP_SPLIT for byte peeling, got: {:?}",
opcodes
);
assert!(
opcodes.contains(&"OP_CAT".to_string()),
"reverseBytes should emit OP_CAT for reassembly, got: {:?}",
opcodes
);
// Should use OP_SIZE to check remaining length
assert!(
opcodes.contains(&"OP_SIZE".to_string()),
"reverseBytes should emit OP_SIZE for length check, got: {:?}",
opcodes
);
}
// -----------------------------------------------------------------------
// Test: only public methods appear in stack output (method count)
// -----------------------------------------------------------------------
#[test]
fn test_method_count_matches_public_methods() {
// P2PKH program has 1 public method (unlock) and 1 constructor (non-public)
let program = p2pkh_program();
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
// Should have exactly 1 method (unlock) — constructor is skipped
assert_eq!(
methods.len(),
1,
"expected 1 stack method (unlock), got {}: {:?}",
methods.len(),
methods.iter().map(|m| &m.name).collect::<Vec<_>>()
);
assert_eq!(methods[0].name, "unlock");
}
// -----------------------------------------------------------------------
// Test: multi-method contract has correct number of StackMethods
// -----------------------------------------------------------------------
#[test]
fn test_multi_method_dispatch() {
let program = ANFProgram {
contract_name: "Multi".to_string(),
properties: vec![],
methods: vec![
ANFMethod {
name: "constructor".to_string(),
params: vec![],
body: vec![],
is_public: false,
},
ANFMethod {
name: "method1".to_string(),
params: vec![ANFParam {
name: "x".to_string(),
param_type: "bigint".to_string(),
}],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "x".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Number(serde_json::Number::from(42)),
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::BinOp {
op: "===".to_string(),
left: "t0".to_string(),
right: "t1".to_string(),
result_type: None,
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::Assert { value: "t2".to_string() },
source_loc: None,
},
],
is_public: true,
},
ANFMethod {
name: "method2".to_string(),
params: vec![ANFParam {
name: "y".to_string(),
param_type: "bigint".to_string(),
}],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "y".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Number(serde_json::Number::from(100)),
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::BinOp {
op: "===".to_string(),
left: "t0".to_string(),
right: "t1".to_string(),
result_type: None,
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::Assert { value: "t2".to_string() },
source_loc: None,
},
],
is_public: true,
},
],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
assert_eq!(
methods.len(),
2,
"expected 2 stack methods, got {}: {:?}",
methods.len(),
methods.iter().map(|m| &m.name).collect::<Vec<_>>()
);
}
// -----------------------------------------------------------------------
// Test: extractOutputs uses offset 40, not 44
// -----------------------------------------------------------------------
#[test]
fn test_extract_outputs_uses_offset_40() {
let program = ANFProgram {
contract_name: "OutputsCheck".to_string(),
properties: vec![],
methods: vec![ANFMethod {
name: "check".to_string(),
params: vec![ANFParam {
name: "preimage".to_string(),
param_type: "SigHashPreimage".to_string(),
}],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "preimage".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::Call {
func: "extractOutputs".to_string(),
args: vec!["t0".to_string()],
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::Assert { value: "t1".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let opcodes = collect_all_opcodes(&methods[0].ops);
// The offset for extractOutputs should be 40 (hashOutputs(32) + nLocktime(4) + sighashType(4))
// Encoded as PUSH(40)
assert!(
opcodes.contains(&"PUSH(40)".to_string()),
"expected PUSH(40) for extractOutputs offset, got: {:?}",
opcodes
);
// Must NOT use the old incorrect offset 44
assert!(
!opcodes.contains(&"PUSH(44)".to_string()),
"extractOutputs should NOT use offset 44, got: {:?}",
opcodes
);
}
// -----------------------------------------------------------------------
// Test: arithmetic binary op (a + b) produces OP_ADD in stack output
// Mirrors Go TestLowerToStack_ArithmeticOps
// -----------------------------------------------------------------------
#[test]
fn test_arithmetic_ops_contains_add() {
// Contract: verify(a, b) { assert(a + b === target) }
let program = ANFProgram {
contract_name: "ArithCheck".to_string(),
properties: vec![ANFProperty {
name: "target".to_string(),
prop_type: "bigint".to_string(),
readonly: true,
initial_value: None,
}],
methods: vec![ANFMethod {
name: "verify".to_string(),
params: vec![
ANFParam { name: "a".to_string(), param_type: "bigint".to_string() },
ANFParam { name: "b".to_string(), param_type: "bigint".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "a".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::LoadParam { name: "b".to_string() },
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::BinOp {
op: "+".to_string(),
left: "t0".to_string(),
right: "t1".to_string(),
result_type: None,
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::LoadProp { name: "target".to_string() },
source_loc: None,
},
ANFBinding {
name: "t4".to_string(),
value: ANFValue::BinOp {
op: "===".to_string(),
left: "t2".to_string(),
right: "t3".to_string(),
result_type: None,
},
source_loc: None,
},
ANFBinding {
name: "t5".to_string(),
value: ANFValue::Assert { value: "t4".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let opcodes = collect_all_opcodes(&methods[0].ops);
// The a + b operation should emit OP_ADD
assert!(
opcodes.contains(&"OP_ADD".to_string()),
"expected OP_ADD in stack ops for 'a + b', got: {:?}",
opcodes
);
// The === comparison should emit OP_NUMEQUAL
assert!(
opcodes.contains(&"OP_NUMEQUAL".to_string()),
"expected OP_NUMEQUAL in stack ops for '===', got: {:?}",
opcodes
);
}
// -----------------------------------------------------------------------
// S18: PICK/ROLL depth ≤ max_stack_depth (stack invariant)
// After lowering P2PKH, verify no Pick or Roll references a depth ≥ max_stack_depth
// -----------------------------------------------------------------------
#[test]
fn test_s18_pick_roll_depth_within_max_stack_depth() {
let program = p2pkh_program();
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let max_depth = methods[0].max_stack_depth;
fn check_ops(ops: &[StackOp], max_depth: usize) {
for op in ops {
match op {
StackOp::Pick { depth } => {
assert!(
*depth < max_depth,
"Pick depth {} must be < max_stack_depth {}",
depth,
max_depth
);
}
StackOp::Roll { depth } => {
assert!(
*depth < max_depth,
"Roll depth {} must be < max_stack_depth {}",
depth,
max_depth
);
}
StackOp::If { then_ops, else_ops } => {
check_ops(then_ops, max_depth);
check_ops(else_ops, max_depth);
}
_ => {}
}
}
}
check_ops(&methods[0].ops, max_depth);
}
// -----------------------------------------------------------------------
// Row 190: ByteString concatenation (bin_op "+", result_type="bytes") → OP_CAT
// Row 189 (bigint add) → OP_ADD is already tested above.
// -----------------------------------------------------------------------
#[test]
fn test_bytestring_concat_emits_op_cat() {
let program = ANFProgram {
contract_name: "CatCheck".to_string(),
properties: vec![],
methods: vec![ANFMethod {
name: "verify".to_string(),
params: vec![
ANFParam { name: "a".to_string(), param_type: "ByteString".to_string() },
ANFParam { name: "b".to_string(), param_type: "ByteString".to_string() },
ANFParam { name: "expected".to_string(), param_type: "ByteString".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "a".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::LoadParam { name: "b".to_string() },
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::BinOp {
op: "+".to_string(),
left: "t0".to_string(),
right: "t1".to_string(),
result_type: Some("bytes".to_string()), // ByteString concat
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::LoadParam { name: "expected".to_string() },
source_loc: None,
},
ANFBinding {
name: "t4".to_string(),
value: ANFValue::BinOp {
op: "===".to_string(),
left: "t2".to_string(),
right: "t3".to_string(),
result_type: Some("bytes".to_string()),
},
source_loc: None,
},
ANFBinding {
name: "t5".to_string(),
value: ANFValue::Assert { value: "t4".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
let opcodes = collect_all_opcodes(&methods[0].ops);
assert!(
opcodes.contains(&"OP_CAT".to_string()),
"ByteString '+' (result_type='bytes') should emit OP_CAT; got opcodes: {:?}",
opcodes
);
assert!(
!opcodes.contains(&"OP_ADD".to_string()),
"ByteString '+' should NOT emit OP_ADD (that's for bigint); got opcodes: {:?}",
opcodes
);
}
// -----------------------------------------------------------------------
// Row 201: log2 emits exactly 64 if-ops with OP_DIV+OP_1ADD
// (bit-scanning: 64 iterations, one per bit of a 64-bit integer)
// -----------------------------------------------------------------------
#[test]
fn test_log2_emits_64_if_ops() {
let program = ANFProgram {
contract_name: "TestLog2Count".to_string(),
properties: vec![],
methods: vec![ANFMethod {
name: "check".to_string(),
params: vec![
ANFParam { name: "n".to_string(), param_type: "bigint".to_string() },
],
body: vec![
ANFBinding {
name: "t0".to_string(),
value: ANFValue::LoadParam { name: "n".to_string() },
source_loc: None,
},
ANFBinding {
name: "t1".to_string(),
value: ANFValue::Call {
func: "log2".to_string(),
args: vec!["t0".to_string()],
},
source_loc: None,
},
ANFBinding {
name: "t2".to_string(),
value: ANFValue::LoadConst {
value: serde_json::Value::Number(serde_json::Number::from(0)),
},
source_loc: None,
},
ANFBinding {
name: "t3".to_string(),
value: ANFValue::BinOp {
op: ">=".to_string(),
left: "t1".to_string(),
right: "t2".to_string(),
result_type: None,
},
source_loc: None,
},
ANFBinding {
name: "t4".to_string(),
value: ANFValue::Assert { value: "t3".to_string() },
source_loc: None,
},
],
is_public: true,
}],
};
let methods = lower_to_stack(&program).expect("stack lowering should succeed");
// Count OP_IF occurrences — there should be exactly 64 (one per bit)
fn count_if_ops(ops: &[StackOp]) -> usize {
let mut count = 0;
for op in ops {
match op {
StackOp::If { then_ops, else_ops } => {
count += 1;
count += count_if_ops(then_ops);
count += count_if_ops(else_ops);
}
_ => {}
}
}
count
}
let if_count = count_if_ops(&methods[0].ops);
assert_eq!(
if_count, 64,
"log2 should emit exactly 64 if-ops (one per bit); got {} if-ops",
if_count
);
}
}