summaryrefslogtreecommitdiff
path: root/data/transactions/logic/eval.go
blob: aa2744ddc4aa62361b112882fd4bc17db5eb7eae (plain)
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
// Copyright (C) 2019-2021 Algorand, Inc.
// This file is part of go-algorand
//
// go-algorand is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// go-algorand is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with go-algorand.  If not, see <https://www.gnu.org/licenses/>.

package logic

import (
	"bytes"
	"crypto/sha256"
	"crypto/sha512"
	"encoding/binary"
	"encoding/hex"
	"errors"
	"fmt"
	"io"
	"math"
	"math/big"
	"math/bits"
	"runtime"
	"strings"

	"golang.org/x/crypto/sha3"

	"github.com/algorand/go-algorand/config"
	"github.com/algorand/go-algorand/crypto"
	"github.com/algorand/go-algorand/crypto/secp256k1"
	"github.com/algorand/go-algorand/data/basics"
	"github.com/algorand/go-algorand/data/transactions"
	"github.com/algorand/go-algorand/logging"
	"github.com/algorand/go-algorand/protocol"
)

// EvalMaxVersion is the max version we can interpret and run
const EvalMaxVersion = LogicVersion

// The constants below control TEAL opcodes evaluation and MAY NOT be changed
// without moving them into consensus parameters.

// MaxStringSize is the limit of byte strings created by `concat`
const MaxStringSize = 4096

// MaxByteMathSize is the limit of byte strings supplied as input to byte math opcodes
const MaxByteMathSize = 64

// MaxLogSize is the limit of total log size from n log calls in a program
const MaxLogSize = 1024

// MaxLogCalls is the limit of total log calls during a program execution
const MaxLogCalls = 32

// stackValue is the type for the operand stack.
// Each stackValue is either a valid []byte value or a uint64 value.
// If (.Bytes != nil) the stackValue is a []byte value, otherwise uint64 value.
type stackValue struct {
	Uint  uint64
	Bytes []byte
}

func (sv *stackValue) argType() StackType {
	if sv.Bytes != nil {
		return StackBytes
	}
	return StackUint64
}

func (sv *stackValue) typeName() string {
	if sv.Bytes != nil {
		return "[]byte"
	}
	return "uint64"
}

func (sv *stackValue) clone() stackValue {
	if sv.Bytes != nil {
		// clone stack value if Bytes
		bytesClone := make([]byte, len(sv.Bytes))
		copy(bytesClone, sv.Bytes)
		return stackValue{Bytes: bytesClone}
	}
	// otherwise no cloning is needed if Uint
	return stackValue{Uint: sv.Uint}
}

func (sv *stackValue) String() string {
	if sv.Bytes != nil {
		return hex.EncodeToString(sv.Bytes)
	}
	return fmt.Sprintf("%d 0x%x", sv.Uint, sv.Uint)
}

func (sv *stackValue) address() (addr basics.Address, err error) {
	if len(sv.Bytes) != len(addr) {
		return basics.Address{}, errors.New("not an address")
	}
	copy(addr[:], sv.Bytes)
	return
}

func (sv *stackValue) uint() (uint64, error) {
	if sv.Bytes != nil {
		return 0, errors.New("not a uint64")
	}
	return sv.Uint, nil
}

func (sv *stackValue) bool() (bool, error) {
	u64, err := sv.uint()
	if err != nil {
		return false, err
	}
	switch u64 {
	case 0:
		return false, nil
	case 1:
		return true, nil
	default:
		return false, fmt.Errorf("boolean is neither 1 nor 0: %d", u64)
	}
}

func (sv *stackValue) string(limit int) (string, error) {
	if sv.Bytes == nil {
		return "", errors.New("not a byte array")
	}
	if len(sv.Bytes) > limit {
		return "", errors.New("value is too long")
	}
	return string(sv.Bytes), nil
}

func stackValueFromTealValue(tv *basics.TealValue) (sv stackValue, err error) {
	switch tv.Type {
	case basics.TealBytesType:
		sv.Bytes = []byte(tv.Bytes)
	case basics.TealUintType:
		sv.Uint = tv.Uint
	default:
		err = fmt.Errorf("invalid TealValue type: %d", tv.Type)
	}
	return
}

// ComputeMinTealVersion calculates the minimum safe TEAL version that may be
// used by a transaction in this group. It is important to prevent
// newly-introduced transaction fields from breaking assumptions made by older
// versions of TEAL. If one of the transactions in a group will execute a TEAL
// program whose version predates a given field, that field must not be set
// anywhere in the transaction group, or the group will be rejected.
func ComputeMinTealVersion(group []transactions.SignedTxn) uint64 {
	var minVersion uint64
	for _, txn := range group {
		if !txn.Txn.RekeyTo.IsZero() {
			if minVersion < rekeyingEnabledVersion {
				minVersion = rekeyingEnabledVersion
			}
		}
		if txn.Txn.Type == protocol.ApplicationCallTx {
			if minVersion < appsEnabledVersion {
				minVersion = appsEnabledVersion
			}
		}
	}
	return minVersion
}

func (sv *stackValue) toTealValue() (tv basics.TealValue) {
	if sv.argType() == StackBytes {
		return basics.TealValue{Type: basics.TealBytesType, Bytes: string(sv.Bytes)}
	}
	return basics.TealValue{Type: basics.TealUintType, Uint: sv.Uint}
}

// LedgerForLogic represents ledger API for Stateful TEAL program
type LedgerForLogic interface {
	Balance(addr basics.Address) (basics.MicroAlgos, error)
	MinBalance(addr basics.Address, proto *config.ConsensusParams) (basics.MicroAlgos, error)
	Authorizer(addr basics.Address) (basics.Address, error)
	Round() basics.Round
	LatestTimestamp() int64

	AssetHolding(addr basics.Address, assetIdx basics.AssetIndex) (basics.AssetHolding, error)
	AssetParams(aidx basics.AssetIndex) (basics.AssetParams, basics.Address, error)
	AppParams(aidx basics.AppIndex) (basics.AppParams, basics.Address, error)
	ApplicationID() basics.AppIndex
	OptedIn(addr basics.Address, appIdx basics.AppIndex) (bool, error)
	GetCreatableID(groupIdx int) basics.CreatableIndex

	GetLocal(addr basics.Address, appIdx basics.AppIndex, key string, accountIdx uint64) (value basics.TealValue, exists bool, err error)
	SetLocal(addr basics.Address, key string, value basics.TealValue, accountIdx uint64) error
	DelLocal(addr basics.Address, key string, accountIdx uint64) error

	GetGlobal(appIdx basics.AppIndex, key string) (value basics.TealValue, exists bool, err error)
	SetGlobal(key string, value basics.TealValue) error
	DelGlobal(key string) error

	GetDelta(txn *transactions.Transaction) (evalDelta transactions.EvalDelta, err error)

	Perform(txn *transactions.Transaction, spec transactions.SpecialAddresses) (transactions.ApplyData, error)
}

// EvalSideEffects contains data returned from evaluation
type EvalSideEffects struct {
	scratchSpace scratchSpace
}

// MakePastSideEffects allocates and initializes a slice of EvalSideEffects of length `size`
func MakePastSideEffects(size int) (pastSideEffects []EvalSideEffects) {
	pastSideEffects = make([]EvalSideEffects, size)
	for j := range pastSideEffects {
		pastSideEffects[j] = EvalSideEffects{}
	}
	return
}

// getScratchValue loads and clones a stackValue
// The value is cloned so the original bytes are protected from changes
func (se *EvalSideEffects) getScratchValue(scratchPos uint8) stackValue {
	return se.scratchSpace[scratchPos].clone()
}

// setScratchSpace stores the scratch space
func (se *EvalSideEffects) setScratchSpace(scratch scratchSpace) {
	se.scratchSpace = scratch
}

// EvalParams contains data that comes into condition evaluation.
type EvalParams struct {
	// the transaction being evaluated
	Txn *transactions.SignedTxn

	Proto *config.ConsensusParams

	Trace io.Writer

	TxnGroup []transactions.SignedTxn

	// GroupIndex should point to Txn within TxnGroup
	GroupIndex uint64

	PastSideEffects []EvalSideEffects

	Logger logging.Logger

	Ledger LedgerForLogic

	// optional debugger
	Debugger DebuggerHook

	// MinTealVersion is the minimum allowed TEAL version of this program.
	// The program must reject if its version is less than this version. If
	// MinTealVersion is nil, we will compute it ourselves
	MinTealVersion *uint64

	// Amount "overpaid" by the top-level transactions of the
	// group.  Often 0.  When positive, it is spent by application
	// actions.  Shared value across a group's txns, so that it
	// can be updated. nil is interpretted as 0.
	FeeCredit *uint64

	Specials *transactions.SpecialAddresses

	// determines eval mode: runModeSignature or runModeApplication
	runModeFlags runMode

	// Total pool of app call budget in a group transaction
	PooledApplicationBudget *uint64
}

type opEvalFunc func(cx *EvalContext)
type opCheckFunc func(cx *EvalContext) error

type runMode uint64

const (
	// runModeSignature is TEAL in LogicSig execution
	runModeSignature runMode = 1 << iota

	// runModeApplication is TEAL in application/stateful mode
	runModeApplication

	// local constant, run in any mode
	modeAny = runModeSignature | runModeApplication
)

func (r runMode) Any() bool {
	return r == modeAny
}

func (r runMode) String() string {
	switch r {
	case runModeSignature:
		return "Signature"
	case runModeApplication:
		return "Application"
	case modeAny:
		return "Any"
	default:
	}
	return "Unknown"
}

func (ep EvalParams) budget() int {
	if ep.runModeFlags == runModeSignature {
		return int(ep.Proto.LogicSigMaxCost)
	}
	if ep.Proto.EnableAppCostPooling && ep.PooledApplicationBudget != nil {
		return int(*ep.PooledApplicationBudget)
	}
	return ep.Proto.MaxAppProgramCost
}

func (ep EvalParams) log() logging.Logger {
	if ep.Logger != nil {
		return ep.Logger
	}
	return logging.Base()
}

type scratchSpace = [256]stackValue

// EvalContext is the execution context of AVM bytecode.  It contains
// the full state of the running program, and tracks some of the
// things that the program has been done, like log message and inner
// transactions.
type EvalContext struct {
	EvalParams

	stack     []stackValue
	callstack []int

	program []byte
	pc      int
	nextpc  int
	err     error
	intc    []uint64
	bytec   [][]byte
	version uint64
	scratch scratchSpace

	subtxn *transactions.SignedTxn // place to build for itxn_submit
	// The transactions Performed() and their effects
	InnerTxns []transactions.SignedTxnWithAD

	cost    int // cost incurred so far
	Logs    []string
	logSize int // total log size so far

	// Set of PC values that branches we've seen so far might
	// go. So, if checkStep() skips one, that branch is trying to
	// jump into the middle of a multibyte instruction
	branchTargets map[int]bool

	// Set of PC values that we have begun a checkStep() with. So
	// if a back jump is going to a value that isn't here, it's
	// jumping into the middle of multibyte instruction.
	instructionStarts map[int]bool

	programHashCached crypto.Digest
	txidCache         map[uint64]transactions.Txid
	appAddrCache      map[basics.AppIndex]basics.Address

	// Stores state & disassembly for the optional debugger
	debugState DebugState
}

// StackType describes the type of a value on the operand stack
type StackType byte

// StackTypes is an alias for a list of StackType with syntactic sugar
type StackTypes []StackType

// StackNone in an OpSpec shows that the op pops or yields nothing
const StackNone StackType = 0

// StackAny in an OpSpec shows that the op pops or yield any type
const StackAny StackType = 1

// StackUint64 in an OpSpec shows that the op pops or yields a uint64
const StackUint64 StackType = 2

// StackBytes in an OpSpec shows that the op pops or yields a []byte
const StackBytes StackType = 3

func (st StackType) String() string {
	switch st {
	case StackNone:
		return "None"
	case StackAny:
		return "any"
	case StackUint64:
		return "uint64"
	case StackBytes:
		return "[]byte"
	}
	return "internal error, unknown type"
}

func (sts StackTypes) plus(other StackTypes) StackTypes {
	return append(sts, other...)
}

// PanicError wraps a recover() catching a panic()
type PanicError struct {
	PanicValue interface{}
	StackTrace string
}

func (pe PanicError) Error() string {
	return fmt.Sprintf("panic in TEAL Eval: %v\n%s", pe.PanicValue, pe.StackTrace)
}

var errLogicSigNotSupported = errors.New("LogicSig not supported")
var errTooManyArgs = errors.New("LogicSig has too many arguments")

// EvalStatefulCx executes stateful TEAL program
func EvalStatefulCx(program []byte, params EvalParams) (bool, *EvalContext, error) {
	var cx EvalContext
	cx.EvalParams = params
	cx.runModeFlags = runModeApplication
	pass, err := eval(program, &cx)

	// The following two updates show a need for something like a
	// GroupEvalContext, as we are currently tucking things into the
	// EvalParams so that they are available to later calls.

	// update pooled budget
	if cx.Proto.EnableAppCostPooling && cx.PooledApplicationBudget != nil {
		// if eval passes, then budget is always greater than cost, so should not have underflow
		*cx.PooledApplicationBudget = basics.SubSaturate(*cx.PooledApplicationBudget, uint64(cx.cost))
	}
	// update side effects
	cx.PastSideEffects[cx.GroupIndex].setScratchSpace(cx.scratch)

	return pass, &cx, err
}

// EvalStateful is a lighter weight interface that doesn't return the EvalContext
func EvalStateful(program []byte, params EvalParams) (bool, error) {
	pass, _, err := EvalStatefulCx(program, params)
	return pass, err
}

// Eval checks to see if a transaction passes logic
// A program passes successfully if it finishes with one int element on the stack that is non-zero.
func Eval(program []byte, params EvalParams) (pass bool, err error) {
	var cx EvalContext
	cx.EvalParams = params
	cx.runModeFlags = runModeSignature
	return eval(program, &cx)
}

// eval implementation
// A program passes successfully if it finishes with one int element on the stack that is non-zero.
func eval(program []byte, cx *EvalContext) (pass bool, err error) {
	defer func() {
		if x := recover(); x != nil {
			buf := make([]byte, 16*1024)
			stlen := runtime.Stack(buf, false)
			pass = false
			errstr := string(buf[:stlen])
			if cx.EvalParams.Trace != nil {
				if sb, ok := cx.EvalParams.Trace.(*strings.Builder); ok {
					errstr += sb.String()
				}
			}
			err = PanicError{x, errstr}
			cx.EvalParams.log().Errorf("recovered panic in Eval: %w", err)
		}
	}()

	defer func() {
		// Ensure we update the debugger before exiting
		if cx.Debugger != nil {
			errDbg := cx.Debugger.Complete(cx.refreshDebugState())
			if err == nil {
				err = errDbg
			}
		}
	}()

	if (cx.EvalParams.Proto == nil) || (cx.EvalParams.Proto.LogicSigVersion == 0) {
		err = errLogicSigNotSupported
		return
	}
	if cx.EvalParams.Txn.Lsig.Args != nil && len(cx.EvalParams.Txn.Lsig.Args) > transactions.EvalMaxArgs {
		err = errTooManyArgs
		return
	}

	if len(program) == 0 {
		cx.err = errors.New("invalid program (empty)")
		return false, cx.err
	}
	version, vlen := binary.Uvarint(program)
	if vlen <= 0 {
		cx.err = errors.New("invalid version")
		return false, cx.err
	}
	if version > EvalMaxVersion {
		cx.err = fmt.Errorf("program version %d greater than max supported version %d", version, EvalMaxVersion)
		return false, cx.err
	}
	if version > cx.EvalParams.Proto.LogicSigVersion {
		cx.err = fmt.Errorf("program version %d greater than protocol supported version %d", version, cx.EvalParams.Proto.LogicSigVersion)
		return false, cx.err
	}

	var minVersion uint64
	if cx.EvalParams.MinTealVersion == nil {
		minVersion = ComputeMinTealVersion(cx.EvalParams.TxnGroup)
	} else {
		minVersion = *cx.EvalParams.MinTealVersion
	}
	if version < minVersion {
		cx.err = fmt.Errorf("program version must be >= %d for this transaction group, but have version %d", minVersion, version)
		return false, cx.err
	}

	cx.version = version
	cx.pc = vlen
	cx.stack = make([]stackValue, 0, 10)
	cx.program = program

	if cx.Debugger != nil {
		cx.debugState = makeDebugState(cx)
		if err = cx.Debugger.Register(cx.refreshDebugState()); err != nil {
			return
		}
	}

	for (cx.err == nil) && (cx.pc < len(cx.program)) {
		if cx.Debugger != nil {
			if err = cx.Debugger.Update(cx.refreshDebugState()); err != nil {
				return
			}
		}

		cx.step()
	}
	if cx.err != nil {
		if cx.Trace != nil {
			fmt.Fprintf(cx.Trace, "%3d %s\n", cx.pc, cx.err)
		}

		return false, cx.err
	}
	if len(cx.stack) != 1 {
		if cx.Trace != nil {
			fmt.Fprintf(cx.Trace, "end stack:\n")
			for i, sv := range cx.stack {
				fmt.Fprintf(cx.Trace, "[%d] %s\n", i, sv.String())
			}
		}
		return false, fmt.Errorf("stack len is %d instead of 1", len(cx.stack))
	}
	if cx.stack[0].Bytes != nil {
		return false, errors.New("stack finished with bytes not int")
	}

	return cx.stack[0].Uint != 0, nil
}

// CheckStateful should be faster than EvalStateful.  It can perform
// static checks and reject programs that are invalid. Prior to v4,
// these static checks include a cost estimate that must be low enough
// (controlled by params.Proto).
func CheckStateful(program []byte, params EvalParams) error {
	params.runModeFlags = runModeApplication
	return check(program, params)
}

// Check should be faster than Eval.  It can perform static checks and
// reject programs that are invalid. Prior to v4, these static checks
// include a cost estimate that must be low enough (controlled by
// params.Proto).
func Check(program []byte, params EvalParams) error {
	params.runModeFlags = runModeSignature
	return check(program, params)
}

func check(program []byte, params EvalParams) (err error) {
	defer func() {
		if x := recover(); x != nil {
			buf := make([]byte, 16*1024)
			stlen := runtime.Stack(buf, false)
			errstr := string(buf[:stlen])
			if params.Trace != nil {
				if sb, ok := params.Trace.(*strings.Builder); ok {
					errstr += sb.String()
				}
			}
			err = PanicError{x, errstr}
			params.log().Errorf("recovered panic in Check: %s", err)
		}
	}()
	if (params.Proto == nil) || (params.Proto.LogicSigVersion == 0) {
		return errLogicSigNotSupported
	}
	version, vlen := binary.Uvarint(program)
	if vlen <= 0 {
		return errors.New("invalid version")
	}
	if version > EvalMaxVersion {
		return fmt.Errorf("program version %d greater than max supported version %d", version, EvalMaxVersion)
	}
	if version > params.Proto.LogicSigVersion {
		return fmt.Errorf("program version %d greater than protocol supported version %d", version, params.Proto.LogicSigVersion)
	}

	var minVersion uint64
	if params.MinTealVersion == nil {
		minVersion = ComputeMinTealVersion(params.TxnGroup)
	} else {
		minVersion = *params.MinTealVersion
	}
	if version < minVersion {
		return fmt.Errorf("program version must be >= %d for this transaction group, but have version %d", minVersion, version)
	}

	var cx EvalContext
	cx.version = version
	cx.pc = vlen
	cx.EvalParams = params
	cx.program = program
	cx.branchTargets = make(map[int]bool)
	cx.instructionStarts = make(map[int]bool)

	maxCost := params.budget()
	if version >= backBranchEnabledVersion {
		maxCost = math.MaxInt32
	}
	staticCost := 0
	for cx.pc < len(cx.program) {
		prevpc := cx.pc
		stepCost, err := cx.checkStep()
		if err != nil {
			return fmt.Errorf("pc=%3d %w", cx.pc, err)
		}
		staticCost += stepCost
		if staticCost > maxCost {
			return fmt.Errorf("pc=%3d static cost budget of %d exceeded", cx.pc, maxCost)
		}
		if cx.pc <= prevpc {
			// Recall, this is advancing through opcodes
			// without evaluation. It always goes forward,
			// even if we're in v4 and the jump would go
			// back.
			return fmt.Errorf("pc did not advance, stuck at %d", cx.pc)
		}
	}
	return nil
}

func opCompat(expected, got StackType) bool {
	if expected == StackAny {
		return true
	}
	return expected == got
}

func nilToEmpty(x []byte) []byte {
	if x == nil {
		return make([]byte, 0)
	}
	return x
}

func boolToUint(x bool) uint64 {
	if x {
		return 1
	}
	return 0
}

// MaxStackDepth should move to consensus params
const MaxStackDepth = 1000

func (cx *EvalContext) step() {
	opcode := cx.program[cx.pc]
	spec := &opsByOpcode[cx.version][opcode]

	// this check also ensures TEAL versioning: v2 opcodes are not in opsByOpcode[1] array
	if spec.op == nil {
		cx.err = fmt.Errorf("%3d illegal opcode 0x%02x", cx.pc, opcode)
		return
	}
	if (cx.runModeFlags & spec.Modes) == 0 {
		cx.err = fmt.Errorf("%s not allowed in current mode", spec.Name)
		return
	}

	// check args for stack underflow and types
	if len(cx.stack) < len(spec.Args) {
		cx.err = fmt.Errorf("stack underflow in %s", spec.Name)
		return
	}
	first := len(cx.stack) - len(spec.Args)
	for i, argType := range spec.Args {
		if !opCompat(argType, cx.stack[first+i].argType()) {
			cx.err = fmt.Errorf("%s arg %d wanted %s but got %s", spec.Name, i, argType.String(), cx.stack[first+i].typeName())
			return
		}
	}

	deets := spec.Details
	if deets.Size != 0 && (cx.pc+deets.Size > len(cx.program)) {
		cx.err = fmt.Errorf("%3d %s program ends short of immediate values", cx.pc, spec.Name)
		return
	}
	cx.cost += deets.Cost
	if cx.cost > cx.budget() {
		cx.err = fmt.Errorf("pc=%3d dynamic cost budget exceeded, executing %s: remaining budget is %d but program cost was %d",
			cx.pc, spec.Name, cx.budget(), cx.cost)
		return
	}

	preheight := len(cx.stack)
	spec.op(cx)

	if cx.err == nil {
		postheight := len(cx.stack)
		if spec.Name != "return" && postheight-preheight != len(spec.Returns)-len(spec.Args) {
			cx.err = fmt.Errorf("%s changed stack height improperly %d != %d",
				spec.Name, postheight-preheight, len(spec.Returns)-len(spec.Args))
			return
		}
		first = postheight - len(spec.Returns)
		for i, argType := range spec.Returns {
			stackType := cx.stack[first+i].argType()
			if !opCompat(argType, stackType) {
				cx.err = fmt.Errorf("%s produced %s but intended %s", spec.Name, cx.stack[first+i].typeName(), argType.String())
				return
			}
			if stackType == StackBytes && len(cx.stack[first+i].Bytes) > MaxStringSize {
				cx.err = fmt.Errorf("%s produced a too big (%d) byte-array", spec.Name, len(cx.stack[first+i].Bytes))
				return
			}
		}
	}

	if cx.Trace != nil {
		// This code used to do a little disassembly on its
		// own, but then it missed out on some nuances like
		// getting the field names instead of constants in the
		// txn opcodes.  To get them, we conjure up a
		// disassembleState from the current execution state,
		// and use the existing disassembly routines.  It
		// feels a little funny to make a disassembleState
		// right here, rather than build it as we go, or
		// perhaps we could have an interface that allows
		// disassembly to use the cx directly.  But for now,
		// we don't want to worry about the dissassembly
		// routines mucking about in the execution context
		// (changing the pc, for example) and this gives a big
		// improvement of dryrun readability
		dstate := &disassembleState{program: cx.program, pc: cx.pc, numericTargets: true, intc: cx.intc, bytec: cx.bytec}
		var sourceLine string
		sourceLine, err := spec.dis(dstate, spec)
		if err != nil {
			if cx.err == nil { // don't override an error from evaluation
				cx.err = err
			}
			return
		}
		var stackString string
		if len(cx.stack) == 0 {
			stackString = "<empty stack>"
		} else {
			num := 1
			if len(spec.Returns) > 1 {
				num = len(spec.Returns)
			}
			// check for nil error here, because we might not return
			// values if we encounter an error in the opcode
			if cx.err == nil {
				if len(cx.stack) < num {
					cx.err = fmt.Errorf("stack underflow: expected %d, have %d", num, len(cx.stack))
					return
				}
				for i := 1; i <= num; i++ {
					stackString += fmt.Sprintf("(%s) ", cx.stack[len(cx.stack)-i].String())
				}
			}
		}
		fmt.Fprintf(cx.Trace, "%3d %s => %s\n", cx.pc, sourceLine, stackString)
	}
	if cx.err != nil {
		return
	}

	if len(cx.stack) > MaxStackDepth {
		cx.err = errors.New("stack overflow")
		return
	}
	if cx.nextpc != 0 {
		cx.pc = cx.nextpc
		cx.nextpc = 0
	} else {
		cx.pc += deets.Size
	}
}

func (cx *EvalContext) checkStep() (int, error) {
	cx.instructionStarts[cx.pc] = true
	opcode := cx.program[cx.pc]
	spec := &opsByOpcode[cx.version][opcode]
	if spec.op == nil {
		return 0, fmt.Errorf("%3d illegal opcode 0x%02x", cx.pc, opcode)
	}
	if (cx.runModeFlags & spec.Modes) == 0 {
		return 0, fmt.Errorf("%s not allowed in current mode", spec.Name)
	}
	deets := spec.Details
	if deets.Size != 0 && (cx.pc+deets.Size > len(cx.program)) {
		return 0, fmt.Errorf("%3d %s program ends short of immediate values", cx.pc, spec.Name)
	}
	prevpc := cx.pc
	if deets.checkFunc != nil {
		err := deets.checkFunc(cx)
		if err != nil {
			return 0, err
		}
		if cx.nextpc != 0 {
			cx.pc = cx.nextpc
			cx.nextpc = 0
		} else {
			cx.pc += deets.Size
		}
	} else {
		cx.pc += deets.Size
	}
	if cx.Trace != nil {
		fmt.Fprintf(cx.Trace, "%3d %s\n", prevpc, spec.Name)
	}
	if cx.err == nil {
		for pc := prevpc + 1; pc < cx.pc; pc++ {
			if _, ok := cx.branchTargets[pc]; ok {
				return 0, fmt.Errorf("branch target %d is not an aligned instruction", pc)
			}
		}
	}
	return deets.Cost, nil
}

func opErr(cx *EvalContext) {
	cx.err = errors.New("TEAL runtime encountered err opcode")
}

func opReturn(cx *EvalContext) {
	// Achieve the end condition:
	// Take the last element on the stack and make it the return value (only element on the stack)
	// Move the pc to the end of the program
	last := len(cx.stack) - 1
	cx.stack[0] = cx.stack[last]
	cx.stack = cx.stack[:1]
	cx.nextpc = len(cx.program)
}

func opAssert(cx *EvalContext) {
	last := len(cx.stack) - 1
	if cx.stack[last].Uint != 0 {
		cx.stack = cx.stack[:last]
		return
	}
	cx.err = fmt.Errorf("assert failed pc=%d", cx.pc)
}

func opSwap(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	cx.stack[last], cx.stack[prev] = cx.stack[prev], cx.stack[last]
}

func opSelect(cx *EvalContext) {
	last := len(cx.stack) - 1 // condition on top
	prev := last - 1          // true is one down
	pprev := prev - 1         // false below that

	if cx.stack[last].Uint != 0 {
		cx.stack[pprev] = cx.stack[prev]
	}
	cx.stack = cx.stack[:prev]
}

func opSHA256(cx *EvalContext) {
	last := len(cx.stack) - 1
	hash := sha256.Sum256(cx.stack[last].Bytes)
	cx.stack[last].Bytes = hash[:]
}

// The Keccak256 variant of SHA-3 is implemented for compatibility with Ethereum
func opKeccak256(cx *EvalContext) {
	last := len(cx.stack) - 1
	hasher := sha3.NewLegacyKeccak256()
	hasher.Write(cx.stack[last].Bytes)
	hv := make([]byte, 0, hasher.Size())
	hv = hasher.Sum(hv)
	cx.stack[last].Bytes = hv
}

// This is the hash commonly used in Algorand in crypto/util.go Hash()
//
// It is explicitly implemented here in terms of the specific hash for
// stability and portability in case the rest of Algorand ever moves
// to a different default hash. For stability of this language, at
// that time a new opcode should be made with the new hash.
func opSHA512_256(cx *EvalContext) {
	last := len(cx.stack) - 1
	hash := sha512.Sum512_256(cx.stack[last].Bytes)
	cx.stack[last].Bytes = hash[:]
}

func opPlus(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	sum, carry := bits.Add64(cx.stack[prev].Uint, cx.stack[last].Uint, 0)
	if carry > 0 {
		cx.err = errors.New("+ overflowed")
		return
	}
	cx.stack[prev].Uint = sum
	cx.stack = cx.stack[:last]
}

func opAddw(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	sum, carry := bits.Add64(cx.stack[prev].Uint, cx.stack[last].Uint, 0)
	cx.stack[prev].Uint = carry
	cx.stack[last].Uint = sum
}

func uint128(hi uint64, lo uint64) *big.Int {
	whole := new(big.Int).SetUint64(hi)
	whole.Lsh(whole, 64)
	whole.Add(whole, new(big.Int).SetUint64(lo))
	return whole
}

func opDivModwImpl(hiNum, loNum, hiDen, loDen uint64) (hiQuo uint64, loQuo uint64, hiRem uint64, loRem uint64) {
	dividend := uint128(hiNum, loNum)
	divisor := uint128(hiDen, loDen)

	quo, rem := new(big.Int).QuoRem(dividend, divisor, new(big.Int))
	return new(big.Int).Rsh(quo, 64).Uint64(),
		quo.Uint64(),
		new(big.Int).Rsh(rem, 64).Uint64(),
		rem.Uint64()
}

func opDivModw(cx *EvalContext) {
	loDen := len(cx.stack) - 1
	hiDen := loDen - 1
	if cx.stack[loDen].Uint == 0 && cx.stack[hiDen].Uint == 0 {
		cx.err = errors.New("/ 0")
		return
	}
	loNum := loDen - 2
	hiNum := loDen - 3
	hiQuo, loQuo, hiRem, loRem :=
		opDivModwImpl(cx.stack[hiNum].Uint, cx.stack[loNum].Uint, cx.stack[hiDen].Uint, cx.stack[loDen].Uint)
	cx.stack[hiNum].Uint = hiQuo
	cx.stack[loNum].Uint = loQuo
	cx.stack[hiDen].Uint = hiRem
	cx.stack[loDen].Uint = loRem
}

func opMinus(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	if cx.stack[last].Uint > cx.stack[prev].Uint {
		cx.err = errors.New("- would result negative")
		return
	}
	cx.stack[prev].Uint -= cx.stack[last].Uint
	cx.stack = cx.stack[:last]
}

func opDiv(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	if cx.stack[last].Uint == 0 {
		cx.err = errors.New("/ 0")
		return
	}
	cx.stack[prev].Uint /= cx.stack[last].Uint
	cx.stack = cx.stack[:last]
}

func opModulo(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	if cx.stack[last].Uint == 0 {
		cx.err = errors.New("% 0")
		return
	}
	cx.stack[prev].Uint = cx.stack[prev].Uint % cx.stack[last].Uint
	cx.stack = cx.stack[:last]
}

func opMul(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	high, low := bits.Mul64(cx.stack[prev].Uint, cx.stack[last].Uint)
	if high > 0 {
		cx.err = errors.New("* overflowed")
		return
	}
	cx.stack[prev].Uint = low
	cx.stack = cx.stack[:last]
}

func opMulw(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	high, low := bits.Mul64(cx.stack[prev].Uint, cx.stack[last].Uint)
	cx.stack[prev].Uint = high
	cx.stack[last].Uint = low
}

func opLt(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	cond := cx.stack[prev].Uint < cx.stack[last].Uint
	if cond {
		cx.stack[prev].Uint = 1
	} else {
		cx.stack[prev].Uint = 0
	}
	cx.stack = cx.stack[:last]
}

func opGt(cx *EvalContext) {
	opSwap(cx)
	opLt(cx)
}

func opLe(cx *EvalContext) {
	opGt(cx)
	opNot(cx)
}

func opGe(cx *EvalContext) {
	opLt(cx)
	opNot(cx)
}

func opAnd(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	cond := (cx.stack[prev].Uint != 0) && (cx.stack[last].Uint != 0)
	if cond {
		cx.stack[prev].Uint = 1
	} else {
		cx.stack[prev].Uint = 0
	}
	cx.stack = cx.stack[:last]
}

func opOr(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	cond := (cx.stack[prev].Uint != 0) || (cx.stack[last].Uint != 0)
	if cond {
		cx.stack[prev].Uint = 1
	} else {
		cx.stack[prev].Uint = 0
	}
	cx.stack = cx.stack[:last]
}

func opEq(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	ta := cx.stack[prev].argType()
	tb := cx.stack[last].argType()
	if ta != tb {
		cx.err = fmt.Errorf("cannot compare (%s to %s)", cx.stack[prev].typeName(), cx.stack[last].typeName())
		return
	}
	var cond bool
	if ta == StackBytes {
		cond = bytes.Equal(cx.stack[prev].Bytes, cx.stack[last].Bytes)
	} else {
		cond = cx.stack[prev].Uint == cx.stack[last].Uint
	}
	if cond {
		cx.stack[prev].Uint = 1
	} else {
		cx.stack[prev].Uint = 0
	}
	cx.stack[prev].Bytes = nil
	cx.stack = cx.stack[:last]
}

func opNeq(cx *EvalContext) {
	opEq(cx)
	opNot(cx)
}

func opNot(cx *EvalContext) {
	last := len(cx.stack) - 1
	cond := cx.stack[last].Uint == 0
	if cond {
		cx.stack[last].Uint = 1
	} else {
		cx.stack[last].Uint = 0
	}
}

func opLen(cx *EvalContext) {
	last := len(cx.stack) - 1
	cx.stack[last].Uint = uint64(len(cx.stack[last].Bytes))
	cx.stack[last].Bytes = nil
}

func opItob(cx *EvalContext) {
	last := len(cx.stack) - 1
	ibytes := make([]byte, 8)
	binary.BigEndian.PutUint64(ibytes, cx.stack[last].Uint)
	// cx.stack[last].Uint is not cleared out as optimization
	// stackValue.argType() checks Bytes field first
	cx.stack[last].Bytes = ibytes
}

func opBtoi(cx *EvalContext) {
	last := len(cx.stack) - 1
	ibytes := cx.stack[last].Bytes
	if len(ibytes) > 8 {
		cx.err = fmt.Errorf("btoi arg too long, got [%d]bytes", len(ibytes))
		return
	}
	value := uint64(0)
	for _, b := range ibytes {
		value = value << 8
		value = value | (uint64(b) & 0x0ff)
	}
	cx.stack[last].Uint = value
	cx.stack[last].Bytes = nil
}

func opBitOr(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	cx.stack[prev].Uint = cx.stack[prev].Uint | cx.stack[last].Uint
	cx.stack = cx.stack[:last]
}

func opBitAnd(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	cx.stack[prev].Uint = cx.stack[prev].Uint & cx.stack[last].Uint
	cx.stack = cx.stack[:last]
}

func opBitXor(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	cx.stack[prev].Uint = cx.stack[prev].Uint ^ cx.stack[last].Uint
	cx.stack = cx.stack[:last]
}

func opBitNot(cx *EvalContext) {
	last := len(cx.stack) - 1
	cx.stack[last].Uint = cx.stack[last].Uint ^ 0xffffffffffffffff
}

func opShiftLeft(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	if cx.stack[last].Uint > 63 {
		cx.err = fmt.Errorf("shl arg too big, (%d)", cx.stack[last].Uint)
		return
	}
	cx.stack[prev].Uint = cx.stack[prev].Uint << cx.stack[last].Uint
	cx.stack = cx.stack[:last]
}

func opShiftRight(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	if cx.stack[last].Uint > 63 {
		cx.err = fmt.Errorf("shr arg too big, (%d)", cx.stack[last].Uint)
		return
	}
	cx.stack[prev].Uint = cx.stack[prev].Uint >> cx.stack[last].Uint
	cx.stack = cx.stack[:last]
}

func opSqrt(cx *EvalContext) {
	/*
		        It would not be safe to use math.Sqrt, because we would have to
			convert our u64 to an f64, but f64 cannot represent all u64s exactly.

			This algorithm comes from Jack W. Crenshaw's 1998 article in Embedded:
			http://www.embedded.com/electronics-blogs/programmer-s-toolbox/4219659/Integer-Square-Roots
	*/

	last := len(cx.stack) - 1

	sq := cx.stack[last].Uint
	var rem uint64 = 0
	var root uint64 = 0

	for i := 0; i < 32; i++ {
		root <<= 1
		rem = (rem << 2) | (sq >> (64 - 2))
		sq <<= 2
		if root < rem {
			rem -= root | 1
			root += 2
		}
	}
	cx.stack[last].Uint = root >> 1
}

func opBitLen(cx *EvalContext) {
	last := len(cx.stack) - 1
	if cx.stack[last].argType() == StackUint64 {
		cx.stack[last].Uint = uint64(bits.Len64(cx.stack[last].Uint))
		return
	}
	length := len(cx.stack[last].Bytes)
	idx := 0
	for i, b := range cx.stack[last].Bytes {
		if b != 0 {
			idx = bits.Len8(b) + (8 * (length - i - 1))
			break
		}

	}
	cx.stack[last].Bytes = nil
	cx.stack[last].Uint = uint64(idx)
}

func opExpImpl(base uint64, exp uint64) (uint64, error) {
	// These checks are slightly repetive but the clarity of
	// avoiding nested checks seems worth it.
	if exp == 0 && base == 0 {
		return 0, errors.New("0^0 is undefined")
	}
	if base == 0 {
		return 0, nil
	}
	if exp == 0 || base == 1 {
		return 1, nil
	}
	// base is now at least 2, so exp can not be 64
	if exp >= 64 {
		return 0, fmt.Errorf("%d^%d overflow", base, exp)
	}
	answer := base
	// safe to cast exp, because it is known to fit in int (it's < 64)
	for i := 1; i < int(exp); i++ {
		next := answer * base
		if next/answer != base {
			return 0, fmt.Errorf("%d^%d overflow", base, exp)
		}
		answer = next
	}
	return answer, nil
}

func opExp(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1

	exp := cx.stack[last].Uint
	base := cx.stack[prev].Uint
	val, err := opExpImpl(base, exp)
	if err != nil {
		cx.err = err
		return
	}
	cx.stack[prev].Uint = val
	cx.stack = cx.stack[:last]
}

func opExpwImpl(base uint64, exp uint64) (*big.Int, error) {
	// These checks are slightly repetive but the clarity of
	// avoiding nested checks seems worth it.
	if exp == 0 && base == 0 {
		return &big.Int{}, errors.New("0^0 is undefined")
	}
	if base == 0 {
		return &big.Int{}, nil
	}
	if exp == 0 || base == 1 {
		return new(big.Int).SetUint64(1), nil
	}
	// base is now at least 2, so exp can not be 128
	if exp >= 128 {
		return &big.Int{}, fmt.Errorf("%d^%d overflow", base, exp)
	}

	answer := new(big.Int).SetUint64(base)
	bigbase := new(big.Int).SetUint64(base)
	// safe to cast exp, because it is known to fit in int (it's < 128)
	for i := 1; i < int(exp); i++ {
		next := answer.Mul(answer, bigbase)
		answer = next
		if answer.BitLen() > 128 {
			return &big.Int{}, fmt.Errorf("%d^%d overflow", base, exp)
		}
	}
	return answer, nil

}

func opExpw(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1

	exp := cx.stack[last].Uint
	base := cx.stack[prev].Uint
	val, err := opExpwImpl(base, exp)
	if err != nil {
		cx.err = err
		return
	}
	hi := new(big.Int).Rsh(val, 64).Uint64()
	lo := val.Uint64()

	cx.stack[prev].Uint = hi
	cx.stack[last].Uint = lo
}

func opBytesBinOp(cx *EvalContext, result *big.Int, op func(x, y *big.Int) *big.Int) {
	last := len(cx.stack) - 1
	prev := last - 1

	if len(cx.stack[last].Bytes) > MaxByteMathSize || len(cx.stack[prev].Bytes) > MaxByteMathSize {
		cx.err = errors.New("math attempted on large byte-array")
		return
	}

	rhs := new(big.Int).SetBytes(cx.stack[last].Bytes)
	lhs := new(big.Int).SetBytes(cx.stack[prev].Bytes)
	op(lhs, rhs) // op's receiver has already been bound to result
	if result.Sign() < 0 {
		cx.err = errors.New("byte math would have negative result")
		return
	}
	cx.stack[prev].Bytes = result.Bytes()
	cx.stack = cx.stack[:last]
}

func opBytesPlus(cx *EvalContext) {
	result := new(big.Int)
	opBytesBinOp(cx, result, result.Add)
}

func opBytesMinus(cx *EvalContext) {
	result := new(big.Int)
	opBytesBinOp(cx, result, result.Sub)
}

func opBytesDiv(cx *EvalContext) {
	result := new(big.Int)
	checkDiv := func(x, y *big.Int) *big.Int {
		if y.BitLen() == 0 {
			cx.err = errors.New("division by zero")
			return new(big.Int)
		}
		return result.Div(x, y)
	}
	opBytesBinOp(cx, result, checkDiv)
}

func opBytesMul(cx *EvalContext) {
	result := new(big.Int)
	opBytesBinOp(cx, result, result.Mul)
}

func opBytesLt(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1

	if len(cx.stack[last].Bytes) > MaxByteMathSize || len(cx.stack[prev].Bytes) > MaxByteMathSize {
		cx.err = errors.New("math attempted on large byte-array")
		return
	}

	rhs := new(big.Int).SetBytes(cx.stack[last].Bytes)
	lhs := new(big.Int).SetBytes(cx.stack[prev].Bytes)
	cx.stack[prev].Bytes = nil
	if lhs.Cmp(rhs) < 0 {
		cx.stack[prev].Uint = 1
	} else {
		cx.stack[prev].Uint = 0
	}
	cx.stack = cx.stack[:last]
}

func opBytesGt(cx *EvalContext) {
	opSwap(cx)
	opBytesLt(cx)
}

func opBytesLe(cx *EvalContext) {
	opBytesGt(cx)
	opNot(cx)
}

func opBytesGe(cx *EvalContext) {
	opBytesLt(cx)
	opNot(cx)
}

func opBytesEq(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1

	if len(cx.stack[last].Bytes) > MaxByteMathSize || len(cx.stack[prev].Bytes) > MaxByteMathSize {
		cx.err = errors.New("math attempted on large byte-array")
		return
	}

	rhs := new(big.Int).SetBytes(cx.stack[last].Bytes)
	lhs := new(big.Int).SetBytes(cx.stack[prev].Bytes)
	cx.stack[prev].Bytes = nil
	if lhs.Cmp(rhs) == 0 {
		cx.stack[prev].Uint = 1
	} else {
		cx.stack[prev].Uint = 0
	}
	cx.stack = cx.stack[:last]
}

func opBytesNeq(cx *EvalContext) {
	opBytesEq(cx)
	opNot(cx)
}

func opBytesModulo(cx *EvalContext) {
	result := new(big.Int)
	checkMod := func(x, y *big.Int) *big.Int {
		if y.BitLen() == 0 {
			cx.err = errors.New("modulo by zero")
			return new(big.Int)
		}
		return result.Mod(x, y)
	}
	opBytesBinOp(cx, result, checkMod)
}

func zpad(smaller []byte, size int) []byte {
	padded := make([]byte, size)
	extra := size - len(smaller)  // how much was added?
	copy(padded[extra:], smaller) // slide original contents to the right
	return padded
}

// Return two slices, representing the top two slices on the stack.
// They can be returned in either order, but the first slice returned
// must be newly allocated, and already in place at the top of stack
// (the original top having been popped).
func opBytesBinaryLogicPrep(cx *EvalContext) ([]byte, []byte) {
	last := len(cx.stack) - 1
	prev := last - 1

	llen := len(cx.stack[last].Bytes)
	plen := len(cx.stack[prev].Bytes)

	var fresh, other []byte
	if llen > plen {
		fresh, other = zpad(cx.stack[prev].Bytes, llen), cx.stack[last].Bytes
	} else {
		fresh, other = zpad(cx.stack[last].Bytes, plen), cx.stack[prev].Bytes
	}
	cx.stack[prev].Bytes = fresh
	cx.stack = cx.stack[:last]
	return fresh, other
}

func opBytesBitOr(cx *EvalContext) {
	a, b := opBytesBinaryLogicPrep(cx)
	for i := range a {
		a[i] = a[i] | b[i]
	}
}

func opBytesBitAnd(cx *EvalContext) {
	a, b := opBytesBinaryLogicPrep(cx)
	for i := range a {
		a[i] = a[i] & b[i]
	}
}

func opBytesBitXor(cx *EvalContext) {
	a, b := opBytesBinaryLogicPrep(cx)
	for i := range a {
		a[i] = a[i] ^ b[i]
	}
}

func opBytesBitNot(cx *EvalContext) {
	last := len(cx.stack) - 1

	fresh := make([]byte, len(cx.stack[last].Bytes))
	for i, b := range cx.stack[last].Bytes {
		fresh[i] = ^b
	}
	cx.stack[last].Bytes = fresh
}

func opBytesZero(cx *EvalContext) {
	last := len(cx.stack) - 1
	length := cx.stack[last].Uint
	if length > MaxStringSize {
		cx.err = fmt.Errorf("bzero attempted to create a too large string")
		return
	}
	cx.stack[last].Bytes = make([]byte, length)
}

func opIntConstBlock(cx *EvalContext) {
	cx.intc, cx.nextpc, cx.err = parseIntcblock(cx.program, cx.pc)
}

func opIntConstN(cx *EvalContext, n uint) {
	if n >= uint(len(cx.intc)) {
		cx.err = fmt.Errorf("intc [%d] beyond %d constants", n, len(cx.intc))
		return
	}
	cx.stack = append(cx.stack, stackValue{Uint: cx.intc[n]})
}
func opIntConstLoad(cx *EvalContext) {
	n := uint(cx.program[cx.pc+1])
	opIntConstN(cx, n)
}
func opIntConst0(cx *EvalContext) {
	opIntConstN(cx, 0)
}
func opIntConst1(cx *EvalContext) {
	opIntConstN(cx, 1)
}
func opIntConst2(cx *EvalContext) {
	opIntConstN(cx, 2)
}
func opIntConst3(cx *EvalContext) {
	opIntConstN(cx, 3)
}

func opPushInt(cx *EvalContext) {
	val, bytesUsed := binary.Uvarint(cx.program[cx.pc+1:])
	if bytesUsed <= 0 {
		cx.err = fmt.Errorf("could not decode int at pc=%d", cx.pc+1)
		return
	}
	sv := stackValue{Uint: val}
	cx.stack = append(cx.stack, sv)
	cx.nextpc = cx.pc + 1 + bytesUsed
}

func opByteConstBlock(cx *EvalContext) {
	cx.bytec, cx.nextpc, cx.err = parseBytecBlock(cx.program, cx.pc)
}

func opByteConstN(cx *EvalContext, n uint) {
	if n >= uint(len(cx.bytec)) {
		cx.err = fmt.Errorf("bytec [%d] beyond %d constants", n, len(cx.bytec))
		return
	}
	cx.stack = append(cx.stack, stackValue{Bytes: cx.bytec[n]})
}
func opByteConstLoad(cx *EvalContext) {
	n := uint(cx.program[cx.pc+1])
	opByteConstN(cx, n)
}
func opByteConst0(cx *EvalContext) {
	opByteConstN(cx, 0)
}
func opByteConst1(cx *EvalContext) {
	opByteConstN(cx, 1)
}
func opByteConst2(cx *EvalContext) {
	opByteConstN(cx, 2)
}
func opByteConst3(cx *EvalContext) {
	opByteConstN(cx, 3)
}

func opPushBytes(cx *EvalContext) {
	pos := cx.pc + 1
	length, bytesUsed := binary.Uvarint(cx.program[pos:])
	if bytesUsed <= 0 {
		cx.err = fmt.Errorf("could not decode length at pc=%d", pos)
		return
	}
	pos += bytesUsed
	end := uint64(pos) + length
	if end > uint64(len(cx.program)) || end < uint64(pos) {
		cx.err = fmt.Errorf("pushbytes too long at pc=%d", pos)
		return
	}
	sv := stackValue{Bytes: cx.program[pos:end]}
	cx.stack = append(cx.stack, sv)
	cx.nextpc = int(end)
}

func opArgN(cx *EvalContext, n uint64) {
	if n >= uint64(len(cx.Txn.Lsig.Args)) {
		cx.err = fmt.Errorf("cannot load arg[%d] of %d", n, len(cx.Txn.Lsig.Args))
		return
	}
	val := nilToEmpty(cx.Txn.Lsig.Args[n])
	cx.stack = append(cx.stack, stackValue{Bytes: val})
}

func opArg(cx *EvalContext) {
	n := uint64(cx.program[cx.pc+1])
	opArgN(cx, n)
}
func opArg0(cx *EvalContext) {
	opArgN(cx, 0)
}
func opArg1(cx *EvalContext) {
	opArgN(cx, 1)
}
func opArg2(cx *EvalContext) {
	opArgN(cx, 2)
}
func opArg3(cx *EvalContext) {
	opArgN(cx, 3)
}
func opArgs(cx *EvalContext) {
	last := len(cx.stack) - 1
	n := cx.stack[last].Uint
	// Pop the index and push the result back on the stack.
	cx.stack = cx.stack[:last]
	opArgN(cx, n)
}

func branchTarget(cx *EvalContext) (int, error) {
	offset := int16(uint16(cx.program[cx.pc+1])<<8 | uint16(cx.program[cx.pc+2]))
	if offset < 0 && cx.version < backBranchEnabledVersion {
		return 0, fmt.Errorf("negative branch offset %x", offset)
	}
	target := cx.pc + 3 + int(offset)
	var branchTooFar bool
	if cx.version >= 2 {
		// branching to exactly the end of the program (target == len(cx.program)), the next pc after the last instruction, is okay and ends normally
		branchTooFar = target > len(cx.program) || target < 0
	} else {
		branchTooFar = target >= len(cx.program) || target < 0
	}
	if branchTooFar {
		return 0, errors.New("branch target beyond end of program")
	}

	return target, nil
}

// checks any branch that is {op} {int16 be offset}
func checkBranch(cx *EvalContext) error {
	cx.nextpc = cx.pc + 3
	target, err := branchTarget(cx)
	if err != nil {
		return err
	}
	if target < cx.nextpc {
		// If a branch goes backwards, we should have already noted that an instruction began at that location.
		if _, ok := cx.instructionStarts[target]; !ok {
			return fmt.Errorf("back branch target %d is not an aligned instruction", target)
		}
	}
	cx.branchTargets[target] = true
	return nil
}
func opBnz(cx *EvalContext) {
	last := len(cx.stack) - 1
	cx.nextpc = cx.pc + 3
	isNonZero := cx.stack[last].Uint != 0
	cx.stack = cx.stack[:last] // pop
	if isNonZero {
		target, err := branchTarget(cx)
		if err != nil {
			cx.err = err
			return
		}
		cx.nextpc = target
	}
}

func opBz(cx *EvalContext) {
	last := len(cx.stack) - 1
	cx.nextpc = cx.pc + 3
	isZero := cx.stack[last].Uint == 0
	cx.stack = cx.stack[:last] // pop
	if isZero {
		target, err := branchTarget(cx)
		if err != nil {
			cx.err = err
			return
		}
		cx.nextpc = target
	}
}

func opB(cx *EvalContext) {
	target, err := branchTarget(cx)
	if err != nil {
		cx.err = err
		return
	}
	cx.nextpc = target
}

func opCallSub(cx *EvalContext) {
	cx.callstack = append(cx.callstack, cx.pc+3)
	opB(cx)
}

func opRetSub(cx *EvalContext) {
	top := len(cx.callstack) - 1
	if top < 0 {
		cx.err = errors.New("retsub with empty callstack")
		return
	}
	target := cx.callstack[top]
	cx.callstack = cx.callstack[:top]
	cx.nextpc = target
}

func opPop(cx *EvalContext) {
	last := len(cx.stack) - 1
	cx.stack = cx.stack[:last]
}

func opDup(cx *EvalContext) {
	last := len(cx.stack) - 1
	sv := cx.stack[last]
	cx.stack = append(cx.stack, sv)
}

func opDup2(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	cx.stack = append(cx.stack, cx.stack[prev:]...)
}

func opDig(cx *EvalContext) {
	depth := int(uint(cx.program[cx.pc+1]))
	idx := len(cx.stack) - 1 - depth
	// Need to check stack size explicitly here because checkArgs() doesn't understand dig
	// so we can't expect our stack to be prechecked.
	if idx < 0 {
		cx.err = fmt.Errorf("dig %d with stack size = %d", depth, len(cx.stack))
		return
	}
	sv := cx.stack[idx]
	cx.stack = append(cx.stack, sv)
}

func opCover(cx *EvalContext) {
	depth := int(cx.program[cx.pc+1])
	topIdx := len(cx.stack) - 1
	idx := topIdx - depth
	// Need to check stack size explicitly here because checkArgs() doesn't understand cover
	// so we can't expect our stack to be prechecked.
	if idx < 0 {
		cx.err = fmt.Errorf("cover %d with stack size = %d", depth, len(cx.stack))
		return
	}
	sv := cx.stack[topIdx]
	copy(cx.stack[idx+1:], cx.stack[idx:])
	cx.stack[idx] = sv
}

func opUncover(cx *EvalContext) {
	depth := int(cx.program[cx.pc+1])
	topIdx := len(cx.stack) - 1
	idx := topIdx - depth
	// Need to check stack size explicitly here because checkArgs() doesn't understand uncover
	// so we can't expect our stack to be prechecked.
	if idx < 0 {
		cx.err = fmt.Errorf("uncover %d with stack size = %d", depth, len(cx.stack))
		return
	}

	sv := cx.stack[idx]
	copy(cx.stack[idx:], cx.stack[idx+1:])
	cx.stack[topIdx] = sv
}

func (cx *EvalContext) assetHoldingToValue(holding *basics.AssetHolding, fs assetHoldingFieldSpec) (sv stackValue, err error) {
	switch fs.field {
	case AssetBalance:
		sv.Uint = holding.Amount
	case AssetFrozen:
		sv.Uint = boolToUint(holding.Frozen)
	default:
		err = fmt.Errorf("invalid asset_holding_get field %d", fs.field)
		return
	}

	if !typecheck(fs.ftype, sv.argType()) {
		err = fmt.Errorf("%s expected field type is %s but got %s", fs.field.String(), fs.ftype.String(), sv.argType().String())
	}
	return
}

func (cx *EvalContext) assetParamsToValue(params *basics.AssetParams, creator basics.Address, fs assetParamsFieldSpec) (sv stackValue, err error) {
	switch fs.field {
	case AssetTotal:
		sv.Uint = params.Total
	case AssetDecimals:
		sv.Uint = uint64(params.Decimals)
	case AssetDefaultFrozen:
		sv.Uint = boolToUint(params.DefaultFrozen)
	case AssetUnitName:
		sv.Bytes = []byte(params.UnitName)
	case AssetName:
		sv.Bytes = []byte(params.AssetName)
	case AssetURL:
		sv.Bytes = []byte(params.URL)
	case AssetMetadataHash:
		sv.Bytes = params.MetadataHash[:]
	case AssetManager:
		sv.Bytes = params.Manager[:]
	case AssetReserve:
		sv.Bytes = params.Reserve[:]
	case AssetFreeze:
		sv.Bytes = params.Freeze[:]
	case AssetClawback:
		sv.Bytes = params.Clawback[:]
	case AssetCreator:
		sv.Bytes = creator[:]
	default:
		err = fmt.Errorf("invalid asset_params_get field %d", fs.field)
		return
	}

	if !typecheck(fs.ftype, sv.argType()) {
		err = fmt.Errorf("%s expected field type is %s but got %s", fs.field.String(), fs.ftype.String(), sv.argType().String())
	}
	return
}

func (cx *EvalContext) appParamsToValue(params *basics.AppParams, fs appParamsFieldSpec) (sv stackValue, err error) {
	switch fs.field {
	case AppApprovalProgram:
		sv.Bytes = params.ApprovalProgram[:]
	case AppClearStateProgram:
		sv.Bytes = params.ClearStateProgram[:]
	case AppGlobalNumUint:
		sv.Uint = params.GlobalStateSchema.NumUint
	case AppGlobalNumByteSlice:
		sv.Uint = params.GlobalStateSchema.NumByteSlice
	case AppLocalNumUint:
		sv.Uint = params.LocalStateSchema.NumUint
	case AppLocalNumByteSlice:
		sv.Uint = params.LocalStateSchema.NumByteSlice
	case AppExtraProgramPages:
		sv.Uint = uint64(params.ExtraProgramPages)
	default:
		// The pseudo fields AppCreator and AppAddress are handled before this method
		err = fmt.Errorf("invalid app_params_get field %d", fs.field)
		return
	}

	if !typecheck(fs.ftype, sv.argType()) {
		err = fmt.Errorf("%s expected field type is %s but got %s", fs.field.String(), fs.ftype.String(), sv.argType().String())
	}
	return
}

// TxnFieldToTealValue is a thin wrapper for txnFieldToStack for external use
func TxnFieldToTealValue(txn *transactions.Transaction, groupIndex int, field TxnField, arrayFieldIdx uint64) (basics.TealValue, error) {
	if groupIndex < 0 {
		return basics.TealValue{}, fmt.Errorf("negative groupIndex %d", groupIndex)
	}
	cx := EvalContext{EvalParams: EvalParams{GroupIndex: uint64(groupIndex)}}
	fs := txnFieldSpecByField[field]
	sv, err := cx.txnFieldToStack(txn, fs, arrayFieldIdx, uint64(groupIndex))
	return sv.toTealValue(), err
}

func (cx *EvalContext) getTxID(txn *transactions.Transaction, groupIndex uint64) transactions.Txid {
	// Initialize txidCache if necessary
	if cx.txidCache == nil {
		cx.txidCache = make(map[uint64]transactions.Txid, len(cx.TxnGroup))
	}

	// Hashes are expensive, so we cache computed TxIDs
	txid, ok := cx.txidCache[groupIndex]
	if !ok {
		txid = txn.ID()
		cx.txidCache[groupIndex] = txid
	}

	return txid
}

func (cx *EvalContext) itxnFieldToStack(itxn *transactions.SignedTxnWithAD, fs txnFieldSpec, arrayFieldIdx uint64) (sv stackValue, err error) {
	if fs.effects {
		switch fs.field {
		case Logs:
			if arrayFieldIdx >= uint64(len(itxn.EvalDelta.Logs)) {
				err = fmt.Errorf("invalid Logs index %d", arrayFieldIdx)
				return
			}
			sv.Bytes = nilToEmpty([]byte(itxn.EvalDelta.Logs[arrayFieldIdx]))
		case NumLogs:
			sv.Uint = uint64(len(itxn.EvalDelta.Logs))
		case CreatedAssetID:
			sv.Uint = uint64(itxn.ApplyData.ConfigAsset)
		case CreatedApplicationID:
			sv.Uint = uint64(itxn.ApplyData.ApplicationID)
		default:
			err = fmt.Errorf("invalid txn field %d", fs.field)
		}
		return
	}

	if fs.field == GroupIndex || fs.field == TxID {
		err = fmt.Errorf("illegal field for inner transaction %s", fs.field)
	} else {
		sv, err = cx.txnFieldToStack(&itxn.Txn, fs, arrayFieldIdx, 0)
	}
	return
}

func (cx *EvalContext) txnFieldToStack(txn *transactions.Transaction, fs txnFieldSpec, arrayFieldIdx uint64, groupIndex uint64) (sv stackValue, err error) {
	if fs.effects {
		return sv, errors.New("Unable to obtain effects from top-level transactions")
	}
	err = nil
	switch fs.field {
	case Sender:
		sv.Bytes = txn.Sender[:]
	case Fee:
		sv.Uint = txn.Fee.Raw
	case FirstValid:
		sv.Uint = uint64(txn.FirstValid)
	case LastValid:
		sv.Uint = uint64(txn.LastValid)
	case Note:
		sv.Bytes = nilToEmpty(txn.Note)
	case Receiver:
		sv.Bytes = txn.Receiver[:]
	case Amount:
		sv.Uint = txn.Amount.Raw
	case CloseRemainderTo:
		sv.Bytes = txn.CloseRemainderTo[:]
	case VotePK:
		sv.Bytes = txn.VotePK[:]
	case SelectionPK:
		sv.Bytes = txn.SelectionPK[:]
	case VoteFirst:
		sv.Uint = uint64(txn.VoteFirst)
	case VoteLast:
		sv.Uint = uint64(txn.VoteLast)
	case VoteKeyDilution:
		sv.Uint = txn.VoteKeyDilution
	case Nonparticipation:
		sv.Uint = boolToUint(txn.Nonparticipation)
	case Type:
		sv.Bytes = []byte(txn.Type)
	case TypeEnum:
		sv.Uint = txnTypeIndexes[string(txn.Type)]
	case XferAsset:
		sv.Uint = uint64(txn.XferAsset)
	case AssetAmount:
		sv.Uint = txn.AssetAmount
	case AssetSender:
		sv.Bytes = txn.AssetSender[:]
	case AssetReceiver:
		sv.Bytes = txn.AssetReceiver[:]
	case AssetCloseTo:
		sv.Bytes = txn.AssetCloseTo[:]
	case GroupIndex:
		sv.Uint = groupIndex
	case TxID:
		txid := cx.getTxID(txn, groupIndex)
		sv.Bytes = txid[:]
	case Lease:
		sv.Bytes = txn.Lease[:]
	case ApplicationID:
		sv.Uint = uint64(txn.ApplicationID)
	case OnCompletion:
		sv.Uint = uint64(txn.OnCompletion)

	case ApplicationArgs:
		if arrayFieldIdx >= uint64(len(txn.ApplicationArgs)) {
			err = fmt.Errorf("invalid ApplicationArgs index %d", arrayFieldIdx)
			return
		}
		sv.Bytes = nilToEmpty(txn.ApplicationArgs[arrayFieldIdx])
	case NumAppArgs:
		sv.Uint = uint64(len(txn.ApplicationArgs))

	case Accounts:
		if arrayFieldIdx == 0 {
			// special case: sender
			sv.Bytes = txn.Sender[:]
		} else {
			if arrayFieldIdx > uint64(len(txn.Accounts)) {
				err = fmt.Errorf("invalid Accounts index %d", arrayFieldIdx)
				return
			}
			sv.Bytes = txn.Accounts[arrayFieldIdx-1][:]
		}
	case NumAccounts:
		sv.Uint = uint64(len(txn.Accounts))

	case Assets:
		if arrayFieldIdx >= uint64(len(txn.ForeignAssets)) {
			err = fmt.Errorf("invalid Assets index %d", arrayFieldIdx)
			return
		}
		sv.Uint = uint64(txn.ForeignAssets[arrayFieldIdx])
	case NumAssets:
		sv.Uint = uint64(len(txn.ForeignAssets))

	case Applications:
		if arrayFieldIdx == 0 {
			// special case: current app id
			sv.Uint = uint64(txn.ApplicationID)
		} else {
			if arrayFieldIdx > uint64(len(txn.ForeignApps)) {
				err = fmt.Errorf("invalid Applications index %d", arrayFieldIdx)
				return
			}
			sv.Uint = uint64(txn.ForeignApps[arrayFieldIdx-1])
		}
	case NumApplications:
		sv.Uint = uint64(len(txn.ForeignApps))

	case GlobalNumUint:
		sv.Uint = uint64(txn.GlobalStateSchema.NumUint)
	case GlobalNumByteSlice:
		sv.Uint = uint64(txn.GlobalStateSchema.NumByteSlice)

	case LocalNumUint:
		sv.Uint = uint64(txn.LocalStateSchema.NumUint)
	case LocalNumByteSlice:
		sv.Uint = uint64(txn.LocalStateSchema.NumByteSlice)

	case ApprovalProgram:
		sv.Bytes = nilToEmpty(txn.ApprovalProgram)
	case ClearStateProgram:
		sv.Bytes = nilToEmpty(txn.ClearStateProgram)
	case RekeyTo:
		sv.Bytes = txn.RekeyTo[:]
	case ConfigAsset:
		sv.Uint = uint64(txn.ConfigAsset)
	case ConfigAssetTotal:
		sv.Uint = uint64(txn.AssetParams.Total)
	case ConfigAssetDecimals:
		sv.Uint = uint64(txn.AssetParams.Decimals)
	case ConfigAssetDefaultFrozen:
		sv.Uint = boolToUint(txn.AssetParams.DefaultFrozen)
	case ConfigAssetUnitName:
		sv.Bytes = nilToEmpty([]byte(txn.AssetParams.UnitName))
	case ConfigAssetName:
		sv.Bytes = nilToEmpty([]byte(txn.AssetParams.AssetName))
	case ConfigAssetURL:
		sv.Bytes = nilToEmpty([]byte(txn.AssetParams.URL))
	case ConfigAssetMetadataHash:
		sv.Bytes = nilToEmpty(txn.AssetParams.MetadataHash[:])
	case ConfigAssetManager:
		sv.Bytes = txn.AssetParams.Manager[:]
	case ConfigAssetReserve:
		sv.Bytes = txn.AssetParams.Reserve[:]
	case ConfigAssetFreeze:
		sv.Bytes = txn.AssetParams.Freeze[:]
	case ConfigAssetClawback:
		sv.Bytes = txn.AssetParams.Clawback[:]
	case FreezeAsset:
		sv.Uint = uint64(txn.FreezeAsset)
	case FreezeAssetAccount:
		sv.Bytes = txn.FreezeAccount[:]
	case FreezeAssetFrozen:
		sv.Uint = boolToUint(txn.AssetFrozen)
	case ExtraProgramPages:
		sv.Uint = uint64(txn.ExtraProgramPages)
	default:
		err = fmt.Errorf("invalid txn field %d", fs.field)
		return
	}

	txnFieldType := TxnFieldTypes[fs.field]
	if !typecheck(txnFieldType, sv.argType()) {
		err = fmt.Errorf("%s expected field type is %s but got %s", fs.field.String(), txnFieldType.String(), sv.argType().String())
	}
	return
}

func opTxn(cx *EvalContext) {
	field := TxnField(cx.program[cx.pc+1])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	_, ok = txnaFieldSpecByField[field]
	if ok {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	sv, err := cx.txnFieldToStack(&cx.Txn.Txn, fs, 0, cx.GroupIndex)
	if err != nil {
		cx.err = err
		return
	}
	cx.stack = append(cx.stack, sv)
}

func opTxna(cx *EvalContext) {
	field := TxnField(cx.program[cx.pc+1])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	_, ok = txnaFieldSpecByField[field]
	if !ok {
		cx.err = fmt.Errorf("txna unsupported field %d", field)
		return
	}
	arrayFieldIdx := uint64(cx.program[cx.pc+2])
	sv, err := cx.txnFieldToStack(&cx.Txn.Txn, fs, arrayFieldIdx, cx.GroupIndex)
	if err != nil {
		cx.err = err
		return
	}
	cx.stack = append(cx.stack, sv)
}

func opTxnas(cx *EvalContext) {
	last := len(cx.stack) - 1

	field := TxnField(cx.program[cx.pc+1])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	_, ok = txnaFieldSpecByField[field]
	if !ok {
		cx.err = fmt.Errorf("txnas unsupported field %d", field)
		return
	}
	arrayFieldIdx := cx.stack[last].Uint
	sv, err := cx.txnFieldToStack(&cx.Txn.Txn, fs, arrayFieldIdx, cx.GroupIndex)
	if err != nil {
		cx.err = err
		return
	}
	cx.stack[last] = sv
}

func opGtxn(cx *EvalContext) {
	gtxid := cx.program[cx.pc+1]
	if int(gtxid) >= len(cx.TxnGroup) {
		cx.err = fmt.Errorf("gtxn lookup TxnGroup[%d] but it only has %d", gtxid, len(cx.TxnGroup))
		return
	}
	tx := &cx.TxnGroup[gtxid].Txn
	field := TxnField(cx.program[cx.pc+2])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	_, ok = txnaFieldSpecByField[field]
	if ok {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	var sv stackValue
	var err error
	if field == GroupIndex {
		// GroupIndex; asking this when we just specified it is _dumb_, but oh well
		sv.Uint = uint64(gtxid)
	} else {
		sv, err = cx.txnFieldToStack(tx, fs, 0, uint64(gtxid))
		if err != nil {
			cx.err = err
			return
		}
	}
	cx.stack = append(cx.stack, sv)
}

func opGtxna(cx *EvalContext) {
	gtxid := int(uint(cx.program[cx.pc+1]))
	if gtxid >= len(cx.TxnGroup) {
		cx.err = fmt.Errorf("gtxna lookup TxnGroup[%d] but it only has %d", gtxid, len(cx.TxnGroup))
		return
	}
	tx := &cx.TxnGroup[gtxid].Txn
	field := TxnField(cx.program[cx.pc+2])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	_, ok = txnaFieldSpecByField[field]
	if !ok {
		cx.err = fmt.Errorf("gtxna unsupported field %d", field)
		return
	}
	arrayFieldIdx := uint64(cx.program[cx.pc+3])
	sv, err := cx.txnFieldToStack(tx, fs, arrayFieldIdx, uint64(gtxid))
	if err != nil {
		cx.err = err
		return
	}
	cx.stack = append(cx.stack, sv)
}

func opGtxnas(cx *EvalContext) {
	last := len(cx.stack) - 1

	gtxid := cx.program[cx.pc+1]
	if int(gtxid) >= len(cx.TxnGroup) {
		cx.err = fmt.Errorf("gtxnas lookup TxnGroup[%d] but it only has %d", gtxid, len(cx.TxnGroup))
		return
	}
	tx := &cx.TxnGroup[gtxid].Txn
	field := TxnField(cx.program[cx.pc+2])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	_, ok = txnaFieldSpecByField[field]
	if !ok {
		cx.err = fmt.Errorf("gtxnas unsupported field %d", field)
		return
	}
	arrayFieldIdx := cx.stack[last].Uint
	sv, err := cx.txnFieldToStack(tx, fs, arrayFieldIdx, uint64(gtxid))
	if err != nil {
		cx.err = err
		return
	}
	cx.stack[last] = sv
}

func opGtxns(cx *EvalContext) {
	last := len(cx.stack) - 1
	gtxid := cx.stack[last].Uint
	if gtxid >= uint64(len(cx.TxnGroup)) {
		cx.err = fmt.Errorf("gtxns lookup TxnGroup[%d] but it only has %d", gtxid, len(cx.TxnGroup))
		return
	}
	tx := &cx.TxnGroup[gtxid].Txn
	field := TxnField(cx.program[cx.pc+1])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	_, ok = txnaFieldSpecByField[field]
	if ok {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	var sv stackValue
	var err error
	if field == GroupIndex {
		// GroupIndex; asking this when we just specified it is _dumb_, but oh well
		sv.Uint = gtxid
	} else {
		sv, err = cx.txnFieldToStack(tx, fs, 0, gtxid)
		if err != nil {
			cx.err = err
			return
		}
	}
	cx.stack[last] = sv
}

func opGtxnsa(cx *EvalContext) {
	last := len(cx.stack) - 1
	gtxid := cx.stack[last].Uint
	if gtxid >= uint64(len(cx.TxnGroup)) {
		cx.err = fmt.Errorf("gtxnsa lookup TxnGroup[%d] but it only has %d", gtxid, len(cx.TxnGroup))
		return
	}
	tx := &cx.TxnGroup[gtxid].Txn
	field := TxnField(cx.program[cx.pc+1])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	_, ok = txnaFieldSpecByField[field]
	if !ok {
		cx.err = fmt.Errorf("gtxnsa unsupported field %d", field)
		return
	}
	arrayFieldIdx := uint64(cx.program[cx.pc+2])
	sv, err := cx.txnFieldToStack(tx, fs, arrayFieldIdx, gtxid)
	if err != nil {
		cx.err = err
		return
	}
	cx.stack[last] = sv
}

func opGtxnsas(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1

	gtxid := cx.stack[prev].Uint
	if gtxid >= uint64(len(cx.TxnGroup)) {
		cx.err = fmt.Errorf("gtxnsas lookup TxnGroup[%d] but it only has %d", gtxid, len(cx.TxnGroup))
		return
	}
	tx := &cx.TxnGroup[gtxid].Txn
	field := TxnField(cx.program[cx.pc+1])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid txn field %d", field)
		return
	}
	_, ok = txnaFieldSpecByField[field]
	if !ok {
		cx.err = fmt.Errorf("gtxnsas unsupported field %d", field)
		return
	}
	arrayFieldIdx := cx.stack[last].Uint
	sv, err := cx.txnFieldToStack(tx, fs, arrayFieldIdx, gtxid)
	if err != nil {
		cx.err = err
		return
	}
	cx.stack[prev] = sv
	cx.stack = cx.stack[:last]
}

func opItxn(cx *EvalContext) {
	field := TxnField(cx.program[cx.pc+1])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid itxn field %d", field)
		return
	}
	_, ok = txnaFieldSpecByField[field]
	if ok {
		cx.err = fmt.Errorf("invalid itxn field %d", field)
		return
	}

	if len(cx.InnerTxns) == 0 {
		cx.err = fmt.Errorf("no inner transaction available %d", field)
		return
	}

	itxn := &cx.InnerTxns[len(cx.InnerTxns)-1]
	sv, err := cx.itxnFieldToStack(itxn, fs, 0)
	if err != nil {
		cx.err = err
		return
	}
	cx.stack = append(cx.stack, sv)
}

func opItxna(cx *EvalContext) {
	field := TxnField(cx.program[cx.pc+1])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid itxn field %d", field)
		return
	}
	_, ok = txnaFieldSpecByField[field]
	if !ok {
		cx.err = fmt.Errorf("itxna unsupported field %d", field)
		return
	}
	arrayFieldIdx := uint64(cx.program[cx.pc+2])

	if len(cx.InnerTxns) == 0 {
		cx.err = fmt.Errorf("no inner transaction available %d", field)
		return
	}

	itxn := &cx.InnerTxns[len(cx.InnerTxns)-1]
	sv, err := cx.itxnFieldToStack(itxn, fs, arrayFieldIdx)
	if err != nil {
		cx.err = err
		return
	}
	cx.stack = append(cx.stack, sv)
}

func opGaidImpl(cx *EvalContext, groupIdx uint64, opName string) (sv stackValue, err error) {
	if groupIdx >= uint64(len(cx.TxnGroup)) {
		err = fmt.Errorf("%s lookup TxnGroup[%d] but it only has %d", opName, groupIdx, len(cx.TxnGroup))
		return
	} else if groupIdx > cx.GroupIndex {
		err = fmt.Errorf("%s can't get creatable ID of txn ahead of the current one (index %d) in the transaction group", opName, groupIdx)
		return
	} else if groupIdx == cx.GroupIndex {
		err = fmt.Errorf("%s is only for accessing creatable IDs of previous txns, use `global CurrentApplicationID` instead to access the current app's creatable ID", opName)
		return
	} else if txn := cx.TxnGroup[groupIdx].Txn; !(txn.Type == protocol.ApplicationCallTx || txn.Type == protocol.AssetConfigTx) {
		err = fmt.Errorf("can't use %s on txn that is not an app call nor an asset config txn with index %d", opName, groupIdx)
		return
	}

	cid, err := cx.getCreatableID(groupIdx)
	if cid == 0 {
		err = fmt.Errorf("%s can't read creatable ID from txn with group index %d because the txn did not create anything", opName, groupIdx)
		return
	}

	sv = stackValue{
		Uint: cid,
	}
	return
}

func opGaid(cx *EvalContext) {
	groupIdx := cx.program[cx.pc+1]
	sv, err := opGaidImpl(cx, uint64(groupIdx), "gaid")
	if err != nil {
		cx.err = err
		return
	}

	cx.stack = append(cx.stack, sv)
}

func opGaids(cx *EvalContext) {
	last := len(cx.stack) - 1
	groupIdx := cx.stack[last].Uint
	sv, err := opGaidImpl(cx, groupIdx, "gaids")
	if err != nil {
		cx.err = err
		return
	}

	cx.stack[last] = sv
}

func (cx *EvalContext) getRound() (rnd uint64, err error) {
	if cx.Ledger == nil {
		err = fmt.Errorf("ledger not available")
		return
	}
	return uint64(cx.Ledger.Round()), nil
}

func (cx *EvalContext) getLatestTimestamp() (timestamp uint64, err error) {
	if cx.Ledger == nil {
		err = fmt.Errorf("ledger not available")
		return
	}
	ts := cx.Ledger.LatestTimestamp()
	if ts < 0 {
		err = fmt.Errorf("latest timestamp %d < 0", ts)
		return
	}
	return uint64(ts), nil
}

func (cx *EvalContext) getApplicationID() (uint64, error) {
	if cx.Ledger == nil {
		return 0, fmt.Errorf("ledger not available")
	}
	return uint64(cx.Ledger.ApplicationID()), nil
}

func (cx *EvalContext) getApplicationAddress() (basics.Address, error) {
	if cx.Ledger == nil {
		return basics.Address{}, fmt.Errorf("ledger not available")
	}

	// Initialize appAddrCache if necessary
	if cx.appAddrCache == nil {
		cx.appAddrCache = make(map[basics.AppIndex]basics.Address)
	}

	appID := cx.Ledger.ApplicationID()
	// Hashes are expensive, so we cache computed app addrs
	appAddr, ok := cx.appAddrCache[appID]
	if !ok {
		appAddr = appID.Address()
		cx.appAddrCache[appID] = appAddr
	}

	return appAddr, nil
}

func (cx *EvalContext) getCreatableID(groupIndex uint64) (cid uint64, err error) {
	if cx.Ledger == nil {
		err = fmt.Errorf("ledger not available")
		return
	}
	gi := int(groupIndex)
	if gi < 0 {
		return 0, fmt.Errorf("groupIndex %d too high", groupIndex)
	}
	return uint64(cx.Ledger.GetCreatableID(gi)), nil
}

func (cx *EvalContext) getCreatorAddress() ([]byte, error) {
	if cx.Ledger == nil {
		return nil, fmt.Errorf("ledger not available")
	}
	_, creator, err := cx.Ledger.AppParams(cx.Ledger.ApplicationID())
	if err != nil {
		return nil, fmt.Errorf("No params for current app")
	}
	return creator[:], nil
}

func (cx *EvalContext) getGroupID() []byte {
	return cx.Txn.Txn.Group[:]
}

var zeroAddress basics.Address

func (cx *EvalContext) globalFieldToValue(fs globalFieldSpec) (sv stackValue, err error) {
	switch fs.field {
	case MinTxnFee:
		sv.Uint = cx.Proto.MinTxnFee
	case MinBalance:
		sv.Uint = cx.Proto.MinBalance
	case MaxTxnLife:
		sv.Uint = cx.Proto.MaxTxnLife
	case ZeroAddress:
		sv.Bytes = zeroAddress[:]
	case GroupSize:
		sv.Uint = uint64(len(cx.TxnGroup))
	case LogicSigVersion:
		sv.Uint = cx.Proto.LogicSigVersion
	case Round:
		sv.Uint, err = cx.getRound()
	case LatestTimestamp:
		sv.Uint, err = cx.getLatestTimestamp()
	case CurrentApplicationID:
		sv.Uint, err = cx.getApplicationID()
	case CurrentApplicationAddress:
		var addr basics.Address
		addr, err = cx.getApplicationAddress()
		sv.Bytes = addr[:]
	case CreatorAddress:
		sv.Bytes, err = cx.getCreatorAddress()
	case GroupID:
		sv.Bytes = cx.getGroupID()
	default:
		err = fmt.Errorf("invalid global field %d", fs.field)
	}

	if !typecheck(fs.ftype, sv.argType()) {
		err = fmt.Errorf("%s expected field type is %s but got %s", fs.field.String(), fs.ftype.String(), sv.argType().String())
	}

	return sv, err
}

func opGlobal(cx *EvalContext) {
	globalField := GlobalField(cx.program[cx.pc+1])
	fs, ok := globalFieldSpecByField[globalField]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid global field %d", globalField)
		return
	}
	if (cx.runModeFlags & fs.mode) == 0 {
		cx.err = fmt.Errorf("global[%d] not allowed in current mode", globalField)
		return
	}

	sv, err := cx.globalFieldToValue(fs)
	if err != nil {
		cx.err = err
		return
	}

	cx.stack = append(cx.stack, sv)
}

// Msg is data meant to be signed and then verified with the
// ed25519verify opcode.
type Msg struct {
	_struct     struct{}      `codec:",omitempty,omitemptyarray"`
	ProgramHash crypto.Digest `codec:"p"`
	Data        []byte        `codec:"d"`
}

// ToBeHashed implements crypto.Hashable
func (msg Msg) ToBeHashed() (protocol.HashID, []byte) {
	return protocol.ProgramData, append(msg.ProgramHash[:], msg.Data...)
}

// programHash lets us lazily compute H(cx.program)
func (cx *EvalContext) programHash() crypto.Digest {
	if cx.programHashCached == (crypto.Digest{}) {
		cx.programHashCached = crypto.HashObj(Program(cx.program))
	}
	return cx.programHashCached
}

func opEd25519verify(cx *EvalContext) {
	last := len(cx.stack) - 1 // index of PK
	prev := last - 1          // index of signature
	pprev := prev - 1         // index of data

	var sv crypto.SignatureVerifier
	if len(cx.stack[last].Bytes) != len(sv) {
		cx.err = errors.New("invalid public key")
		return
	}
	copy(sv[:], cx.stack[last].Bytes)

	var sig crypto.Signature
	if len(cx.stack[prev].Bytes) != len(sig) {
		cx.err = errors.New("invalid signature")
		return
	}
	copy(sig[:], cx.stack[prev].Bytes)

	msg := Msg{ProgramHash: cx.programHash(), Data: cx.stack[pprev].Bytes}
	if sv.Verify(msg, sig) {
		cx.stack[pprev].Uint = 1
	} else {
		cx.stack[pprev].Uint = 0
	}
	cx.stack[pprev].Bytes = nil
	cx.stack = cx.stack[:prev]
}

// leadingZeros needs to be replaced by big.Int.FillBytes
func leadingZeros(size int, b *big.Int) ([]byte, error) {
	data := b.Bytes()
	if size < len(data) {
		return nil, fmt.Errorf("insufficient buffer size: %d < %d", size, len(data))
	}
	if size == len(data) {
		return data, nil
	}

	buf := make([]byte, size)
	copy(buf[size-len(data):], data)
	return buf, nil
}

func opEcdsaVerify(cx *EvalContext) {
	ecdsaCurve := EcdsaCurve(cx.program[cx.pc+1])
	fs, ok := ecdsaCurveSpecByField[ecdsaCurve]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid curve %d", ecdsaCurve)
		return
	}

	if fs.field != Secp256k1 {
		cx.err = fmt.Errorf("unsupported curve %d", fs.field)
		return
	}

	last := len(cx.stack) - 1 // index of PK y
	prev := last - 1          // index of PK x
	pprev := prev - 1         // index of signature s
	fourth := pprev - 1       // index of signature r
	fifth := fourth - 1       // index of data

	pkY := cx.stack[last].Bytes
	pkX := cx.stack[prev].Bytes
	sigS := cx.stack[pprev].Bytes
	sigR := cx.stack[fourth].Bytes
	msg := cx.stack[fifth].Bytes

	x := new(big.Int).SetBytes(pkX)
	y := new(big.Int).SetBytes(pkY)
	pubkey := secp256k1.S256().Marshal(x, y)

	signature := make([]byte, 0, len(sigR)+len(sigS))
	signature = append(signature, sigR...)
	signature = append(signature, sigS...)

	result := secp256k1.VerifySignature(pubkey, msg, signature)

	if result {
		cx.stack[fifth].Uint = 1
	} else {
		cx.stack[fifth].Uint = 0
	}
	cx.stack[fifth].Bytes = nil
	cx.stack = cx.stack[:fourth]
}

func opEcdsaPkDecompress(cx *EvalContext) {
	ecdsaCurve := EcdsaCurve(cx.program[cx.pc+1])
	fs, ok := ecdsaCurveSpecByField[ecdsaCurve]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid curve %d", ecdsaCurve)
		return
	}

	if fs.field != Secp256k1 {
		cx.err = fmt.Errorf("unsupported curve %d", fs.field)
		return
	}

	last := len(cx.stack) - 1 // compressed PK

	pubkey := cx.stack[last].Bytes
	x, y := secp256k1.DecompressPubkey(pubkey)
	if x == nil {
		cx.err = fmt.Errorf("invalid pubkey")
		return
	}

	var err error
	cx.stack[last].Uint = 0
	cx.stack[last].Bytes, err = leadingZeros(32, x)
	if err != nil {
		cx.err = fmt.Errorf("x component zeroing failed: %s", err.Error())
		return
	}

	var sv stackValue
	sv.Bytes, err = leadingZeros(32, y)
	if err != nil {
		cx.err = fmt.Errorf("y component zeroing failed: %s", err.Error())
		return
	}

	cx.stack = append(cx.stack, sv)
}

func opEcdsaPkRecover(cx *EvalContext) {
	ecdsaCurve := EcdsaCurve(cx.program[cx.pc+1])
	fs, ok := ecdsaCurveSpecByField[ecdsaCurve]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid curve %d", ecdsaCurve)
		return
	}

	if fs.field != Secp256k1 {
		cx.err = fmt.Errorf("unsupported curve %d", fs.field)
		return
	}

	last := len(cx.stack) - 1 // index of signature s
	prev := last - 1          // index of signature r
	pprev := prev - 1         // index of recovery id
	fourth := pprev - 1       // index of data

	sigS := cx.stack[last].Bytes
	sigR := cx.stack[prev].Bytes
	recid := cx.stack[pprev].Uint
	msg := cx.stack[fourth].Bytes

	if recid > 3 {
		cx.err = fmt.Errorf("invalid recovery id: %d", recid)
		return
	}

	signature := make([]byte, 0, len(sigR)+len(sigS)+1)
	signature = append(signature, sigR...)
	signature = append(signature, sigS...)
	signature = append(signature, uint8(recid))

	pk, err := secp256k1.RecoverPubkey(msg, signature)
	if err != nil {
		cx.err = fmt.Errorf("pubkey recover failed: %s", err.Error())
		return
	}
	x, y := secp256k1.S256().Unmarshal(pk)
	if x == nil {
		cx.err = fmt.Errorf("pubkey unmarshal failed")
		return
	}

	cx.stack[fourth].Uint = 0
	cx.stack[fourth].Bytes, err = leadingZeros(32, x)
	if err != nil {
		cx.err = fmt.Errorf("x component zeroing failed: %s", err.Error())
		return
	}
	cx.stack[pprev].Uint = 0
	cx.stack[pprev].Bytes, err = leadingZeros(32, y)
	if err != nil {
		cx.err = fmt.Errorf("y component zeroing failed: %s", err.Error())
		return
	}
	cx.stack = cx.stack[:prev]
}

func opLoad(cx *EvalContext) {
	n := cx.program[cx.pc+1]
	cx.stack = append(cx.stack, cx.scratch[n])
}

func opLoads(cx *EvalContext) {
	last := len(cx.stack) - 1
	n := cx.stack[last].Uint
	if n >= uint64(len(cx.scratch)) {
		cx.err = fmt.Errorf("invalid Scratch index %d", n)
		return
	}
	cx.stack[last] = cx.scratch[n]
}

func opStore(cx *EvalContext) {
	n := cx.program[cx.pc+1]
	last := len(cx.stack) - 1
	cx.scratch[n] = cx.stack[last]
	cx.stack = cx.stack[:last]
}

func opStores(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	n := cx.stack[prev].Uint
	if n >= uint64(len(cx.scratch)) {
		cx.err = fmt.Errorf("invalid Scratch index %d", n)
		return
	}
	cx.scratch[n] = cx.stack[last]
	cx.stack = cx.stack[:prev]
}

func opGloadImpl(cx *EvalContext, groupIdx uint64, scratchIdx byte, opName string) (scratchValue stackValue, err error) {
	if groupIdx >= uint64(len(cx.TxnGroup)) {
		err = fmt.Errorf("%s lookup TxnGroup[%d] but it only has %d", opName, groupIdx, len(cx.TxnGroup))
		return
	} else if int(scratchIdx) >= len(cx.scratch) {
		err = fmt.Errorf("invalid Scratch index %d", scratchIdx)
		return
	} else if txn := cx.TxnGroup[groupIdx].Txn; txn.Type != protocol.ApplicationCallTx {
		err = fmt.Errorf("can't use %s on non-app call txn with index %d", opName, groupIdx)
		return
	} else if groupIdx == cx.GroupIndex {
		err = fmt.Errorf("can't use %s on self, use load instead", opName)
		return
	} else if groupIdx > cx.GroupIndex {
		err = fmt.Errorf("%s can't get future scratch space from txn with index %d", opName, groupIdx)
		return
	}

	scratchValue = cx.PastSideEffects[groupIdx].getScratchValue(scratchIdx)
	return
}

func opGload(cx *EvalContext) {
	groupIdx := uint64(cx.program[cx.pc+1])
	scratchIdx := cx.program[cx.pc+2]
	scratchValue, err := opGloadImpl(cx, groupIdx, scratchIdx, "gload")
	if err != nil {
		cx.err = err
		return
	}

	cx.stack = append(cx.stack, scratchValue)
}

func opGloads(cx *EvalContext) {
	last := len(cx.stack) - 1
	groupIdx := cx.stack[last].Uint
	scratchIdx := cx.program[cx.pc+1]
	scratchValue, err := opGloadImpl(cx, groupIdx, scratchIdx, "gloads")
	if err != nil {
		cx.err = err
		return
	}

	cx.stack[last] = scratchValue
}

func opConcat(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	a := cx.stack[prev].Bytes
	b := cx.stack[last].Bytes
	newlen := len(a) + len(b)
	newvalue := make([]byte, newlen)
	copy(newvalue, a)
	copy(newvalue[len(a):], b)
	cx.stack[prev].Bytes = newvalue
	cx.stack = cx.stack[:last]
}

func substring(x []byte, start, end int) (out []byte, err error) {
	out = x
	if end < start {
		err = errors.New("substring end before start")
		return
	}
	if start > len(x) || end > len(x) {
		err = errors.New("substring range beyond length of string")
		return
	}
	out = x[start:end]
	err = nil
	return
}

func opSubstring(cx *EvalContext) {
	last := len(cx.stack) - 1
	start := cx.program[cx.pc+1]
	end := cx.program[cx.pc+2]
	cx.stack[last].Bytes, cx.err = substring(cx.stack[last].Bytes, int(start), int(end))
}

func opSubstring3(cx *EvalContext) {
	last := len(cx.stack) - 1 // end
	prev := last - 1          // start
	pprev := prev - 1         // bytes
	start := cx.stack[prev].Uint
	end := cx.stack[last].Uint
	if start > math.MaxInt32 || end > math.MaxInt32 {
		cx.err = errors.New("substring range beyond length of string")
		return
	}
	cx.stack[pprev].Bytes, cx.err = substring(cx.stack[pprev].Bytes, int(start), int(end))
	cx.stack = cx.stack[:prev]
}

func opGetBit(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	idx := cx.stack[last].Uint
	target := cx.stack[prev]

	var bit uint64
	if target.argType() == StackUint64 {
		if idx > 63 {
			cx.err = errors.New("getbit index > 63 with with Uint")
			return
		}
		mask := uint64(1) << idx
		bit = (target.Uint & mask) >> idx
	} else {
		// indexing into a byteslice
		byteIdx := idx / 8
		if byteIdx >= uint64(len(target.Bytes)) {
			cx.err = errors.New("getbit index beyond byteslice")
			return
		}
		byteVal := target.Bytes[byteIdx]

		bitIdx := idx % 8
		// We saying that bit 9 (the 10th bit), for example,
		// is the 2nd bit in the second byte, and that "2nd
		// bit" here means almost-highest-order bit, because
		// we're thinking of the bits in the byte itself as
		// being big endian. So this looks "reversed"
		mask := byte(0x80) >> bitIdx
		bit = uint64((byteVal & mask) >> (7 - bitIdx))
	}
	cx.stack[prev].Uint = bit
	cx.stack[prev].Bytes = nil
	cx.stack = cx.stack[:last]
}

func opSetBit(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	pprev := prev - 1

	bit := cx.stack[last].Uint
	idx := cx.stack[prev].Uint
	target := cx.stack[pprev]

	if bit > 1 {
		cx.err = errors.New("setbit value > 1")
		return
	}

	if target.argType() == StackUint64 {
		if idx > 63 {
			cx.err = errors.New("setbit index > 63 with Uint")
			return
		}
		mask := uint64(1) << idx
		if bit == uint64(1) {
			cx.stack[pprev].Uint |= mask // manipulate stack in place
		} else {
			cx.stack[pprev].Uint &^= mask // manipulate stack in place
		}
	} else {
		// indexing into a byteslice
		byteIdx := idx / 8
		if byteIdx >= uint64(len(target.Bytes)) {
			cx.err = errors.New("setbit index beyond byteslice")
			return
		}

		bitIdx := idx % 8
		// We saying that bit 9 (the 10th bit), for example,
		// is the 2nd bit in the second byte, and that "2nd
		// bit" here means almost-highest-order bit, because
		// we're thinking of the bits in the byte itself as
		// being big endian. So this looks "reversed"
		mask := byte(0x80) >> bitIdx
		// Copy to avoid modifying shared slice
		scratch := append([]byte(nil), target.Bytes...)
		if bit == uint64(1) {
			scratch[byteIdx] |= mask
		} else {
			scratch[byteIdx] &^= mask
		}
		cx.stack[pprev].Bytes = scratch
	}
	cx.stack = cx.stack[:prev]
}

func opGetByte(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1

	idx := cx.stack[last].Uint
	target := cx.stack[prev]

	if idx >= uint64(len(target.Bytes)) {
		cx.err = errors.New("getbyte index beyond array length")
		return
	}
	cx.stack[prev].Uint = uint64(target.Bytes[idx])
	cx.stack[prev].Bytes = nil
	cx.stack = cx.stack[:last]
}

func opSetByte(cx *EvalContext) {
	last := len(cx.stack) - 1
	prev := last - 1
	pprev := prev - 1
	if cx.stack[last].Uint > 255 {
		cx.err = errors.New("setbyte value > 255")
		return
	}
	if cx.stack[prev].Uint >= uint64(len(cx.stack[pprev].Bytes)) {
		cx.err = errors.New("setbyte index beyond array length")
		return
	}
	// Copy to avoid modifying shared slice
	cx.stack[pprev].Bytes = append([]byte(nil), cx.stack[pprev].Bytes...)
	cx.stack[pprev].Bytes[cx.stack[prev].Uint] = byte(cx.stack[last].Uint)
	cx.stack = cx.stack[:prev]
}

func opExtractImpl(x []byte, start, length int) (out []byte, err error) {
	out = x
	end := start + length
	if start > len(x) || end > len(x) {
		err = errors.New("extract range beyond length of string")
		return
	}
	out = x[start:end]
	return
}

func opExtract(cx *EvalContext) {
	last := len(cx.stack) - 1
	startIdx := cx.program[cx.pc+1]
	lengthIdx := cx.program[cx.pc+2]
	// Shortcut: if length is 0, take bytes from start index to the end
	length := int(lengthIdx)
	if length == 0 {
		length = len(cx.stack[last].Bytes) - int(startIdx)
	}
	cx.stack[last].Bytes, cx.err = opExtractImpl(cx.stack[last].Bytes, int(startIdx), length)
}

func opExtract3(cx *EvalContext) {
	last := len(cx.stack) - 1 // length
	prev := last - 1          // start
	byteArrayIdx := prev - 1  // bytes
	startIdx := cx.stack[prev].Uint
	lengthIdx := cx.stack[last].Uint
	if startIdx > math.MaxInt32 || lengthIdx > math.MaxInt32 {
		cx.err = errors.New("extract range beyond length of string")
		return
	}
	cx.stack[byteArrayIdx].Bytes, cx.err = opExtractImpl(cx.stack[byteArrayIdx].Bytes, int(startIdx), int(lengthIdx))
	cx.stack = cx.stack[:prev]
}

// We convert the bytes manually here because we need to accept "short" byte arrays.
// A single byte is a legal uint64 decoded this way.
func convertBytesToInt(x []byte) (out uint64) {
	out = uint64(0)
	for _, b := range x {
		out = out << 8
		out = out | (uint64(b) & 0x0ff)
	}
	return
}

func opExtractNBytes(cx *EvalContext, n int) {
	last := len(cx.stack) - 1 // start
	prev := last - 1          // bytes
	startIdx := cx.stack[last].Uint
	cx.stack[prev].Bytes, cx.err = opExtractImpl(cx.stack[prev].Bytes, int(startIdx), n) // extract n bytes

	cx.stack[prev].Uint = convertBytesToInt(cx.stack[prev].Bytes)
	cx.stack[prev].Bytes = nil
	cx.stack = cx.stack[:last]
}

func opExtract16Bits(cx *EvalContext) {
	opExtractNBytes(cx, 2) // extract 2 bytes
}

func opExtract32Bits(cx *EvalContext) {
	opExtractNBytes(cx, 4) // extract 4 bytes
}

func opExtract64Bits(cx *EvalContext) {
	opExtractNBytes(cx, 8) // extract 8 bytes
}

// accountReference yields the address and Accounts offset designated
// by a stackValue. If the stackValue is the app account, it need not
// be in the Accounts array, therefore len(Accounts) + 1 is returned
// as the index. This unusual convention is based on the existing
// convention that 0 is the sender, 1-len(Accounts) are indexes into
// Accounts array, and so len+1 is the next available value.  This
// will allow encoding into EvalDelta efficiently when it becomes
// necessary (when apps change local state on their own account).
func (cx *EvalContext) accountReference(account stackValue) (basics.Address, uint64, error) {
	if account.argType() == StackUint64 {
		addr, err := cx.Txn.Txn.AddressByIndex(account.Uint, cx.Txn.Txn.Sender)
		return addr, account.Uint, err
	}
	addr, err := account.address()
	if err != nil {
		return addr, 0, err
	}
	idx, err := cx.Txn.Txn.IndexByAddress(addr, cx.Txn.Txn.Sender)

	if err != nil {
		// Application address is acceptable. index is meaningless though
		appAddr, _ := cx.getApplicationAddress()
		if appAddr == addr {
			return addr, uint64(len(cx.Txn.Txn.Accounts) + 1), nil
		}
	}

	return addr, idx, err
}

type opQuery func(basics.Address, *config.ConsensusParams) (basics.MicroAlgos, error)

func opBalanceQuery(cx *EvalContext, query opQuery, item string) error {
	last := len(cx.stack) - 1 // account (index or actual address)

	addr, _, err := cx.accountReference(cx.stack[last])
	if err != nil {
		return err
	}

	microAlgos, err := query(addr, cx.Proto)
	if err != nil {
		return fmt.Errorf("failed to fetch %s of %v: %w", item, addr, err)
	}

	cx.stack[last].Bytes = nil
	cx.stack[last].Uint = microAlgos.Raw
	return nil
}
func opBalance(cx *EvalContext) {
	if cx.Ledger == nil {
		cx.err = fmt.Errorf("ledger not available")
		return
	}

	balanceQuery := func(addr basics.Address, _ *config.ConsensusParams) (basics.MicroAlgos, error) {
		return cx.Ledger.Balance(addr)
	}
	err := opBalanceQuery(cx, balanceQuery, "balance")
	if err != nil {
		cx.err = err
	}
}
func opMinBalance(cx *EvalContext) {
	if cx.Ledger == nil {
		cx.err = fmt.Errorf("ledger not available")
		return
	}

	err := opBalanceQuery(cx, cx.Ledger.MinBalance, "minimum balance")
	if err != nil {
		cx.err = err
	}
}

func opAppOptedIn(cx *EvalContext) {
	last := len(cx.stack) - 1 // app
	prev := last - 1          // account

	if cx.Ledger == nil {
		cx.err = fmt.Errorf("ledger not available")
		return
	}

	addr, _, err := cx.accountReference(cx.stack[prev])
	if err != nil {
		cx.err = err
		return
	}

	app, err := appReference(cx, cx.stack[last].Uint, false)
	if err != nil {
		cx.err = err
		return
	}

	optedIn, err := cx.Ledger.OptedIn(addr, app)
	if err != nil {
		cx.err = err
		return
	}

	cx.stack[prev].Bytes = nil
	if optedIn {
		cx.stack[prev].Uint = 1
	} else {
		cx.stack[prev].Uint = 0
	}

	cx.stack = cx.stack[:last]
}

func opAppLocalGet(cx *EvalContext) {
	last := len(cx.stack) - 1 // state key
	prev := last - 1          // account

	key := cx.stack[last].Bytes

	result, _, err := opAppLocalGetImpl(cx, 0, key, cx.stack[prev])
	if err != nil {
		cx.err = err
		return
	}

	cx.stack[prev] = result
	cx.stack = cx.stack[:last]
}

func opAppLocalGetEx(cx *EvalContext) {
	last := len(cx.stack) - 1 // state key
	prev := last - 1          // app id
	pprev := prev - 1         // account

	key := cx.stack[last].Bytes
	appID := cx.stack[prev].Uint

	result, ok, err := opAppLocalGetImpl(cx, appID, key, cx.stack[pprev])
	if err != nil {
		cx.err = err
		return
	}

	var isOk stackValue
	if ok {
		isOk.Uint = 1
	}

	cx.stack[pprev] = result
	cx.stack[prev] = isOk
	cx.stack = cx.stack[:last]
}

func opAppLocalGetImpl(cx *EvalContext, appID uint64, key []byte, acct stackValue) (result stackValue, ok bool, err error) {
	if cx.Ledger == nil {
		err = fmt.Errorf("ledger not available")
		return
	}

	addr, accountIdx, err := cx.accountReference(acct)
	if err != nil {
		return
	}

	app, err := appReference(cx, appID, false)
	if err != nil {
		return
	}

	tv, ok, err := cx.Ledger.GetLocal(addr, app, string(key), accountIdx)
	if err != nil {
		cx.err = err
		return
	}

	if ok {
		result, err = stackValueFromTealValue(&tv)
	}
	return
}

func opAppGetGlobalStateImpl(cx *EvalContext, appIndex uint64, key []byte) (result stackValue, ok bool, err error) {
	if cx.Ledger == nil {
		err = fmt.Errorf("ledger not available")
		return
	}

	app, err := appReference(cx, appIndex, true)
	if err != nil {
		return
	}
	tv, ok, err := cx.Ledger.GetGlobal(app, string(key))

	if err != nil {
		return
	}

	if ok {
		result, err = stackValueFromTealValue(&tv)
	}
	return
}

func opAppGlobalGet(cx *EvalContext) {
	last := len(cx.stack) - 1 // state key

	key := cx.stack[last].Bytes

	result, _, err := opAppGetGlobalStateImpl(cx, 0, key)
	if err != nil {
		cx.err = err
		return
	}

	cx.stack[last] = result
}

func opAppGlobalGetEx(cx *EvalContext) {
	last := len(cx.stack) - 1 // state key
	prev := last - 1          // app

	key := cx.stack[last].Bytes

	result, ok, err := opAppGetGlobalStateImpl(cx, cx.stack[prev].Uint, key)
	if err != nil {
		cx.err = err
		return
	}

	var isOk stackValue
	if ok {
		isOk.Uint = 1
	}

	cx.stack[prev] = result
	cx.stack[last] = isOk
}

func opAppLocalPut(cx *EvalContext) {
	last := len(cx.stack) - 1 // value
	prev := last - 1          // state key
	pprev := prev - 1         // account

	sv := cx.stack[last]
	key := string(cx.stack[prev].Bytes)

	if cx.Ledger == nil {
		cx.err = fmt.Errorf("ledger not available")
		return
	}

	addr, accountIdx, err := cx.accountReference(cx.stack[pprev])
	if err == nil {
		err = cx.Ledger.SetLocal(addr, key, sv.toTealValue(), accountIdx)
	}

	if err != nil {
		cx.err = err
		return
	}

	cx.stack = cx.stack[:pprev]
}

func opAppGlobalPut(cx *EvalContext) {
	last := len(cx.stack) - 1 // value
	prev := last - 1          // state key

	sv := cx.stack[last]
	key := string(cx.stack[prev].Bytes)

	if cx.Ledger == nil {
		cx.err = fmt.Errorf("ledger not available")
		return
	}

	err := cx.Ledger.SetGlobal(key, sv.toTealValue())
	if err != nil {
		cx.err = err
		return
	}

	cx.stack = cx.stack[:prev]
}

func opAppLocalDel(cx *EvalContext) {
	last := len(cx.stack) - 1 // key
	prev := last - 1          // account

	key := string(cx.stack[last].Bytes)

	if cx.Ledger == nil {
		cx.err = fmt.Errorf("ledger not available")
		return
	}

	addr, accountIdx, err := cx.accountReference(cx.stack[prev])
	if err == nil {
		err = cx.Ledger.DelLocal(addr, key, accountIdx)
	}
	if err != nil {
		cx.err = err
		return
	}

	cx.stack = cx.stack[:prev]
}

func opAppGlobalDel(cx *EvalContext) {
	last := len(cx.stack) - 1 // key

	key := string(cx.stack[last].Bytes)

	if cx.Ledger == nil {
		cx.err = fmt.Errorf("ledger not available")
		return
	}

	err := cx.Ledger.DelGlobal(key)
	if err != nil {
		cx.err = err
		return
	}
	cx.stack = cx.stack[:last]
}

// We have a difficult naming problem here. In some opcodes, TEAL
// allows (and used to require) ASAs and Apps to to be referenced by
// their "index" in an app call txn's foeign-apps or foreign-assets
// arrays.  That was a small integer, no more than 2 or so, and was
// often called an "index".  But it was not a basics.AssetIndex or
// basics.ApplicationIndex.

func appReference(cx *EvalContext, ref uint64, foreign bool) (basics.AppIndex, error) {
	if cx.version >= directRefEnabledVersion {
		if ref == 0 {
			return cx.Ledger.ApplicationID(), nil
		}
		if ref <= uint64(len(cx.Txn.Txn.ForeignApps)) {
			return basics.AppIndex(cx.Txn.Txn.ForeignApps[ref-1]), nil
		}
		for _, appID := range cx.Txn.Txn.ForeignApps {
			if appID == basics.AppIndex(ref) {
				return appID, nil
			}
		}
		// It should be legal to use your own app id, which
		// can't be in ForeignApps during creation, because it
		// is unknown then.  But it can be discovered in the
		// app code.  It's tempting to combine this with the
		// == 0 test, above, but it must come after the check
		// for being below len(ForeignApps)
		if ref == uint64(cx.Ledger.ApplicationID()) {
			return cx.Ledger.ApplicationID(), nil
		}
	} else {
		// Old rules
		if foreign {
			// In old versions, a foreign reference must be an index in ForeignAssets or 0
			if ref == 0 {
				return cx.Ledger.ApplicationID(), nil
			}
			if ref <= uint64(len(cx.Txn.Txn.ForeignApps)) {
				return basics.AppIndex(cx.Txn.Txn.ForeignApps[ref-1]), nil
			}
		} else {
			// Otherwise it's direct
			return basics.AppIndex(ref), nil
		}
	}
	return basics.AppIndex(0), fmt.Errorf("invalid App reference %d", ref)
}

func asaReference(cx *EvalContext, ref uint64, foreign bool) (basics.AssetIndex, error) {
	if cx.version >= directRefEnabledVersion {
		// In recent versions, accept either kind of ASA reference
		if ref < uint64(len(cx.Txn.Txn.ForeignAssets)) {
			return basics.AssetIndex(cx.Txn.Txn.ForeignAssets[ref]), nil
		}
		for _, assetID := range cx.Txn.Txn.ForeignAssets {
			if assetID == basics.AssetIndex(ref) {
				return assetID, nil
			}
		}
	} else {
		// Old rules
		if foreign {
			// In old versions, a foreign reference must be an index in ForeignAssets
			if ref < uint64(len(cx.Txn.Txn.ForeignAssets)) {
				return basics.AssetIndex(cx.Txn.Txn.ForeignAssets[ref]), nil
			}
		} else {
			// Otherwise it's direct
			return basics.AssetIndex(ref), nil
		}
	}
	return basics.AssetIndex(0), fmt.Errorf("invalid Asset reference %d", ref)

}

func opAssetHoldingGet(cx *EvalContext) {
	last := len(cx.stack) - 1 // asset
	prev := last - 1          // account

	if cx.Ledger == nil {
		cx.err = fmt.Errorf("ledger not available")
		return
	}

	holdingField := AssetHoldingField(cx.program[cx.pc+1])
	fs, ok := assetHoldingFieldSpecByField[holdingField]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid asset_holding_get field %d", holdingField)
		return
	}

	addr, _, err := cx.accountReference(cx.stack[prev])
	if err != nil {
		cx.err = err
		return
	}

	asset, err := asaReference(cx, cx.stack[last].Uint, false)
	if err != nil {
		cx.err = err
		return
	}

	var exist uint64 = 0
	var value stackValue
	if holding, err := cx.Ledger.AssetHolding(addr, asset); err == nil {
		// the holding exist, read the value
		exist = 1
		value, err = cx.assetHoldingToValue(&holding, fs)
		if err != nil {
			cx.err = err
			return
		}
	}

	cx.stack[prev] = value
	cx.stack[last].Uint = exist
}

func opAssetParamsGet(cx *EvalContext) {
	last := len(cx.stack) - 1 // asset

	if cx.Ledger == nil {
		cx.err = fmt.Errorf("ledger not available")
		return
	}

	paramField := AssetParamsField(cx.program[cx.pc+1])
	fs, ok := assetParamsFieldSpecByField[paramField]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid asset_params_get field %d", paramField)
		return
	}

	asset, err := asaReference(cx, cx.stack[last].Uint, true)
	if err != nil {
		cx.err = err
		return
	}

	var exist uint64 = 0
	var value stackValue
	if params, creator, err := cx.Ledger.AssetParams(asset); err == nil {
		// params exist, read the value
		exist = 1
		value, err = cx.assetParamsToValue(&params, creator, fs)
		if err != nil {
			cx.err = err
			return
		}
	}

	cx.stack[last] = value
	cx.stack = append(cx.stack, stackValue{Uint: exist})
}

func opAppParamsGet(cx *EvalContext) {
	last := len(cx.stack) - 1 // app

	if cx.Ledger == nil {
		cx.err = fmt.Errorf("ledger not available")
		return
	}

	paramField := AppParamsField(cx.program[cx.pc+1])
	fs, ok := appParamsFieldSpecByField[paramField]
	if !ok || fs.version > cx.version {
		cx.err = fmt.Errorf("invalid app_params_get field %d", paramField)
		return
	}

	app, err := appReference(cx, cx.stack[last].Uint, true)
	if err != nil {
		cx.err = err
		return
	}

	var exist uint64 = 0
	var value stackValue
	if params, creator, err := cx.Ledger.AppParams(app); err == nil {
		// params exist, read the value
		exist = 1

		switch fs.field {
		case AppCreator:
			value.Bytes = creator[:]
		case AppAddress:
			address := app.Address()
			value.Bytes = address[:]
		default:
			value, err = cx.appParamsToValue(&params, fs)
		}
		if err != nil {
			cx.err = err
			return
		}
	}

	cx.stack[last] = value
	cx.stack = append(cx.stack, stackValue{Uint: exist})
}

func opLog(cx *EvalContext) {
	last := len(cx.stack) - 1

	if len(cx.Logs) == MaxLogCalls {
		cx.err = fmt.Errorf("too many log calls in program. up to %d is allowed", MaxLogCalls)
		return
	}
	log := cx.stack[last]
	cx.logSize += len(log.Bytes)
	if cx.logSize > MaxLogSize {
		cx.err = fmt.Errorf("program logs too large. %d bytes >  %d bytes limit", cx.logSize, MaxLogSize)
		return
	}
	cx.Logs = append(cx.Logs, string(log.Bytes))
	cx.stack = cx.stack[:last]
}

func authorizedSender(cx *EvalContext, addr basics.Address) bool {
	appAddr, err := cx.getApplicationAddress()
	if err != nil {
		return false
	}
	authorizer, err := cx.Ledger.Authorizer(addr)
	if err != nil {
		return false
	}
	return appAddr == authorizer
}

func opTxBegin(cx *EvalContext) {
	if cx.subtxn != nil {
		cx.err = errors.New("itxn_begin without itxn_submit")
		return
	}
	// Start fresh
	cx.subtxn = &transactions.SignedTxn{}
	// Fill in defaults.
	addr, err := cx.getApplicationAddress()
	if err != nil {
		cx.err = err
		return
	}

	fee := cx.Proto.MinTxnFee
	if cx.FeeCredit != nil {
		// Use credit to shrink the fee, but don't change FeeCredit
		// here, because they might never itxn_submit, or they might
		// change the fee.  Do it in itxn_submit.
		fee = basics.SubSaturate(fee, *cx.FeeCredit)
	}
	cx.subtxn.Txn.Header = transactions.Header{
		Sender:     addr, // Default, to simplify usage
		Fee:        basics.MicroAlgos{Raw: fee},
		FirstValid: cx.Txn.Txn.FirstValid,
		LastValid:  cx.Txn.Txn.LastValid,
	}
}

// availableAccount is used instead of accountReference for more recent opcodes
// that don't need (or want!) to allow low numbers to represent the account at
// that index in Accounts array.
func (cx *EvalContext) availableAccount(sv stackValue) (basics.Address, error) {
	if sv.argType() != StackBytes || len(sv.Bytes) != crypto.DigestSize {
		return basics.Address{}, fmt.Errorf("not an address")
	}

	addr, _, err := cx.accountReference(sv)
	return addr, err
}

// availableAsset is used instead of asaReference for more recent opcodes that
// don't need (or want!) to allow low numbers to represent the asset at that
// index in ForeignAssets array.
func (cx *EvalContext) availableAsset(sv stackValue) (basics.AssetIndex, error) {
	aid, err := sv.uint()
	if err != nil {
		return basics.AssetIndex(0), err
	}
	// Ensure that aid is in Foreign Assets
	for _, assetID := range cx.Txn.Txn.ForeignAssets {
		if assetID == basics.AssetIndex(aid) {
			return basics.AssetIndex(aid), nil
		}
	}
	return basics.AssetIndex(0), fmt.Errorf("invalid Asset reference %d", aid)
}

func (cx *EvalContext) stackIntoTxnField(sv stackValue, fs txnFieldSpec, txn *transactions.Transaction) (err error) {
	switch fs.field {
	case Type:
		if sv.Bytes == nil {
			err = fmt.Errorf("Type arg not a byte array")
			return
		}
		txType, ok := innerTxnTypes[string(sv.Bytes)]
		if ok {
			txn.Type = txType
		} else {
			err = fmt.Errorf("%s is not a valid Type for itxn_field", sv.Bytes)
		}
	case TypeEnum:
		var i uint64
		i, err = sv.uint()
		if err != nil {
			return
		}
		// i != 0 is so that the error reports 0 instead of Unknown
		if i != 0 && i < uint64(len(TxnTypeNames)) {
			txType, ok := innerTxnTypes[TxnTypeNames[i]]
			if ok {
				txn.Type = txType
			} else {
				err = fmt.Errorf("%s is not a valid Type for itxn_field", TxnTypeNames[i])
			}
		} else {
			err = fmt.Errorf("%d is not a valid TypeEnum", i)
		}
	case Sender:
		txn.Sender, err = cx.availableAccount(sv)
	case Fee:
		txn.Fee.Raw, err = sv.uint()
	// FirstValid, LastValid unsettable: no motivation
	// Note unsettable: would be strange, as this "Note" would not end up "chain-visible"
	// GenesisID, GenesisHash unsettable: surely makes no sense
	// Group unsettable: Can't make groups from AVM (yet?)
	// Lease unsettable: This seems potentially useful.
	// RekeyTo unsettable: Feels dangerous for first release.

	// KeyReg not allowed yet, so no fields settable

	// Payment
	case Receiver:
		txn.Receiver, err = cx.availableAccount(sv)
	case Amount:
		txn.Amount.Raw, err = sv.uint()
	case CloseRemainderTo:
		txn.CloseRemainderTo, err = cx.availableAccount(sv)
	// AssetTransfer
	case XferAsset:
		txn.XferAsset, err = cx.availableAsset(sv)
	case AssetAmount:
		txn.AssetAmount, err = sv.uint()
	case AssetSender:
		txn.AssetSender, err = cx.availableAccount(sv)
	case AssetReceiver:
		txn.AssetReceiver, err = cx.availableAccount(sv)
	case AssetCloseTo:
		txn.AssetCloseTo, err = cx.availableAccount(sv)
	// AssetConfig
	case ConfigAsset:
		txn.ConfigAsset, err = cx.availableAsset(sv)
	case ConfigAssetTotal:
		txn.AssetParams.Total, err = sv.uint()
	case ConfigAssetDecimals:
		var decimals uint64
		decimals, err = sv.uint()
		if err == nil {
			if decimals > uint64(cx.Proto.MaxAssetDecimals) {
				err = fmt.Errorf("too many decimals (%d)", decimals)
			} else {
				txn.AssetParams.Decimals = uint32(decimals)
			}
		}
	case ConfigAssetDefaultFrozen:
		txn.AssetParams.DefaultFrozen, err = sv.bool()
	case ConfigAssetUnitName:
		txn.AssetParams.UnitName, err = sv.string(cx.Proto.MaxAssetUnitNameBytes)
	case ConfigAssetName:
		txn.AssetParams.AssetName, err = sv.string(cx.Proto.MaxAssetNameBytes)
	case ConfigAssetURL:
		txn.AssetParams.URL, err = sv.string(cx.Proto.MaxAssetURLBytes)
	case ConfigAssetMetadataHash:
		if len(sv.Bytes) != 32 {
			err = fmt.Errorf("ConfigAssetMetadataHash must be 32 bytes")
		} else {
			copy(txn.AssetParams.MetadataHash[:], sv.Bytes)
		}
	case ConfigAssetManager:
		txn.AssetParams.Manager, err = sv.address()
	case ConfigAssetReserve:
		txn.AssetParams.Reserve, err = sv.address()
	case ConfigAssetFreeze:
		txn.AssetParams.Freeze, err = sv.address()
	case ConfigAssetClawback:
		txn.AssetParams.Clawback, err = sv.address()
	// Freeze
	case FreezeAsset:
		txn.FreezeAsset, err = cx.availableAsset(sv)
	case FreezeAssetAccount:
		txn.FreezeAccount, err = cx.availableAccount(sv)
	case FreezeAssetFrozen:
		txn.AssetFrozen, err = sv.bool()

	// appl needs to wait. Can't call AVM from AVM.

	default:
		return fmt.Errorf("invalid itxn_field %s", fs.field)
	}
	return
}

func opTxField(cx *EvalContext) {
	if cx.subtxn == nil {
		cx.err = errors.New("itxn_field without itxn_begin")
		return
	}
	last := len(cx.stack) - 1
	field := TxnField(cx.program[cx.pc+1])
	fs, ok := txnFieldSpecByField[field]
	if !ok || fs.itxVersion == 0 || fs.itxVersion > cx.version {
		cx.err = fmt.Errorf("invalid itxn_field field %d", field)
	}
	sv := cx.stack[last]
	cx.err = cx.stackIntoTxnField(sv, fs, &cx.subtxn.Txn)
	cx.stack = cx.stack[:last] // pop
}

func opTxSubmit(cx *EvalContext) {
	if cx.Ledger == nil {
		cx.err = fmt.Errorf("ledger not available")
		return
	}

	if cx.subtxn == nil {
		cx.err = errors.New("itxn_submit without itxn_begin")
		return
	}

	if len(cx.InnerTxns) >= cx.Proto.MaxInnerTransactions {
		cx.err = errors.New("itxn_submit with MaxInnerTransactions")
		return
	}

	// Error out on anything unusual.  Allow pay, axfer.
	switch cx.subtxn.Txn.Type {
	case protocol.PaymentTx, protocol.AssetTransferTx, protocol.AssetConfigTx, protocol.AssetFreezeTx:
		// only pay, axfer, acfg, afrz for now
	default:
		cx.err = fmt.Errorf("Invalid inner transaction type %#v", cx.subtxn.Txn.Type)
		return
	}

	// The goal is to follow the same invariants used by the
	// transaction pool. Namely that any transaction that makes it
	// to Perform (which is equivalent to eval.applyTransaction)
	// is authorized, and WellFormed.
	if !authorizedSender(cx, cx.subtxn.Txn.Sender) {
		cx.err = fmt.Errorf("unauthorized")
		return
	}

	// Recall that WellFormed does not care about individual
	// transaction fees because of fee pooling. So we check below.
	cx.err = cx.subtxn.Txn.WellFormed(*cx.Specials, *cx.Proto)
	if cx.err != nil {
		return
	}

	paid := cx.subtxn.Txn.Fee.Raw
	if paid >= cx.Proto.MinTxnFee {
		// Over paying - accumulate into FeeCredit
		overpaid := paid - cx.Proto.MinTxnFee
		if cx.FeeCredit == nil {
			cx.FeeCredit = new(uint64)
		}
		*cx.FeeCredit = basics.AddSaturate(*cx.FeeCredit, overpaid)
	} else {
		underpaid := cx.Proto.MinTxnFee - paid
		// Try to pay with FeeCredit, else fail.
		if cx.FeeCredit != nil && *cx.FeeCredit >= underpaid {
			*cx.FeeCredit -= underpaid
		} else {
			// We allow changing the fee. One pattern might be for an
			// app to unilaterally set its Fee to 0. The idea would be
			// that other transactions were supposed to overpay.
			cx.err = fmt.Errorf("fee too small")
			return
		}
	}

	ad, err := cx.Ledger.Perform(&cx.subtxn.Txn, *cx.Specials)
	if err != nil {
		cx.err = err
		return
	}
	cx.InnerTxns = append(cx.InnerTxns, transactions.SignedTxnWithAD{
		SignedTxn: *cx.subtxn,
		ApplyData: ad,
	})
	cx.subtxn = nil
}