summaryrefslogtreecommitdiff
path: root/data/transactions/logic/evalStateful_test.go
blob: 91ad91d1fed1863227cee16cf86ecfbdb133f5c0 (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
// Copyright (C) 2019-2024 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 (
	"encoding/hex"
	"fmt"
	"strconv"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/algorand/go-algorand/config"
	"github.com/algorand/go-algorand/crypto"
	"github.com/algorand/go-algorand/data/basics"
	"github.com/algorand/go-algorand/data/transactions"
	"github.com/algorand/go-algorand/protocol"
	"github.com/algorand/go-algorand/test/partitiontest"
)

func makeApp(li uint64, lb uint64, gi uint64, gb uint64) basics.AppParams {
	return basics.AppParams{
		ApprovalProgram:   []byte{},
		ClearStateProgram: []byte{},
		GlobalState:       map[string]basics.TealValue{},
		StateSchemas: basics.StateSchemas{
			LocalStateSchema:  basics.StateSchema{NumUint: li, NumByteSlice: lb},
			GlobalStateSchema: basics.StateSchema{NumUint: gi, NumByteSlice: gb},
		},
		ExtraProgramPages: 0,
	}
}

func makeSampleEnv() (*EvalParams, *transactions.Transaction, *Ledger) {
	return makeSampleEnvWithVersion(LogicVersion)
}

func makeSampleEnvWithVersion(version uint64) (*EvalParams, *transactions.Transaction, *Ledger) {
	if version < appsEnabledVersion {
		panic("makeSampleEnv is for apps, but you've asked for a version before apps work")
	}
	firstTxn := makeSampleTxn()
	firstTxn.Txn.Type = protocol.ApplicationCallTx
	ep := defaultAppParamsWithVersion(version, makeSampleTxnGroup(firstTxn)...)
	ledger := NewLedger(nil)
	ep.SigLedger = ledger
	ep.Ledger = ledger
	return ep, &ep.TxnGroup[0].Txn, ledger
}

func makeOldAndNewEnv(version uint64) (*EvalParams, *EvalParams, *Ledger) {
	new, _, sharedLedger := makeSampleEnvWithVersion(version)
	old, _, _ := makeSampleEnvWithVersion(version - 1)
	old.Ledger = sharedLedger
	return old, new, sharedLedger
}

func (r *resources) String() string {
	sb := strings.Builder{}
	if len(r.createdAsas) > 0 {
		fmt.Fprintf(&sb, "createdAsas: %v\n", r.createdAsas)
	}
	if len(r.createdApps) > 0 {
		fmt.Fprintf(&sb, "createdApps: %v\n", r.createdApps)
	}

	if len(r.sharedAccounts) > 0 {
		fmt.Fprintf(&sb, "sharedAccts:\n")
		for addr := range r.sharedAccounts {
			fmt.Fprintf(&sb, " %s\n", addr)
		}
	}
	if len(r.sharedAsas) > 0 {
		fmt.Fprintf(&sb, "sharedAsas:\n")
		for id := range r.sharedAsas {
			fmt.Fprintf(&sb, " %d\n", id)
		}
	}
	if len(r.sharedApps) > 0 {
		fmt.Fprintf(&sb, "sharedApps:\n")
		for id := range r.sharedApps {
			fmt.Fprintf(&sb, " %d\n", id)
		}
	}

	if len(r.sharedHoldings) > 0 {
		fmt.Fprintf(&sb, "sharedHoldings:\n")
		for hl := range r.sharedHoldings {
			fmt.Fprintf(&sb, " %s x %d\n", hl.Address, hl.Asset)
		}
	}
	if len(r.sharedLocals) > 0 {
		fmt.Fprintf(&sb, "sharedLocals:\n")
		for hl := range r.sharedLocals {
			fmt.Fprintf(&sb, " %s x %d\n", hl.Address, hl.App)
		}
	}

	return sb.String()
}

func TestEvalModes(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()
	// ed25519verify* and err are tested separately below

	// check modeAny (v1 + txna/gtxna) are available in RunModeSignature
	// check all opcodes available in runModeApplication
	opcodesRunModeAny := `intcblock 0 1 1 1 1 500 100
	bytecblock "ALGO" 0x1337 0x2001 0xdeadbeef 0x70077007
bytec 0
sha256
keccak256
sha512_256
sha3_256
len
intc_0
+
intc_1
-
intc_2
/
intc_3
*
intc 4
<
intc_1
>
intc_1
<=
intc_1
>=
intc_1
&&
intc_1
||
bytec_1
bytec_2
!=
bytec_3
bytec 4
==
!
itob
btoi
%	// use values left after bytes comparison
|
intc_1
&
txn Fee
^
global MinTxnFee
~
gtxn 0 LastValid
mulw
pop
store 0
load 0
bnz label
label:
dup
pop
txna Accounts 0
gtxna 0 ApplicationArgs 0
==
`
	opcodesRunModeSignature := `arg_0
arg_1
!=
arg_2
arg_3
!=
&&
txn Sender
arg 4
!=
&&
!=
&&
`

	opcodesRunModeApplication := `txn Sender
balance
&&
txn Sender
min_balance
&&
txn Sender
intc 6  // 100
app_opted_in
&&
txn Sender
bytec_0 // ALGO
intc_1
app_local_put
bytec_0
intc_1
app_global_put
txn Sender
intc 6
bytec_0
app_local_get_ex
pop
&&
int 0
bytec_0
app_global_get_ex
pop
&&
txn Sender
bytec_0
app_local_del
bytec_0
app_global_del
txn Sender
intc 5 // 500
asset_holding_get AssetBalance
pop
&&
intc 5 // 500
asset_params_get AssetTotal
pop
&&
!=
bytec_0
log
`
	tests := map[RunMode]string{
		ModeSig: opcodesRunModeAny + opcodesRunModeSignature,
		ModeApp: opcodesRunModeAny + opcodesRunModeApplication,
	}

	for mode, test := range tests {
		mode, test := mode, test
		t.Run(fmt.Sprintf("opcodes_mode=%d", mode), func(t *testing.T) {
			t.Parallel()

			ep, tx, ledger := makeSampleEnv()
			ep.TxnGroup[0].Lsig.Args = [][]byte{
				tx.Sender[:],
				tx.Receiver[:],
				tx.CloseRemainderTo[:],
				tx.VotePK[:],
				tx.SelectionPK[:],
				tx.Note,
			}
			tx.ApplicationID = 100
			tx.ForeignAssets = []basics.AssetIndex{500} // needed since v4
			params := basics.AssetParams{
				Total:         1000,
				Decimals:      2,
				DefaultFrozen: false,
				UnitName:      "ALGO",
				AssetName:     "",
				URL:           string(protocol.PaymentTx),
				Manager:       tx.Sender,
				Reserve:       tx.Receiver,
				Freeze:        tx.Receiver,
				Clawback:      tx.Receiver,
			}
			algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
			ledger.NewAccount(tx.Sender, 1)
			ledger.NewApp(tx.Sender, 100, basics.AppParams{})
			ledger.NewLocals(tx.Sender, 100)
			ledger.NewLocal(tx.Sender, 100, "ALGO", algoValue)
			ledger.NewAsset(tx.Sender, 5, params)

			if mode == ModeSig {
				ep.runMode = ModeSig
				testLogic(t, test, AssemblerMaxVersion, ep)
				ep.runMode = ModeApp
			} else {
				testApp(t, test, ep)
			}
		})
	}

	// check err opcode work in both modes
	source := "err"
	testLogic(t, source, AssemblerMaxVersion, nil, "err opcode executed")
	testApp(t, source, nil, "err opcode executed")

	// check that ed25519verify and arg is not allowed in stateful mode between v2-v4
	disallowedV4 := []string{
		"byte 0x01; int 32; bzero; int 64; bzero; ed25519verify",
		"arg 0",
		"arg_0",
		"arg_1",
		"arg_2",
		"arg_3",
	}
	for _, source := range disallowedV4 {
		ops := testProg(t, source, 4)
		testAppBytes(t, ops.Program, nil,
			"not allowed in current mode", "not allowed in current mode")
	}

	// check that arg is not allowed in stateful mode beyond v5
	disallowed := []string{
		"arg 0",
		"arg_0",
		"arg_1",
		"arg_2",
		"arg_3",
	}
	for _, source := range disallowed {
		ops := testProg(t, source, AssemblerMaxVersion)
		testAppBytes(t, ops.Program, nil,
			"not allowed in current mode", "not allowed in current mode")
	}

	// check stateful opcodes are not allowed in stateless mode
	for v := uint64(2); v <= AssemblerMaxVersion; v++ {
		sender := "txn Sender;"
		if v < directRefEnabledVersion {
			sender = "int 0;"
		}
		statefulOpcodeCalls := map[string]uint64{
			sender + "balance":                                2,
			sender + "min_balance":                            3,
			sender + "int 0; app_opted_in":                    2,
			sender + "int 0; byte 0x01; app_local_get_ex":     2,
			"byte 0x01; app_global_get":                       2,
			"int 0; byte 0x01; app_global_get_ex":             2,
			sender + "byte 0x01; byte 0x01; app_local_put":    2,
			"byte 0x01; int 0; app_global_put":                2,
			sender + "byte 0x01; app_local_del":               2,
			"byte 0x01; app_global_del":                       2,
			sender + "int 0; asset_holding_get AssetFrozen":   2,
			"int 0; int 0; asset_params_get AssetManager":     2,
			"int 0; int 0; app_params_get AppApprovalProgram": 5,
			"byte 0x01; log":                                  5,
			sender + "acct_params_get AcctBalance":            7,

			"byte 0x1234; int 12; box_create":             8,
			"byte 0x1234; int 12; int 4; box_extract":     8,
			"byte 0x1234; int 12; byte 0x24; box_replace": 8,
			"byte 0x1234; box_del":                        8,
			"byte 0x1234; box_len":                        8,
			"byte 0x1234; box_get":                        8,
			"byte 0x1234; byte 0x12; box_put":             8,
		}
		for source, introduced := range statefulOpcodeCalls {
			if v < introduced {
				continue
			}
			testLogic(t, source, v, defaultSigParamsWithVersion(v),
				"not allowed in current mode", "not allowed in current mode")
		}
	}

	require.Equal(t, RunMode(1), ModeSig)
	require.Equal(t, RunMode(2), ModeApp)
	require.True(t, modeAny == ModeSig|ModeApp)
	require.True(t, modeAny.Any())
}

func TestApplicationsDisallowOldTeal(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	const source = "int 1"

	txn := makeSampleTxn()
	txn.Txn.Type = protocol.ApplicationCallTx
	txn.Txn.RekeyTo = basics.Address{}
	ep := defaultAppParams(txn)

	for v := uint64(0); v < appsEnabledVersion; v++ {
		ops := testProg(t, source, v)
		e := fmt.Sprintf("program version must be >= %d", appsEnabledVersion)
		testAppBytes(t, ops.Program, ep, e, e)
	}

	testApp(t, source, ep)
}

func TestBalance(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	testLogicRange(t, 2, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
		v := ep.Proto.LogicSigVersion
		ledger.NewAccount(tx.Receiver, 177)
		testApp(t, "int 2; balance; int 177; ==", ep, "invalid Account reference")
		testApp(t, `int 1; balance; int 177; ==`, ep)

		source := `txn Accounts 1; balance; int 177; ==;`
		// won't assemble in old version teal
		if v < directRefEnabledVersion {
			testProg(t, source, ep.Proto.LogicSigVersion,
				exp(1, "balance arg 0 wanted type uint64..."))
			return
		}

		// but legal after that
		testApp(t, source, ep)

		source = "txn Sender; balance; int 13; ==; assert; int 1"
		testApp(t, source, ep, "assert failed")

		ledger.NewAccount(tx.Sender, 13)
		testApp(t, source, ep)
	})
}

func testApps(t *testing.T, programs []string, txgroup []transactions.SignedTxn, opt protoOpt, ledger *Ledger,
	expected ...expect) (*EvalParams, error) {
	t.Helper()
	proto := makeTestProto(opt)
	codes := make([][]byte, len(programs))
	for i, program := range programs {
		if program != "" {
			codes[i] = testProg(t, program, proto.LogicSigVersion).Program
		}
	}
	if txgroup == nil {
		for _, program := range programs {
			sample := makeSampleTxn()
			if program != "" {
				sample.Txn.Type = protocol.ApplicationCallTx
			}
			txgroup = append(txgroup, sample)
		}
	}
	ep := NewAppEvalParams(transactions.WrapSignedTxnsWithAD(txgroup), proto, &transactions.SpecialAddresses{})
	if ledger == nil {
		ledger = NewLedger(nil)
	}
	ledger.Reset()
	ep.Ledger = ledger
	ep.SigLedger = ledger
	return ep, testAppsBytes(t, codes, ep, expected...)
}

func testAppsBytes(t *testing.T, programs [][]byte, ep *EvalParams, expected ...expect) error {
	t.Helper()
	require.LessOrEqual(t, len(programs), len(ep.TxnGroup))
	for i := range ep.TxnGroup {
		program := ep.TxnGroup[i].Txn.ApprovalProgram
		if len(programs) > i && programs[i] != nil {
			program = programs[i]
		}
		if program != nil {
			appID := ep.TxnGroup[i].Txn.ApplicationID
			if appID == 0 {
				appID = basics.AppIndex(888)
			}
			if len(expected) > 0 && expected[0].l == i {
				// Stop after first failure
				_, err := testAppFull(t, program, i, appID, ep, expected[0].s)
				return err
			}
			testAppFull(t, program, i, appID, ep)
		} else {
			if len(expected) > 0 && expected[0].l == i {
				require.Failf(t, "testAppsBytes used incorrectly.", "No error can happen in txn %d. Not an app.", i)
			}
		}
	}
	return nil
}

func testApp(t *testing.T, program string, ep *EvalParams, problems ...string) (transactions.EvalDelta, error) {
	t.Helper()
	if ep == nil {
		ep = defaultAppParamsWithVersion(LogicVersion)
	}
	ops := testProg(t, program, ep.Proto.LogicSigVersion)
	return testAppBytes(t, ops.Program, ep, problems...)
}

func testAppBytes(t *testing.T, program []byte, ep *EvalParams, problems ...string) (transactions.EvalDelta, error) {
	t.Helper()
	if ep == nil {
		ep = defaultAppParamsWithVersion(LogicVersion)
	} else {
		ep.reset()
	}
	aid := ep.TxnGroup[0].Txn.ApplicationID
	if aid == 0 {
		aid = basics.AppIndex(888)
	}
	return testAppFull(t, program, 0, aid, ep, problems...)
}

// testAppFull gives a lot of control to caller - in particular, notice that
// ep.reset() is in testAppBytes, not here. This means that ADs in the ep are
// not cleared, so repeated use of a single ep is probably not a good idea
// unless you are *intending* to see how ep is modified as you go.
func testAppFull(t *testing.T, program []byte, gi int, aid basics.AppIndex, ep *EvalParams, problems ...string) (transactions.EvalDelta, error) {
	t.Helper()

	var checkProblem string
	var evalProblem string
	switch len(problems) {
	case 2:
		checkProblem = problems[0]
		evalProblem = problems[1]
	case 1:
		evalProblem = problems[0]
	case 0:
		// no problems == expect success
	default:
		require.Fail(t, "Misused testApp: %d problems", len(problems))
	}

	ep.Trace = &strings.Builder{}

	err := CheckContract(program, ep)
	if checkProblem == "" {
		require.NoError(t, err, "Error in CheckContract %v", ep.Trace)
	} else {
		require.ErrorContains(t, err, checkProblem, "Wrong error in CheckContract %v", ep.Trace)
	}

	// We continue on to check Eval() of things that failed Check() because it's
	// a nice confirmation that Check() is usually stricter than Eval(). This
	// may mean that the problems argument is often duplicated, but this seems
	// the best way to be concise about all sorts of tests.

	if ep.Ledger == nil {
		ep.Ledger = NewLedger(nil)
	}

	pass, err := EvalApp(program, gi, aid, ep)
	delta := ep.TxnGroup[gi].EvalDelta
	if evalProblem == "" {
		require.NoError(t, err, "Eval\n%sExpected: PASS", ep.Trace)
		require.True(t, pass, "Eval\n%sExpected: PASS", ep.Trace)
		return delta, nil
	}

	// There is an evalProblem to check. REJECT is special and only means that
	// the app didn't accept.  Maybe it's an error, maybe it's just !pass.
	if evalProblem == "REJECT" {
		require.True(t, err != nil || !pass, "Eval%s\nExpected: REJECT", ep.Trace)
	} else {
		require.ErrorContains(t, err, evalProblem, "Wrong error in EvalContract %v", ep.Trace)
	}
	return delta, err
}

// testLogicRange allows for running tests against a range of avm
// versions. Generally `start` will be the version that introduced the feature,
// and `stop` will be 0 to indicate it should work right on up through the
// current version.  `stop` will be an actual version number if we're confirming
// that something STOPS working as of a particular version. Note that this does
// *not* use different consensus versions. It is tempting to make it find the
// lowest possible consensus version in the loop in order to support the `v` it
// it working on.  For super confidence, one might argue this should be a nested
// loop over all of the consensus versions that work with the `v`, from the
// first possible, to vFuture.
func testLogicRange(t *testing.T, start, stop int, test func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger)) {
	t.Helper()
	if stop == 0 { // Treat 0 as current max
		stop = LogicVersion
	}

	for v := uint64(start); v <= uint64(stop); v++ {
		t.Run(fmt.Sprintf("v=%d", v), func(t *testing.T) {
			ep, tx, ledger := makeSampleEnvWithVersion(v)
			test(t, ep, tx, ledger)
		})
	}
}

func TestMinBalance(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	// since v3 is before directRefEnabledVersion, do a quick test on it separately
	ep, tx, ledger := makeSampleEnvWithVersion(3)
	ledger.NewAccount(tx.Sender, 100)

	testApp(t, "int 0; min_balance; int 1001; ==", ep)
	// Sender makes an asset, min balance goes up
	ledger.NewAsset(tx.Sender, 7, basics.AssetParams{Total: 1000})
	testApp(t, "int 0; min_balance; int 2002; ==", ep)

	// now test in more detail v4 and on
	testLogicRange(t, 4, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
		ledger.NewAccount(tx.Sender, 234)
		ledger.NewAccount(tx.Receiver, 123)
		testApp(t, "txn Sender; min_balance; int 1001; ==", ep)
		// Sender makes an asset, min balance goes up
		ledger.NewAsset(tx.Sender, 7, basics.AssetParams{Total: 1000})
		testApp(t, "txn Sender; min_balance; int 2002; ==", ep)
		schemas := makeApp(1, 2, 3, 4)
		ledger.NewApp(tx.Sender, 77, schemas)
		ledger.NewLocals(tx.Sender, 77)
		// create + optin + 10 schema base + 4 ints + 6 bytes (local
		// and global count b/c NewLocals opts the creator in)
		minb := 1002 + 1006 + 10*1003 + 4*1004 + 6*1005
		testApp(t, fmt.Sprintf("txn Sender; min_balance; int %d; ==", 2002+minb), ep)
		// request extra program pages, min balance increase
		withepp := makeApp(1, 2, 3, 4)
		withepp.ExtraProgramPages = 2
		ledger.NewApp(tx.Sender, 77, withepp)
		minb += 2 * 1002
		testApp(t, fmt.Sprintf("txn Sender; min_balance; int %d; ==", 2002+minb), ep)

		testApp(t, "txn Accounts 1; min_balance; int 1001; ==", ep)
		// Receiver opts in
		ledger.NewHolding(tx.Receiver, 7, 1, true)
		testApp(t, "txn Receiver; min_balance; int 2002; ==", ep)
	})
}

func TestAppCheckOptedIn(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	pre, now, ledger := makeOldAndNewEnv(directRefEnabledVersion)

	txn := pre.TxnGroup[0]
	ledger.NewAccount(txn.Txn.Receiver, 1)
	ledger.NewAccount(txn.Txn.Sender, 1)
	testApp(t, "int 2; int 100; app_opted_in; int 1; ==", now, "invalid Account reference")

	// Receiver is not opted in
	testApp(t, "int 1; int 100; app_opted_in; int 0; ==", now)
	testApp(t, "int 1; int 0; app_opted_in; int 0; ==", now)
	// These two give the same result, for different reasons
	testApp(t, "int 1; int 3; app_opted_in; int 0; ==", now) // refers to tx.ForeignApps[2], which is 111
	testApp(t, "int 1; int 3; app_opted_in; int 0; ==", pre) // not an indirect reference: actually app 3
	// 0 is a legal way to refer to the current app, even in pre (though not in spec)
	// but current app is 888 - not opted in
	testApp(t, "int 1; int 0; app_opted_in; int 0; ==", pre)

	// Sender is not opted in
	testApp(t, "int 0; int 100; app_opted_in; int 0; ==", now)

	// Receiver opted in
	ledger.NewLocals(txn.Txn.Receiver, 100)
	testApp(t, "int 1; int 100; app_opted_in; int 1; ==", now)
	testApp(t, "int 1; int 2; app_opted_in; int 1; ==", now) // tx.ForeignApps[1] == 100
	testApp(t, "int 1; int 2; app_opted_in; int 0; ==", pre) // in pre, int 2 is an actual app id
	testApp(t, "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01\"; int 2; app_opted_in; int 1; ==", now)
	testProg(t, "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01\"; int 2; app_opted_in; int 1; ==", directRefEnabledVersion-1,
		exp(1, "app_opted_in arg 0 wanted type uint64..."))

	// Receiver opts into 888, the current app in testApp
	ledger.NewLocals(txn.Txn.Receiver, 888)
	// int 0 is current app (888) even in pre
	testApp(t, "int 1; int 0; app_opted_in; int 1; ==", pre)
	// Here it is "obviously" allowed, because indexes became legal
	testApp(t, "int 1; int 0; app_opted_in; int 1; ==", now)

	// Sender opted in
	ledger.NewLocals(txn.Txn.Sender, 100)
	testApp(t, "int 0; int 100; app_opted_in; int 1; ==", now)
}

func TestAppReadLocalState(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()

	text := `int 2  // account idx
int 100 // app id
txn ApplicationArgs 0
app_local_get_ex
bnz exist
int 0
==
bnz exit
exist:
err
exit:
int 1
==`

	pre, now, ledger := makeOldAndNewEnv(directRefEnabledVersion)
	ledger.NewAccount(now.TxnGroup[0].Txn.Receiver, 1)
	testApp(t, text, now, "invalid Account reference")

	text = `int 1  // account idx
int 100 // app id
txn ApplicationArgs 0
app_local_get_ex
bnz exist
int 0
==
bnz exit
exist:
err
exit:
int 1`

	testApp(t, text, now, "is not opted into")

	// Make a different app (not 100)
	ledger.NewApp(now.TxnGroup[0].Txn.Receiver, 9999, basics.AppParams{})
	testApp(t, text, now, "is not opted into")

	// create the app and check the value from ApplicationArgs[0] (protocol.PaymentTx) does not exist
	ledger.NewApp(now.TxnGroup[0].Txn.Receiver, 100, basics.AppParams{})
	ledger.NewLocals(now.TxnGroup[0].Txn.Receiver, 100)
	testApp(t, text, now)

	text = `int 1  // account idx
int 100 // app id
txn ApplicationArgs 0
app_local_get_ex
bnz exist
err
exist:
byte "ALGO"
==`
	ledger.NewLocal(now.TxnGroup[0].Txn.Receiver, 100, string(protocol.PaymentTx), basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"})

	testApp(t, text, now)
	testApp(t, strings.Replace(text, "int 1  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01\"", -1), now)
	testProg(t, strings.Replace(text, "int 1  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01\"", -1), directRefEnabledVersion-1,
		exp(4, "app_local_get_ex arg 0 wanted type uint64..."))
	testApp(t, strings.Replace(text, "int 100 // app id", "int 2", -1), now)
	// Next we're testing if the use of the current app's id works
	// as a direct reference. The error is because the receiver
	// account is not opted into 123.
	now.TxnGroup[0].Txn.ApplicationID = 123
	testApp(t, strings.Replace(text, "int 100 // app id", "int 123", -1), now, "is not opted into")
	testApp(t, strings.Replace(text, "int 100 // app id", "int 2", -1), pre, "is not opted into")
	testApp(t, strings.Replace(text, "int 100 // app id", "int 9", -1), now, "unavailable App 9")
	testApp(t, strings.Replace(text, "int 1  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), now,
		"no account")

	// opt into 123, and try again
	ledger.NewApp(now.TxnGroup[0].Txn.Receiver, 123, basics.AppParams{})
	ledger.NewLocals(now.TxnGroup[0].Txn.Receiver, 123)
	ledger.NewLocal(now.TxnGroup[0].Txn.Receiver, 123, string(protocol.PaymentTx), basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"})
	testApp(t, strings.Replace(text, "int 100 // app id", "int 123", -1), now)
	testApp(t, strings.Replace(text, "int 100 // app id", "int 0", -1), now)

	// Somewhat surprising, but in `pre` when the app argument was expected to be
	// an actual app id (not an index in foreign apps), 0 was *still* treated
	// like current app.
	pre.TxnGroup[0].Txn.ApplicationID = 123
	testApp(t, strings.Replace(text, "int 100 // app id", "int 0", -1), pre)

	// check special case account idx == 0 => sender
	ledger.NewApp(now.TxnGroup[0].Txn.Sender, 100, basics.AppParams{})
	ledger.NewLocals(now.TxnGroup[0].Txn.Sender, 100)
	text = `int 0  // account idx
int 100 // app id
txn ApplicationArgs 0
app_local_get_ex
bnz exist
err
exist:
byte "ALGO"
==`

	ledger.NewLocal(now.TxnGroup[0].Txn.Sender, 100, string(protocol.PaymentTx), basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"})
	testApp(t, text, now)
	testApp(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), now)
	testApp(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui02\"", -1), now,
		"invalid Account reference")

	// check reading state of other app
	ledger.NewApp(now.TxnGroup[0].Txn.Sender, 56, basics.AppParams{})
	ledger.NewApp(now.TxnGroup[0].Txn.Sender, 100, basics.AppParams{})
	text = `int 0  // account idx
int 56 // app id
txn ApplicationArgs 0
app_local_get_ex
bnz exist
err
exist:
byte "ALGO"
==`

	ledger.NewLocals(now.TxnGroup[0].Txn.Sender, 56)
	ledger.NewLocal(now.TxnGroup[0].Txn.Sender, 56, string(protocol.PaymentTx), basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"})
	testApp(t, text, now)

	// check app_local_get
	text = `int 0  // account idx
txn ApplicationArgs 0
app_local_get
byte "ALGO"
==`

	ledger.NewLocal(now.TxnGroup[0].Txn.Sender, 100, string(protocol.PaymentTx), basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"})
	now.TxnGroup[0].Txn.ApplicationID = 100
	testApp(t, text, now)
	testApp(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), now)
	testProg(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), directRefEnabledVersion-1,
		exp(3, "app_local_get arg 0 wanted type uint64..."))
	testApp(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01\"", -1), now)
	testApp(t, strings.Replace(text, "int 0  // account idx", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui02\"", -1), now,
		"invalid Account reference")

	// check app_local_get default value
	text = `int 0  // account idx
byte "ALGO"
app_local_get
int 0
==`

	ledger.NewLocal(now.TxnGroup[0].Txn.Sender, 100, string(protocol.PaymentTx), basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"})
	testApp(t, text, now)
}

// TestAppErrorDetails confirms that the error returned from app failures
// has the right structured information.
func TestAppErrorDetails(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	badsource := notrack(`
byte 0x04040004; log			// log
int 5; store 10					// store an int
byte 0x01020300; store 15		// store a bytes

int 100; byte 0x0201; == // types mismatch so this will fail
`)
	_, err := testApp(t, badsource, nil, "cannot compare")
	attrs := basics.Attributes(err)
	zeros := [256]int{}
	scratch := convertSlice(zeros[:], func(i int) any { return uint64(i) })
	scratch[10] = uint64(5)
	scratch[15] = []byte{0x01, 0x02, 0x03, 0x00}
	require.Equal(t, map[string]any{
		"pc":          26,
		"group-index": 0,
		"app-index":   basics.AppIndex(888),
		"eval-states": []evalState{
			{
				Logs:    [][]byte{{0x04, 0x04, 0x00, 0x04}},
				Stack:   []any{uint64(100), []byte{02, 01}},
				Scratch: scratch[:16],
			},
		},
	}, attrs)

	goodsource := `
byte 0x04040104; log			// log
byte 0x04040204; log			// log

int 4; store 2			// store an int
byte "jj"; store 3		// store a bytes
int 1
`
	gscratch := convertSlice(zeros[:], func(i int) any { return uint64(i) })
	gscratch[2] = uint64(4)
	gscratch[3] = []byte("jj")

	_, err = testApps(t, []string{goodsource, badsource}, nil, nil, nil, exp(1, "cannot compare"))
	attrs = basics.Attributes(err)
	require.Equal(t, map[string]any{
		"pc":          26,
		"group-index": 1,
		"app-index":   basics.AppIndex(888),
		"eval-states": []evalState{
			{
				Logs: [][]byte{
					{0x04, 0x04, 0x01, 0x04},
					{0x04, 0x04, 0x02, 0x04},
				},
				Scratch: gscratch[:4],
			},
			{
				Logs:    [][]byte{{0x04, 0x04, 0x00, 0x04}},
				Stack:   []any{uint64(100), []byte{02, 01}},
				Scratch: scratch[:16],
			},
		},
	}, attrs)

	_, _, ledger := makeSampleEnv()
	ledger.NewAccount(appAddr(888), 100_000)
	bad := testProg(t, badsource, 5)
	innerFailSource := `
int 777
itxn_begin
int appl; itxn_field TypeEnum
byte 0x` + hex.EncodeToString(bad.Program) + ` // run the bad program by trying to create it
itxn_field ApprovalProgram

byte 0x05
itxn_field ClearStateProgram

itxn_submit
`
	_, err = testApps(t, []string{goodsource, innerFailSource}, nil, nil, ledger, exp(1, "inner tx 0 failed"))
	attrs = basics.Attributes(err)
	require.Equal(t, map[string]any{
		"pc":          45,
		"group-index": 1,
		"app-index":   basics.AppIndex(888),
		"eval-states": []evalState{
			{
				Logs: [][]byte{
					{0x04, 0x04, 0x01, 0x04},
					{0x04, 0x04, 0x02, 0x04},
				},
				Scratch: gscratch[:4],
			},
			{
				Stack: []any{uint64(777)},
			},
		},
		"inner-msg": "logic eval error: cannot compare (uint64 to []byte). Details: app=5000, pc=26, opcodes=pushint 100; pushbytes 0x0201 // 0x0201; ==",
		"inner-attrs": map[string]any{
			"pc":          26,
			"group-index": 0,
			"app-index":   basics.AppIndex(firstTestID),
			"eval-states": []evalState{
				{
					Logs:    [][]byte{{0x04, 0x04, 0x00, 0x04}},
					Stack:   []any{uint64(100), []byte{02, 01}},
					Scratch: scratch[:16],
				},
			},
		},
	}, attrs)

}

func TestAppReadGlobalState(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	text := `int 0
txn ApplicationArgs 0
app_global_get_ex
bnz exist
err
exist:
byte "ALGO"
==
int 1  // ForeignApps index
txn ApplicationArgs 0
app_global_get_ex
bnz exist1
err
exist1:
byte "ALGO"
==
&&
txn ApplicationArgs 0
app_global_get
byte "ALGO"
==
&&
`
	pre, now, ledger := makeOldAndNewEnv(directRefEnabledVersion)
	ledger.NewAccount(now.TxnGroup[0].Txn.Sender, 1)

	now.TxnGroup[0].Txn.ApplicationID = 100
	now.TxnGroup[0].Txn.ForeignApps = []basics.AppIndex{now.TxnGroup[0].Txn.ApplicationID}
	testApp(t, text, now, "no app 100")

	// create the app and check the value from ApplicationArgs[0] (protocol.PaymentTx) does not exist
	ledger.NewApp(now.TxnGroup[0].Txn.Sender, 100, basics.AppParams{})

	testApp(t, text, now, "err opcode")

	ledger.NewGlobal(100, string(protocol.PaymentTx), basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"})

	testApp(t, text, now)

	// check error on invalid app index for app_global_get_ex
	text = "int 2; txn ApplicationArgs 0; app_global_get_ex"
	testApp(t, text, now, "unavailable App 2")
	// check that actual app id ok instead of indirect reference
	text = `int 100; txn ApplicationArgs 0; app_global_get_ex; int 1; ==; assert; byte "ALGO"; ==`
	testApp(t, text, now)
	testApp(t, text, pre, "App index 100 beyond") // but not in old teal

	// check app_global_get default value
	text = "byte 0x414c474f55; app_global_get; int 0; =="

	ledger.NewLocals(now.TxnGroup[0].Txn.Sender, 100)
	ledger.NewLocal(now.TxnGroup[0].Txn.Sender, 100, string(protocol.PaymentTx), basics.TealValue{Type: basics.TealBytesType, Bytes: "ALGO"})
	testApp(t, text, now)

	text = `
byte 0x41414141
int 4141
app_global_put
int 1  // ForeignApps index
byte 0x41414141
app_global_get_ex
bnz exist
err
exist:
int 4141
==
`
	// check that even during application creation (Txn.ApplicationID == 0)
	// we will use the the kvCow if the exact application ID (100) is
	// specified in the transaction
	now.TxnGroup[0].Txn.ApplicationID = 0
	now.TxnGroup[0].Txn.ForeignApps = []basics.AppIndex{100}

	testAppFull(t, testProg(t, text, directRefEnabledVersion).Program, 0, 100, now)

	// Direct reference to the current app also works
	now.TxnGroup[0].Txn.ForeignApps = []basics.AppIndex{}
	testAppFull(t, testProg(t, strings.Replace(text, "int 1  // ForeignApps index", "int 100", -1), directRefEnabledVersion).Program,
		0, 100, now)
	testAppFull(t, testProg(t, strings.Replace(text, "int 1  // ForeignApps index", "global CurrentApplicationID", -1), directRefEnabledVersion).Program,
		0, 100, now)
}

const assetsTestTemplate = `int 0//account
int 55
asset_holding_get AssetBalance
!
bnz error
int 123
==
int 0//account
int 55
asset_holding_get AssetFrozen
!
bnz error
int 1
==
&&
int 0//params
asset_params_get AssetTotal
!
bnz error
int 1000
==
&&
int 0//params
asset_params_get AssetDecimals
!
bnz error
int 2
==
&&
int 0//params
asset_params_get AssetDefaultFrozen
!
bnz error
int 0
==
&&
int 0//params
asset_params_get AssetUnitName
!
bnz error
byte "ALGO"
==
&&
int 0//params
asset_params_get AssetName
!
bnz error
len
int 0
==
&&
int 0//params
asset_params_get AssetURL
!
bnz error
txna ApplicationArgs 0
==
&&
int 0//params
asset_params_get AssetMetadataHash
!
bnz error
byte 0x0000000000000000000000000000000000000000000000000000000000000000
==
&&
int 0//params
asset_params_get AssetManager
!
bnz error
txna Accounts 0
==
&&
int 0//params
asset_params_get AssetReserve
!
bnz error
txna Accounts 1
==
&&
int 0//params
asset_params_get AssetFreeze
!
bnz error
txna Accounts 1
==
&&
int 0//params
asset_params_get AssetClawback
!
bnz error
txna Accounts 1
==
&&
bnz ok
error:
err
ok:
%s
int 1
`

const v5extras = `
int 0//params
asset_params_get AssetCreator
pop
txn Sender
==
assert
`

func TestAssets(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()
	tests := map[uint64]string{
		4: fmt.Sprintf(assetsTestTemplate, ""),
		5: fmt.Sprintf(assetsTestTemplate, v5extras),
	}

	for v, source := range tests {
		testAssetsByVersion(t, source, v)
	}
}

func testAssetsByVersion(t *testing.T, assetsTestProgram string, version uint64) {
	for _, field := range assetHoldingFieldNames {
		fs := assetHoldingFieldSpecByName[field]
		if fs.version <= version && !strings.Contains(assetsTestProgram, field) {
			t.Errorf("TestAssets missing field %v", field)
		}
	}
	for _, field := range assetParamsFieldNames {
		fs := assetParamsFieldSpecByName[field]
		if fs.version <= version && !strings.Contains(assetsTestProgram, field) {
			t.Errorf("TestAssets missing field %v", field)
		}
	}

	txn := makeSampleAppl(888)
	pre := defaultAppParamsWithVersion(directRefEnabledVersion-1, txn)
	require.GreaterOrEqual(t, version, uint64(directRefEnabledVersion))
	now := defaultAppParamsWithVersion(version, txn)
	ledger := NewLedger(
		map[basics.Address]uint64{
			txn.Txn.Sender: 1,
		},
	)
	pre.Ledger = ledger
	now.Ledger = ledger

	// bear in mind: the sample transaction has ForeignAccounts{55,77}
	testApp(t, "int 5; int 55; asset_holding_get AssetBalance", now, "invalid Account reference 5")
	// was legal to get balance on a non-ForeignAsset
	testApp(t, "int 0; int 54; asset_holding_get AssetBalance; ==", pre)
	// but not since directRefEnabledVersion
	testApp(t, "int 0; int 54; asset_holding_get AssetBalance", now, "unavailable Asset 54")

	// it wasn't legal to use a direct ref for account
	testProg(t, `byte "aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00"; int 54; asset_holding_get AssetBalance`,
		directRefEnabledVersion-1, exp(1, "asset_holding_get AssetBalance arg 0 wanted type uint64..."))
	// but it is now (empty asset yields 0,0 on stack)
	testApp(t, `byte "aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00"; int 55; asset_holding_get AssetBalance; ==`, now)
	// This is receiver, who is in Assets array
	testApp(t, `byte "aoeuiaoeuiaoeuiaoeuiaoeuiaoeui01"; int 55; asset_holding_get AssetBalance; ==`, now)
	// But this is not in Assets, so illegal
	testApp(t, `byte "aoeuiaoeuiaoeuiaoeuiaoeuiaoeui02"; int 55; asset_holding_get AssetBalance; ==`, now, "invalid")

	// for params get, presence in ForeignAssets has always be required
	testApp(t, "int 5; asset_params_get AssetTotal", pre, "Asset index 5 beyond")
	testApp(t, "int 5; asset_params_get AssetTotal", now, "unavailable Asset 5")

	params := basics.AssetParams{
		Total:         1000,
		Decimals:      2,
		DefaultFrozen: false,
		UnitName:      "ALGO",
		AssetName:     "",
		URL:           string(protocol.PaymentTx),
		Manager:       txn.Txn.Sender,
		Reserve:       txn.Txn.Receiver,
		Freeze:        txn.Txn.Receiver,
		Clawback:      txn.Txn.Receiver,
	}

	ledger.NewAsset(txn.Txn.Sender, 55, params)
	ledger.NewHolding(txn.Txn.Sender, 55, 123, true)
	// For consistency you can now use an indirect ref in holding_get
	// (recall ForeignAssets[0] = 55, which has balance 123)
	testApp(t, "int 0; int 0; asset_holding_get AssetBalance; int 1; ==; assert; int 123; ==", now)
	// but previous code would still try to read ASA 0
	testApp(t, "int 0; int 0; asset_holding_get AssetBalance; int 0; ==; assert; int 0; ==", pre)

	testApp(t, assetsTestProgram, now)

	// In current versions, can swap out the account index for the account
	testApp(t, strings.Replace(assetsTestProgram, "int 0//account", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), now)
	// Or an asset index for the asset id
	testApp(t, strings.Replace(assetsTestProgram, "int 0//params", "int 55", -1), now)
	// Or an index for the asset id
	testApp(t, strings.Replace(assetsTestProgram, "int 55", "int 0", -1), now)

	// but old code cannot
	testProg(t, strings.Replace(assetsTestProgram, "int 0//account", "byte \"aoeuiaoeuiaoeuiaoeuiaoeuiaoeui00\"", -1), directRefEnabledVersion-1, exp(3, "asset_holding_get AssetBalance arg 0 wanted type uint64..."))

	if version < 5 {
		// Can't run these with AppCreator anyway
		testApp(t, strings.Replace(assetsTestProgram, "int 0//params", "int 55", -1), pre, "Asset index 55 beyond")
		testApp(t, strings.Replace(assetsTestProgram, "int 55", "int 0", -1), pre, "err opcode")
	}

	// check holdings bool value
	source := `intcblock 0 55 1
intc_0  // 0, account idx (txn.Sender)
intc_1  // 55
asset_holding_get AssetFrozen
!
bnz error
intc_0 // 0
==
bnz ok
error:
err
ok:
intc_2 // 1
`
	ledger.NewHolding(txn.Txn.Sender, 55, 123, false)
	testApp(t, source, now)

	// check holdings invalid offsets
	ops := testProg(t, source, version)
	require.Equal(t, OpsByName[now.Proto.LogicSigVersion]["asset_holding_get"].Opcode, ops.Program[8])
	ops.Program[9] = 0x02
	_, err := EvalApp(ops.Program, 0, 888, now)
	require.Error(t, err)
	require.Contains(t, err.Error(), "invalid asset_holding_get field 2")

	// check holdings bool value
	source = `intcblock 0 1
intc_0
asset_params_get AssetDefaultFrozen
!
bnz error
intc_1
==
bnz ok
error:
err
ok:
intc_1
`
	params.DefaultFrozen = true
	ledger.NewAsset(txn.Txn.Sender, 55, params)
	testApp(t, source, now)
	// check holdings invalid offsets
	ops = testProg(t, source, version)
	require.Equal(t, OpsByName[now.Proto.LogicSigVersion]["asset_params_get"].Opcode, ops.Program[6])
	ops.Program[7] = 0x20
	_, err = EvalApp(ops.Program, 0, 888, now)
	require.Error(t, err)
	require.Contains(t, err.Error(), "invalid asset_params_get field 32")

	// check empty string
	source = `intcblock 0 1
intc_0  // foreign asset idx (txn.ForeignAssets[0])
asset_params_get AssetURL
!
bnz error
len
intc_0
==
bnz ok
error:
err
ok:
intc_1
`
	params.URL = ""
	ledger.NewAsset(txn.Txn.Sender, 55, params)
	testApp(t, source, now)

	source = `intcblock 1 9
intc_0  // foreign asset idx (txn.ForeignAssets[1])
asset_params_get AssetURL
!
bnz error
len
intc_1
==
bnz ok
error:
err
ok:
intc_0
`
	params.URL = "foobarbaz"
	ledger.NewAsset(txn.Txn.Sender, 77, params)
	testApp(t, source, now)

	source = `intcblock 0 1
intc_0
asset_params_get AssetURL
!
bnz error
intc_0
==
bnz ok
error:
err
ok:
intc_1
`
	params.URL = ""
	ledger.NewAsset(txn.Txn.Sender, 55, params)
	testApp(t, notrack(source), now, "cannot compare ([]byte to uint64)")
}

// TestAssetDisambiguation ensures we have a consistent interpretation of low
// numbers when used as an argument to asset_*_get. A low number is an asset ID
// if that asset ID is available, or a slot number in txn.Assets if not.
func TestAssetDisambiguation(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	// Make sure we don't treat slot indexes as asset IDs when
	// ep.UnnamedResources is not nil.
	for _, unnamedResources := range []bool{false, true} {
		unnamedResources := unnamedResources
		t.Run(fmt.Sprintf("unnamedResources=%v", unnamedResources), func(t *testing.T) {
			t.Parallel()
			// It would be nice to start at 2, when apps were added, but `assert` is
			// very convenient for testing, and nothing important changed from 2 to
			// 3. (Between directRefEnabledVersion=4, so that change is a big deal.)
			testLogicRange(t, 3, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
				if unnamedResources {
					ep.UnnamedResources = &mockUnnamedResourcePolicy{allowEverything: true}
				}
				ledger.NewAsset(tx.Sender, 1, basics.AssetParams{AssetName: "one", Total: 1})
				ledger.NewAsset(tx.Sender, 255, basics.AssetParams{AssetName: "twenty", Total: 255})
				ledger.NewAsset(tx.Sender, 256, basics.AssetParams{AssetName: "thirty", Total: 256})
				tx.ForeignAssets = []basics.AssetIndex{255, 256}
				// Since 1 is not available, 1 must mean the 1th asset slot = 256
				testApp(t, `int 1; asset_params_get AssetName; assert; byte "thirty"; ==`, ep)

				if ep.Proto.LogicSigVersion < directRefEnabledVersion {
					// in v3, the asset argument is always treated as an ID, so this is asset 1
					testApp(t, `int 0; int 1; asset_holding_get AssetBalance; assert; int 1; ==`, ep)
				} else {
					testApp(t, `int 0; int 1; asset_holding_get AssetBalance; assert; int 256; ==`, ep)
				}

				tx.ForeignAssets = []basics.AssetIndex{1, 256}
				if ep.Proto.LogicSigVersion < directRefEnabledVersion {
					// There's no direct use of assets IDs, so 1 is still the 1th slot (256)
					testApp(t, `int 1; asset_params_get AssetName; assert; byte "thirty"; ==`, ep)
				} else {
					// Since 1 IS available, 1 means the assetid=1, not the 1th slot
					testApp(t, `int 1; asset_params_get AssetName; assert; byte "one"; ==`, ep)
				}
				testApp(t, `int 0; int 1; asset_holding_get AssetBalance; assert; int 1; ==`, ep)

				ep.Proto.AppForbidLowResources = true
				tx.ForeignAssets = []basics.AssetIndex{255, 256}
				// Since 1 is not available, 1 must mean the 1th asset slot = 256
				testApp(t, `int 1; asset_params_get AssetName; assert; byte "thirty"; ==`, ep)
				if ep.Proto.LogicSigVersion < directRefEnabledVersion {
					// in v3, the asset argument is always treated as an ID, so this is asset 1
					testApp(t, `int 0; int 1; asset_holding_get AssetBalance; assert; int 256; ==`, ep,
						"low Asset lookup 1")
				} else {
					testApp(t, `int 0; int 1; asset_holding_get AssetBalance; assert; int 256; ==`, ep)
				}

				// but now if that resolution led to a number below 255, boom
				tx.ForeignAssets = []basics.AssetIndex{256, 255}
				testApp(t, `int 1; asset_params_get AssetName; assert; byte "thirty"; ==`, ep,
					"low Asset lookup 255")
				if ep.Proto.LogicSigVersion < directRefEnabledVersion {
					// in v3, the asset argument is always treated as an ID, so this is asset 1
					testApp(t, `int 0; int 1; asset_holding_get AssetBalance; assert; int 30; ==`, ep,
						"low Asset lookup 1")
				} else {
					testApp(t, `int 0; int 1; asset_holding_get AssetBalance; assert; int 30; ==`, ep,
						"low Asset lookup 255")
				}

				tx.ForeignAssets = []basics.AssetIndex{1, 256}
				if ep.Proto.LogicSigVersion < directRefEnabledVersion {
					// in v3, the asset argument is always a slot, so this is asset 256
					testApp(t, `int 1; asset_params_get AssetName; assert; byte "thirty"; ==`, ep)
				} else {
					// Since 1 IS available, 1 means the assetid=1, not the 1th slot
					testApp(t, `int 1; asset_params_get AssetName; assert; byte "one"; ==`, ep,
						"low Asset lookup 1")
				}
				// pre v4 and the availability rule come to the same conclusion: treat the 1 as an ID
				testApp(t, `int 0; int 1; asset_holding_get AssetBalance; assert; int 1; ==`, ep,
					"low Asset lookup 1")
			})
		})
	}
}

// TestAppDisambiguation ensures we have a consistent interpretation of low
// numbers when used as an argument to app_(global,local)_get. A low number is
// an app ID if that app ID is available, or a slot number in
// txn.ForeignApplications if not.
func TestAppDisambiguation(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	// Make sure we don't treat slot indexes as app IDs when
	// ep.UnnamedResources is true.
	for _, unnamedResources := range []bool{false, true} {
		unnamedResources := unnamedResources
		t.Run(fmt.Sprintf("unnamedResources=%v", unnamedResources), func(t *testing.T) {
			t.Parallel()
			// It would be nice to start at 2, when apps were added, but `assert` is
			// very convenient for testing, and nothing important changed from 2 to
			// 3. (But directRefEnabledVersion=4, so that change is a big deal.)
			testLogicRange(t, 3, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
				if unnamedResources {
					ep.UnnamedResources = &mockUnnamedResourcePolicy{allowEverything: true}
				}
				// make apps with identifiable properties, so we can tell what we get
				makeIdentifiableApp := func(appID uint64) {
					ledger.NewApp(tx.Sender, basics.AppIndex(appID), basics.AppParams{
						GlobalState: map[string]basics.TealValue{"a": {
							Type: basics.TealUintType,
							Uint: appID,
						}},
						ExtraProgramPages: uint32(appID),
					})
					ledger.NewLocals(tx.Sender, appID)
					ledger.NewLocal(tx.Sender, appID, "x", basics.TealValue{Type: basics.TealUintType, Uint: appID * 10})
				}
				makeIdentifiableApp(1)
				makeIdentifiableApp(20)
				makeIdentifiableApp(256)

				tx.ForeignApps = []basics.AppIndex{20, 256}
				// Since 1 is not available, 1 must mean the first app slot = 20 (recall, 0 mean "this app")
				if ep.Proto.LogicSigVersion >= 5 { // to get AppExtraProgramPages
					testApp(t, `int 1; app_params_get AppExtraProgramPages; assert; int 20; ==`, ep)
				}
				testApp(t, `int 1; byte "a"; app_global_get_ex; assert; int 20; ==`, ep)
				if ep.Proto.LogicSigVersion < directRefEnabledVersion {
					// in v3, the app argument is always treated as an ID.
					testApp(t, `int 0; int 1; byte "x"; app_local_get_ex; assert; int 10; ==`, ep)
				} else {
					testApp(t, `int 0; int 1; byte "x"; app_local_get_ex; assert; int 200; ==`, ep)
				}

				// Make 1 available, so now 1 means the appid=1, not the 1th slot
				tx.ForeignApps = []basics.AppIndex{1, 256}
				if ep.Proto.LogicSigVersion >= 5 { // to get AppExtraProgramPages
					testApp(t, `int 1; app_params_get AppExtraProgramPages; assert; int 1; ==`, ep)
				}
				testApp(t, `int 1; byte "a"; app_global_get_ex; assert; int 1; ==`, ep)
				testApp(t, `int 0; int 1; byte "x"; app_local_get_ex; assert; int 10; ==`, ep)

				// same tests, but as of AppForbidLowResources, using 1 is forbidden
				ep.Proto.AppForbidLowResources = true

				// repeat the first tests, they are using 20 and 256 directly, which are too low
				tx.ForeignApps = []basics.AppIndex{20, 256}
				if ep.Proto.LogicSigVersion >= 5 { // to get AppExtraProgramPages
					testApp(t, `int 1; app_params_get AppExtraProgramPages; assert; int 20; ==`, ep,
						"low App lookup 20")
					testApp(t, `int 2; app_params_get AppExtraProgramPages; assert; int 256; ==`, ep)
				}
				testApp(t, `int 1; byte "a"; app_global_get_ex; assert; int 20; ==`, ep,
					"low App lookup 20")
				testApp(t, `int 2; byte "a"; app_global_get_ex; assert; int 256; ==`, ep)
				if ep.Proto.LogicSigVersion < directRefEnabledVersion {
					// in v3, the app argument is always treated as an ID.
					testApp(t, `int 0; int 1; byte "x"; app_local_get_ex; assert; int 200; ==`, ep,
						"low App lookup 1")
					testApp(t, `int 0; int 2; byte "x"; app_local_get_ex; assert; int 2560; ==`, ep,
						"low App lookup 2")
				} else {
					testApp(t, `int 0; int 1; byte "x"; app_local_get_ex; assert; int 200; ==`, ep,
						"low App lookup 20")
					testApp(t, `int 0; int 2; byte "x"; app_local_get_ex; assert; int 2560; ==`, ep)
				}

				// repeat the second tests, which are using 1, which is too low
				tx.ForeignApps = []basics.AppIndex{1, 256}
				if ep.Proto.LogicSigVersion >= 5 { // to get AppExtraProgramPages
					testApp(t, `int 1; app_params_get AppExtraProgramPages; assert; int 1; ==`, ep,
						"low App lookup 1")
				}
				testApp(t, `int 1; byte "a"; app_global_get_ex; assert; int 1; ==`, ep,
					"low App lookup 1")
				testApp(t, `int 0; int 1; byte "x"; app_local_get_ex; assert; int 10; ==`, ep,
					"low App lookup 1")
			})
		})
	}
}

func TestAppParams(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	// start at 5 for app_params_get
	testLogicRange(t, 5, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
		ledger.NewAccount(tx.Sender, 1)
		ledger.NewApp(tx.Sender, 100, basics.AppParams{})

		/* app id is in ForeignApps, but does not exist */
		source := "int 56; app_params_get AppExtraProgramPages; int 0; ==; assert; int 0; =="
		testApp(t, source, ep)
		/* app id is in ForeignApps, but has zero ExtraProgramPages */
		source = "int 100; app_params_get AppExtraProgramPages; int 1; ==; assert; int 0; =="
		testApp(t, source, ep)
	})
}

func TestAcctParams(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	// start at 6 for acct_params_get
	testLogicRange(t, 6, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
		test := func(source string) {
			t.Helper()
			testApp(t, source, ep)
		}

		test("txn Sender; acct_params_get AcctBalance; !; assert; int 0; ==")
		test("txn Sender; acct_params_get AcctMinBalance; !; assert; int 1001; ==")

		ledger.NewAccount(tx.Sender, 42)

		test("txn Sender; acct_params_get AcctBalance; assert; int 42; ==")
		test("txn Sender; acct_params_get AcctMinBalance; assert; int 1001; ==")
		test("txn Sender; acct_params_get AcctAuthAddr; assert; global ZeroAddress; ==")

		if ep.Proto.LogicSigVersion < 8 {
			return // the rest uses fields that came at 8
		}
		// No apps or schema at first, then 1 created and the global schema noted
		test("txn Sender; acct_params_get AcctTotalAppsCreated; assert; !")
		test("txn Sender; acct_params_get AcctTotalNumUint; assert; !")
		test("txn Sender; acct_params_get AcctTotalNumByteSlice; assert; !")
		test("txn Sender; acct_params_get AcctTotalExtraAppPages; assert; !")
		ledger.NewApp(tx.Sender, 2000, basics.AppParams{
			StateSchemas: basics.StateSchemas{
				LocalStateSchema: basics.StateSchema{
					NumUint:      6,
					NumByteSlice: 7,
				},
				GlobalStateSchema: basics.StateSchema{
					NumUint:      8,
					NumByteSlice: 9,
				},
			},
			ExtraProgramPages: 2,
		})
		test("txn Sender; acct_params_get AcctTotalAppsCreated; assert; int 1; ==")
		test("txn Sender; acct_params_get AcctTotalNumUint; assert; int 8; ==")
		test("txn Sender; acct_params_get AcctTotalNumByteSlice; assert; int 9; ==")
		test("txn Sender; acct_params_get AcctTotalExtraAppPages; assert; int 2; ==")

		// Not opted in at first, then opted into 1, schema added
		test("txn Sender; acct_params_get AcctTotalAppsOptedIn; assert; !")
		ledger.NewLocals(tx.Sender, 2000)
		test("txn Sender; acct_params_get AcctTotalAppsOptedIn; assert; int 1; ==")
		test("txn Sender; acct_params_get AcctTotalNumUint; assert; int 8; int 6; +; ==")
		test("txn Sender; acct_params_get AcctTotalNumByteSlice; assert; int 9; int 7; +; ==")

		// No ASAs at first, then 1 created AND in total
		test("txn Sender; acct_params_get AcctTotalAssetsCreated; assert; !")
		test("txn Sender; acct_params_get AcctTotalAssets; assert; !")
		ledger.NewAsset(tx.Sender, 3000, basics.AssetParams{})
		test("txn Sender; acct_params_get AcctTotalAssetsCreated; assert; int 1; ==")
		test("txn Sender; acct_params_get AcctTotalAssets; assert; int 1; ==")
	})
}

// TestGlobalNonDelete ensures that a deletion is not inserted in the delta if the global didn't exist
func TestGlobalNonDelete(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	testLogicRange(t, 2, 0, func(t *testing.T, ep *EvalParams, txn *transactions.Transaction, ledger *Ledger) {
		source := `byte "none"; app_global_del; int 1`
		ledger.NewApp(txn.Sender, 888, makeApp(0, 0, 1, 0))
		delta, _ := testApp(t, source, ep)
		require.Empty(t, delta.GlobalDelta)
		require.Empty(t, delta.LocalDeltas)
	})
}

// TestLocalNonDelete ensures that a deletion is not inserted in the delta if the local didn't exist
func TestLocalNonDelete(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	testLogicRange(t, 2, 0, func(t *testing.T, ep *EvalParams, txn *transactions.Transaction, ledger *Ledger) {
		source := `int 0; byte "none"; app_local_del; int 1`
		ledger.NewAccount(txn.Sender, 100000)
		ledger.NewApp(txn.Sender, 888, makeApp(0, 0, 1, 0))
		ledger.NewLocals(txn.Sender, 888)
		delta, _ := testApp(t, source, ep)
		require.Empty(t, delta.GlobalDelta)
		require.Empty(t, delta.LocalDeltas)
	})
}

func TestAppLocalReadWriteDeleteErrors(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	sourceRead := `intcblock 0 100 0x77 1
bytecblock "ALGO" "ALGOA"
txn Sender
intc_1                    // 100, app id
bytec_0                   // key "ALGO"
app_local_get_ex
!
bnz error
intc_2                    // 0x77
==
txn Sender
intc_1                    // 100
bytec_1                   // ALGOA
app_local_get_ex
!
bnz error
intc_3                    // 1
==
&&
bnz ok
error:
err
ok:
intc_3                    // 1
`
	sourceWrite := `intcblock 0 100 1
bytecblock "ALGO"
txn Sender
bytec_0                    // key "ALGO"
intc_1                     // 100
app_local_put
intc_2                     // 1
`
	sourceDelete := `intcblock 0 100
bytecblock "ALGO"
txn Sender
bytec_0                      // key "ALGO"
app_local_del
intc_1
`
	tests := map[string]string{
		"read":   sourceRead,
		"write":  sourceWrite,
		"delete": sourceDelete,
	}
	for name, source := range tests {
		name, source := name, source
		t.Run(fmt.Sprintf("test=%s", name), func(t *testing.T) {
			t.Parallel()

			ops := testProg(t, source, AssemblerMaxVersion)

			var txn transactions.SignedTxn
			txn.Txn.Type = protocol.ApplicationCallTx
			txn.Txn.ApplicationID = 100
			ep := defaultAppParams(txn)
			err := CheckContract(ops.Program, ep)
			require.NoError(t, err)

			ledger := NewLedger(
				map[basics.Address]uint64{
					txn.Txn.Sender: 1,
				},
			)
			ep.Ledger = ledger
			ep.SigLedger = ledger

			_, err = EvalApp(ops.Program, 0, 100, ep)
			require.Error(t, err)
			require.Contains(t, err.Error(), "is not opted into")

			ledger.NewApp(txn.Txn.Sender, 100, basics.AppParams{})
			ledger.NewLocals(txn.Txn.Sender, 100)

			if name == "read" {
				_, err = EvalApp(ops.Program, 0, 100, ep)
				require.Error(t, err)
				require.Contains(t, err.Error(), "err opcode") // no such key
			}

			ledger.NewLocal(txn.Txn.Sender, 100, "ALGO", basics.TealValue{Type: basics.TealUintType, Uint: 0x77})
			ledger.NewLocal(txn.Txn.Sender, 100, "ALGOA", basics.TealValue{Type: basics.TealUintType, Uint: 1})

			ledger.Reset()
			pass, err := EvalApp(ops.Program, 0, 100, ep)
			require.NoError(t, err)
			require.True(t, pass)
			delta := ep.TxnGroup[0].EvalDelta
			require.Empty(t, delta.GlobalDelta)
			expLocal := 1
			if name == "read" {
				expLocal = 0
			}
			require.Len(t, delta.LocalDeltas, expLocal)
		})
	}
}

func TestAppLocalStateReadWrite(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	testLogicRange(t, 2, 0, func(t *testing.T, ep *EvalParams, txn *transactions.Transaction, ledger *Ledger) {

		txn.ApplicationID = 100
		ledger.NewAccount(txn.Sender, 1)
		ledger.NewApp(txn.Sender, 100, basics.AppParams{})
		ledger.NewLocals(txn.Sender, 100)

		// write int and bytes values
		source := `txn Sender
byte "ALGO"      // key
int 0x77             // value
app_local_put
txn Sender
byte "ALGOA"    // key
byte "ALGO"      // value
app_local_put
txn Sender
int 100              // app id
byte "ALGOA"    // key
app_local_get_ex
bnz exist
err
exist:
byte "ALGO"
==
txn Sender
int 100              // app id
byte "ALGO"      // key
app_local_get_ex
bnz exist2
err
exist2:
int 0x77
==
&&
`
		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
		}
		delta, _ := testApp(t, source, ep)
		require.Empty(t, delta.GlobalDelta)
		require.Len(t, delta.LocalDeltas, 1)

		require.Len(t, delta.LocalDeltas[0], 2)
		vd := delta.LocalDeltas[0]["ALGO"]
		require.Equal(t, basics.SetUintAction, vd.Action)
		require.Equal(t, uint64(0x77), vd.Uint)

		vd = delta.LocalDeltas[0]["ALGOA"]
		require.Equal(t, basics.SetBytesAction, vd.Action)
		require.Equal(t, "ALGO", vd.Bytes)

		// write same value without writing, expect no local delta
		source = `txn Sender
byte "ALGO"       // key
int 0x77              // value
app_local_put
txn Sender
int 100               // app id
byte "ALGO"       // key
app_local_get_ex
bnz exist
err
exist:
int 0x77
==
`
		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
		}
		ledger.Reset()
		ledger.NoLocal(txn.Sender, 100, "ALGOA")
		ledger.NoLocal(txn.Sender, 100, "ALGO")

		algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
		ledger.NewLocal(txn.Sender, 100, "ALGO", algoValue)

		delta, _ = testApp(t, source, ep)
		require.Empty(t, delta.GlobalDelta)
		require.Empty(t, delta.LocalDeltas)

		// write same value after reading, expect no local delta
		source = `txn Sender
int 100              // app id
byte "ALGO"      // key
app_local_get_ex
bnz exist
err
exist:
txn Sender
byte "ALGO"      // key
int 0x77             // value
app_local_put
txn Sender
int 100              // app id
byte "ALGO"      // key
app_local_get_ex
bnz exist2
err
exist2:
==
`
		ledger.Reset()
		ledger.NewLocal(txn.Sender, 100, "ALGO", algoValue)
		ledger.NoLocal(txn.Sender, 100, "ALGOA")

		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
		}
		delta, _ = testApp(t, source, ep)
		require.Empty(t, delta.GlobalDelta)
		require.Empty(t, delta.LocalDeltas)

		// write a value and expect local delta change
		source = `txn Sender
byte "ALGOA"    // key
int 0x78        // value
app_local_put
int 1
`
		ledger.Reset()
		ledger.NewLocal(txn.Sender, 100, "ALGO", algoValue)
		ledger.NoLocal(txn.Sender, 100, "ALGOA")

		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
		}
		delta, _ = testApp(t, source, ep)
		require.Empty(t, delta.GlobalDelta)
		require.Len(t, delta.LocalDeltas, 1)
		require.Len(t, delta.LocalDeltas[0], 1)
		vd = delta.LocalDeltas[0]["ALGOA"]
		require.Equal(t, basics.SetUintAction, vd.Action)
		require.Equal(t, uint64(0x78), vd.Uint)

		// write a value to existing key and expect delta change and reading the new value
		source = `txn Sender
byte "ALGO"          // key
int 0x78             // value
app_local_put
txn Sender
int 100              // app id
byte "ALGO"          // key
app_local_get_ex
bnz exist
err
exist:
int 0x78
==
`
		ledger.Reset()
		ledger.NewLocal(txn.Sender, 100, "ALGO", algoValue)
		ledger.NoLocal(txn.Sender, 100, "ALGOA")

		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
		}
		delta, _ = testApp(t, source, ep)
		require.Empty(t, delta.GlobalDelta)
		require.Len(t, delta.LocalDeltas, 1)
		require.Len(t, delta.LocalDeltas[0], 1)
		vd = delta.LocalDeltas[0]["ALGO"]
		require.Equal(t, basics.SetUintAction, vd.Action)
		require.Equal(t, uint64(0x78), vd.Uint)

		// write a value after read and expect delta change
		source = `txn Sender
int 100              // app id
byte "ALGO"          // key
app_local_get_ex
bnz exist
err
exist:
txn Sender
byte "ALGO"          // key
int 0x78             // value
app_local_put
`
		ledger.Reset()
		ledger.NewLocal(txn.Sender, 100, "ALGO", algoValue)
		ledger.NoLocal(txn.Sender, 100, "ALGOA")

		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
		}
		delta, _ = testApp(t, source, ep)
		require.Empty(t, delta.GlobalDelta)
		require.Len(t, delta.LocalDeltas, 1)
		require.Len(t, delta.LocalDeltas[0], 1)
		vd = delta.LocalDeltas[0]["ALGO"]
		require.Equal(t, basics.SetUintAction, vd.Action)
		require.Equal(t, uint64(0x78), vd.Uint)

		// write a few values and expect delta change only for unique changed
		source = `txn Sender
byte "ALGO"          // key
int 0x77             // value
app_local_put
txn Sender
byte "ALGO"          // key
int 0x78             // value
app_local_put
txn Sender
byte "ALGOA"           // key
int 0x78             // value
app_local_put
txn Accounts 1
byte "ALGO"          // key
int 0x79             // value
app_local_put
int 1
`
		ledger.Reset()
		ledger.NewLocal(txn.Sender, 100, "ALGO", algoValue)
		ledger.NoLocal(txn.Sender, 100, "ALGOA")

		ledger.NewAccount(txn.Receiver, 500)
		ledger.NewLocals(txn.Receiver, 100)

		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
			source = strings.ReplaceAll(source, "txn Accounts 1", "int 1")
		}
		delta, _ = testApp(t, source, ep)
		require.Empty(t, delta.GlobalDelta)
		require.Len(t, delta.LocalDeltas, 2)
		require.Len(t, delta.LocalDeltas[0], 2)
		require.Len(t, delta.LocalDeltas[1], 1)
		vd = delta.LocalDeltas[0]["ALGO"]
		require.Equal(t, basics.SetUintAction, vd.Action)
		require.Equal(t, uint64(0x78), vd.Uint)

		vd = delta.LocalDeltas[0]["ALGOA"]
		require.Equal(t, basics.SetUintAction, vd.Action)
		require.Equal(t, uint64(0x78), vd.Uint)

		vd = delta.LocalDeltas[1]["ALGO"]
		require.Equal(t, basics.SetUintAction, vd.Action)
		require.Equal(t, uint64(0x79), vd.Uint)
	})
}

func TestAppLocalGlobalErrorCases(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	testLogicRange(t, 2, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
		ledger.NewApp(tx.Sender, 888, basics.AppParams{})

		g, l := "app_global_put;", "app_local_put;"
		sender := "txn Sender;"
		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			sender = "int 0;"
		}
		testApp(t, notrack(fmt.Sprintf(`byte "%v"; int 1;`+g+`int 1`, strings.Repeat("v", ep.Proto.MaxAppKeyLen+1))), ep, "key too long")

		testApp(t, fmt.Sprintf(`byte "%v"; int 1;`+g+`int 1`, strings.Repeat("v", ep.Proto.MaxAppKeyLen)), ep)

		ledger.NewLocals(tx.Sender, 888)
		testApp(t, notrack(fmt.Sprintf(sender+`byte "%v"; int 1;`+l+`int 1`, strings.Repeat("v", ep.Proto.MaxAppKeyLen+1))), ep, "key too long")

		testApp(t, fmt.Sprintf(sender+`byte "%v"; int 1;`+l+`int 1`, strings.Repeat("v", ep.Proto.MaxAppKeyLen)), ep)

		testApp(t, fmt.Sprintf(`byte "foo"; byte "%v";`+g+`int 1`, strings.Repeat("v", ep.Proto.MaxAppBytesValueLen+1)), ep, "value too long for key")

		testApp(t, fmt.Sprintf(`byte "foo"; byte "%v";`+g+`int 1`, strings.Repeat("v", ep.Proto.MaxAppBytesValueLen)), ep)

		testApp(t, fmt.Sprintf(sender+`byte "foo"; byte "%v";`+l+`int 1`, strings.Repeat("v", ep.Proto.MaxAppBytesValueLen+1)), ep, "value too long for key")

		testApp(t, fmt.Sprintf(sender+`byte "foo"; byte "%v";`+l+`int 1`, strings.Repeat("v", ep.Proto.MaxAppBytesValueLen)), ep)

		ep.Proto.MaxAppSumKeyValueLens = 2 // Override to generate error.
		testApp(t, `byte "foo"; byte "foo";`+g+`int 1`, ep, "key/value total too long for key")

		testApp(t, sender+`byte "foo"; byte "foo";`+l+`int 1`, ep, "key/value total too long for key")
	})
}

func TestAppGlobalReadWriteDeleteErrors(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	testLogicRange(t, 2, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
		v := ep.Proto.LogicSigVersion

		sourceRead := `int 0
byte "ALGO"  // key
app_global_get_ex
bnz ok
err
ok:
int 0x77
==
`
		tests := map[string]string{
			"read":   sourceRead,
			"reads":  `byte "ALGO"; app_global_get; int 0x77; ==`,
			"write":  `byte "ALGO"; int 100; app_global_put; int 1`,
			"delete": `byte "ALGO"; app_global_del; int 1`,
		}
		tx.ApplicationID = 100
		ledger.NewApp(tx.Sender, 100, makeApp(0, 0, 1, 0))
		for name, source := range tests {
			ops := testProg(t, source, v)

			// a special test for read
			if name == "read" {
				testAppBytes(t, ops.Program, ep, "err opcode") // no such key
			}
			ledger.NewGlobal(100, "ALGO", basics.TealValue{Type: basics.TealUintType, Uint: 0x77})

			ledger.Reset()

			delta, _ := testAppBytes(t, ops.Program, ep)
			require.Empty(t, delta.LocalDeltas)
		}
	})
}

func TestAppGlobalReadWrite(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	for _, bySlot := range []bool{true, false} {
		testLogicRange(t, 2, 0, func(t *testing.T, ep *EvalParams, txn *transactions.Transaction, ledger *Ledger) {

			// check writing ints and bytes
			source := `byte "ALGO"  // key
int 0x77						// value
app_global_put
byte "ALGOA"  // key "ALGOA"
byte "ALGO"    // value
app_global_put
// check simple
byte "ALGOA"  // key "ALGOA"
app_global_get
byte "ALGO"
==
// check generic with alias
int 0 // current app id alias
byte "ALGOA"  // key "ALGOA"
app_global_get_ex
bnz ok
err
ok:
byte "ALGO"
==
&&
// check generic with exact app id
THISAPP
byte "ALGOA"  // key "ALGOA"
app_global_get_ex
bnz ok1
err
ok1:
byte "ALGO"
==
&&
// check simple
byte "ALGO"
app_global_get
int 0x77
==
&&
// check generic with alias
int 0 // ForeignApps index - current app
byte "ALGO"
app_global_get_ex
bnz ok2
err
ok2:
int 0x77
==
&&
// check generic with exact app id
THISAPP
byte "ALGO"
app_global_get_ex
bnz ok3
err
ok3:
int 0x77
==
&&
`

			txn.Type = protocol.ApplicationCallTx
			txn.ApplicationID = 100
			txn.ForeignApps = []basics.AppIndex{txn.ApplicationID}
			ledger.NewAccount(txn.Sender, 1)
			ledger.NewApp(txn.Sender, 100, basics.AppParams{})

			if bySlot {
				// 100 is in the ForeignApps array, name it by slot
				source = strings.ReplaceAll(source, "THISAPP", "int 1")
			} else {
				// use the actual app number
				if ep.Proto.LogicSigVersion < directRefEnabledVersion {
					return
				}
				source = strings.ReplaceAll(source, "THISAPP", "int 100")
			}
			delta, _ := testApp(t, source, ep)

			require.Len(t, delta.GlobalDelta, 2)
			require.Empty(t, delta.LocalDeltas)

			vd := delta.GlobalDelta["ALGO"]
			require.Equal(t, basics.SetUintAction, vd.Action)
			require.Equal(t, uint64(0x77), vd.Uint)

			vd = delta.GlobalDelta["ALGOA"]
			require.Equal(t, basics.SetBytesAction, vd.Action)
			require.Equal(t, "ALGO", vd.Bytes)

			// write existing value before read
			source = `byte "ALGO"  // key
int 0x77						// value
app_global_put
byte "ALGO"
app_global_get
int 0x77
==
`
			ledger.Reset()
			ledger.NoGlobal(100, "ALGOA")
			ledger.NoGlobal(100, "ALGO")

			algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
			ledger.NewGlobal(100, "ALGO", algoValue)

			delta, _ = testApp(t, source, ep)
			require.Empty(t, delta.GlobalDelta)
			require.Empty(t, delta.LocalDeltas)

			// write existing value after read
			source = `int 0
byte "ALGO"
app_global_get_ex
bnz ok
err
ok:
pop
byte "ALGO"
int 0x77
app_global_put
byte "ALGO"
app_global_get
int 0x77
==
`
			ledger.Reset()
			ledger.NoGlobal(100, "ALGOA")
			ledger.NewGlobal(100, "ALGO", algoValue)

			delta, _ = testApp(t, source, ep)
			require.Empty(t, delta.GlobalDelta)
			require.Empty(t, delta.LocalDeltas)

			// write new values after and before read
			source = `int 0
byte "ALGO"
app_global_get_ex
bnz ok
err
ok:
pop
byte "ALGO"
int 0x78
app_global_put
int 0
byte "ALGO"
app_global_get_ex
bnz ok2
err
ok2:
int 0x78
==
byte "ALGOA"
byte "ALGO"
app_global_put
int 0
byte "ALGOA"
app_global_get_ex
bnz ok3
err
ok3:
byte "ALGO"
==
&&
`
			ledger.Reset()
			ledger.NoGlobal(100, "ALGOA")
			ledger.NewGlobal(100, "ALGO", algoValue)

			delta, _ = testApp(t, source, ep)

			require.Len(t, delta.GlobalDelta, 2)
			require.Empty(t, delta.LocalDeltas)

			vd = delta.GlobalDelta["ALGO"]
			require.Equal(t, basics.SetUintAction, vd.Action)
			require.Equal(t, uint64(0x78), vd.Uint)

			vd = delta.GlobalDelta["ALGOA"]
			require.Equal(t, basics.SetBytesAction, vd.Action)
			require.Equal(t, "ALGO", vd.Bytes)
		})
	}
}

func TestAppGlobalReadOtherApp(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()
	// app_global_get_ex starts in v2
	for _, bySlot := range []bool{true, false} {
		testLogicRange(t, 2, 0, func(t *testing.T, ep *EvalParams, txn *transactions.Transaction, ledger *Ledger) {
			source := `
OTHERAPP
byte "mykey1"
app_global_get_ex
bz ok1
err
ok1:
pop
OTHERAPP
byte "mykey"
app_global_get_ex
bnz ok2
err
ok2:
byte "myval"
==
`

			if bySlot {
				source = strings.ReplaceAll(source, "OTHERAPP", "int 2")
			} else {
				// use the actual app number if allowed
				if ep.Proto.LogicSigVersion < directRefEnabledVersion {
					return
				}
				source = strings.ReplaceAll(source, "OTHERAPP", "int 101")
			}

			txn.ApplicationID = 100
			txn.ForeignApps = []basics.AppIndex{txn.ApplicationID, 101}
			ledger.NewAccount(txn.Sender, 1)
			ledger.NewApp(txn.Sender, 100, basics.AppParams{})

			delta, _ := testApp(t, source, ep, "no app 101")
			require.Empty(t, delta.GlobalDelta)
			require.Empty(t, delta.LocalDeltas)

			ledger.NewApp(txn.Receiver, 101, basics.AppParams{})
			ledger.NewApp(txn.Receiver, 100, basics.AppParams{}) // this keeps current app id = 100
			algoValue := basics.TealValue{Type: basics.TealBytesType, Bytes: "myval"}
			ledger.NewGlobal(101, "mykey", algoValue)

			delta, _ = testApp(t, source, ep)
			require.Empty(t, delta.GlobalDelta)
			require.Empty(t, delta.LocalDeltas)
		})
	}
}

func TestBlankKey(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()
	source := `
byte ""
app_global_get
int 0
==
assert

byte ""
int 7
app_global_put

byte ""
app_global_get
int 7
==
`
	// v3 gives "assert"
	testLogicRange(t, 3, 0, func(t *testing.T, ep *EvalParams, txn *transactions.Transaction, ledger *Ledger) {
		txn.ApplicationID = 100
		ledger.NewAccount(txn.Sender, 1)
		ledger.NewApp(txn.Sender, 100, basics.AppParams{})

		delta, _ := testApp(t, source, ep)
		require.Empty(t, delta.LocalDeltas)
	})
}

func TestAppGlobalDelete(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	for _, bySlot := range []bool{true, false} {
		testLogicRange(t, 2, 0, func(t *testing.T, ep *EvalParams, txn *transactions.Transaction, ledger *Ledger) {
			// check write/delete/read
			source := `byte "ALGO"
int 0x77						// value
app_global_put
byte "ALGOA"
byte "ALGO"
app_global_put
byte "ALGO"
app_global_del
byte "ALGOA"
app_global_del
int 0
byte "ALGO"
app_global_get_ex
bnz error
int 0
byte "ALGOA"
app_global_get_ex
bnz error
==
bnz ok
error:
err
ok:
int 1
`

			ledger.NewAccount(txn.Sender, 1)
			txn.ApplicationID = 100
			ledger.NewApp(txn.Sender, 100, basics.AppParams{})

			delta, _ := testApp(t, source, ep)
			require.Len(t, delta.GlobalDelta, 2)
			require.Empty(t, delta.LocalDeltas)

			ledger.Reset()
			ledger.NoGlobal(100, "ALGOA")
			ledger.NoGlobal(100, "ALGO")

			algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
			ledger.NewGlobal(100, "ALGO", algoValue)

			// check delete existing
			source = `byte "ALGO"
app_global_del
THISAPP
byte "ALGO"
app_global_get_ex
==  // two zeros
`

			if bySlot {
				// 100 is in the ForeignApps array, name it by slot
				source = strings.ReplaceAll(source, "THISAPP", "int 1")
			} else {
				// use the actual app number if allowed
				if ep.Proto.LogicSigVersion < directRefEnabledVersion {
					return
				}
				source = strings.ReplaceAll(source, "THISAPP", "int 100")
			}
			txn.ForeignApps = []basics.AppIndex{txn.ApplicationID}
			delta, _ = testApp(t, source, ep)
			require.Len(t, delta.GlobalDelta, 1)
			vd := delta.GlobalDelta["ALGO"]
			require.Equal(t, basics.DeleteAction, vd.Action)
			require.Equal(t, uint64(0), vd.Uint)
			require.Equal(t, "", vd.Bytes)
			require.Equal(t, 0, len(delta.LocalDeltas))

			ledger.Reset()
			ledger.NoGlobal(100, "ALGOA")
			ledger.NoGlobal(100, "ALGO")

			ledger.NewGlobal(100, "ALGO", algoValue)

			// check delete and write non-existing
			source = `byte "ALGOA"
app_global_del
int 0
byte "ALGOA"
app_global_get_ex
==  // two zeros
byte "ALGOA"
int 0x78
app_global_put
`
			delta, _ = testApp(t, source, ep)
			require.Len(t, delta.GlobalDelta, 1)
			vd = delta.GlobalDelta["ALGOA"]
			require.Equal(t, basics.SetUintAction, vd.Action)
			require.Equal(t, uint64(0x78), vd.Uint)
			require.Equal(t, "", vd.Bytes)
			require.Empty(t, delta.LocalDeltas)

			ledger.Reset()
			ledger.NoGlobal(100, "ALGOA")
			ledger.NoGlobal(100, "ALGO")

			ledger.NewGlobal(100, "ALGO", algoValue)

			// check delete and write existing
			source = `byte "ALGO"
app_global_del
byte "ALGO"
int 0x78
app_global_put
int 1
`
			delta, _ = testApp(t, source, ep)
			require.Len(t, delta.GlobalDelta, 1)
			vd = delta.GlobalDelta["ALGO"]
			require.Equal(t, basics.SetUintAction, vd.Action)
			require.Empty(t, delta.LocalDeltas)

			ledger.Reset()
			ledger.Reset()
			ledger.NoGlobal(100, "ALGOA")
			ledger.NoGlobal(100, "ALGO")

			ledger.NewGlobal(100, "ALGO", algoValue)

			// check delete,write,delete existing
			source = `byte "ALGO"
app_global_del
byte "ALGO"
int 0x78
app_global_put
byte "ALGO"
app_global_del
int 1
`
			delta, _ = testApp(t, source, ep)
			require.Len(t, delta.GlobalDelta, 1)
			vd = delta.GlobalDelta["ALGO"]
			require.Equal(t, basics.DeleteAction, vd.Action)
			require.Empty(t, delta.LocalDeltas)

			ledger.Reset()
			ledger.Reset()
			ledger.NoGlobal(100, "ALGOA")
			ledger.NoGlobal(100, "ALGO")

			ledger.NewGlobal(100, "ALGO", algoValue)

			// check delete, write, delete non-existing
			source = `byte "ALGOA"   // key "ALGOA"
app_global_del
byte "ALGOA"
int 0x78
app_global_put
byte "ALGOA"
app_global_del
int 1
`
			delta, _ = testApp(t, source, ep)
			require.Len(t, delta.GlobalDelta, 1)
			require.Len(t, delta.LocalDeltas, 0)
		})
	}
}

func TestAppLocalDelete(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	testLogicRange(t, 2, 0, func(t *testing.T, ep *EvalParams, txn *transactions.Transaction, ledger *Ledger) {
		// check write/delete/read
		source := `int 0 // sender
byte "ALGO"
int 0x77              // value
app_local_put
int 1 // other
byte "ALGOA"     // key "ALGOA"
byte "ALGO"
app_local_put
int 0 // sender
byte "ALGO"
app_local_del
int 1 // other
byte "ALGOA"
app_local_del
int 0 // sender
int 0 // app
byte "ALGO"
app_local_get_ex
bnz error
int 1 // other
int 100
byte "ALGOA"
app_local_get_ex
bnz error
==
bnz ok
error:
err
ok:
int 1
`
		txn.ApplicationID = 100
		ledger.NewAccount(txn.Sender, 1)
		ledger.NewApp(txn.Sender, 100, basics.AppParams{})
		ledger.NewLocals(txn.Sender, 100)
		ledger.NewAccount(txn.Receiver, 1)
		ledger.NewLocals(txn.Receiver, 100)

		ep.Trace = &strings.Builder{}

		delta, _ := testApp(t, source, ep)
		require.Equal(t, 0, len(delta.GlobalDelta))
		require.Equal(t, 2, len(delta.LocalDeltas))
		ledger.Reset()

		if ep.Proto.LogicSigVersion >= directRefEnabledVersion {
			// test that app_local_put and _app_local_del can use byte addresses
			withBytes := strings.ReplaceAll(source, "int 0 // sender", "txn Sender")
			withBytes = strings.ReplaceAll(withBytes, "int 1 // other", "txn Accounts 1")
			delta, _ := testApp(t, withBytes, ep)
			// But won't even compile in old teal
			testProg(t, withBytes, directRefEnabledVersion-1,
				exp(4, "app_local_put arg 0 wanted..."), exp(11, "app_local_del arg 0 wanted..."))
			require.Equal(t, 0, len(delta.GlobalDelta))
			require.Equal(t, 2, len(delta.LocalDeltas))
			ledger.Reset()
		}

		ledger.NoLocal(txn.Sender, 100, "ALGOA")
		ledger.NoLocal(txn.Sender, 100, "ALGO")
		ledger.NoLocal(txn.Receiver, 100, "ALGOA")
		ledger.NoLocal(txn.Receiver, 100, "ALGO")

		algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
		ledger.NewLocal(txn.Sender, 100, "ALGO", algoValue)

		// check delete existing
		source = `txn Sender
byte "ALGO"
app_local_del
txn Sender
int 100
byte "ALGO"
app_local_get_ex
==  // two zeros
`

		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
		}
		delta, _ = testApp(t, source, ep)
		require.Equal(t, 0, len(delta.GlobalDelta))
		require.Equal(t, 1, len(delta.LocalDeltas))
		vd := delta.LocalDeltas[0]["ALGO"]
		require.Equal(t, basics.DeleteAction, vd.Action)
		require.Equal(t, uint64(0), vd.Uint)
		require.Equal(t, "", vd.Bytes)

		ledger.Reset()
		ledger.NoLocal(txn.Sender, 100, "ALGOA")
		ledger.NoLocal(txn.Sender, 100, "ALGO")

		ledger.NewLocal(txn.Sender, 100, "ALGO", algoValue)

		// check delete and write non-existing
		source = `txn Sender
byte "ALGOA"
app_local_del
txn Sender
int 0
byte "ALGOA"
app_local_get_ex
==  // two zeros
txn Sender
byte "ALGOA"
int 0x78
app_local_put
`
		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
		}
		delta, _ = testApp(t, source, ep)
		require.Equal(t, 0, len(delta.GlobalDelta))
		require.Equal(t, 1, len(delta.LocalDeltas))
		vd = delta.LocalDeltas[0]["ALGOA"]
		require.Equal(t, basics.SetUintAction, vd.Action)
		require.Equal(t, uint64(0x78), vd.Uint)
		require.Equal(t, "", vd.Bytes)

		ledger.Reset()
		ledger.NoLocal(txn.Sender, 100, "ALGOA")
		ledger.NoLocal(txn.Sender, 100, "ALGO")

		ledger.NewLocal(txn.Sender, 100, "ALGO", algoValue)

		// check delete and write existing
		source = `txn Sender
byte "ALGO"
app_local_del
txn Sender
byte "ALGO"
int 0x78
app_local_put
int 1
`
		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
		}
		delta, _ = testApp(t, source, ep)
		require.Equal(t, 0, len(delta.GlobalDelta))
		require.Equal(t, 1, len(delta.LocalDeltas))
		vd = delta.LocalDeltas[0]["ALGO"]
		require.Equal(t, basics.SetUintAction, vd.Action)
		require.Equal(t, uint64(0x78), vd.Uint)
		require.Equal(t, "", vd.Bytes)

		ledger.Reset()
		ledger.NoLocal(txn.Sender, 100, "ALGOA")
		ledger.NoLocal(txn.Sender, 100, "ALGO")

		ledger.NewLocal(txn.Sender, 100, "ALGO", algoValue)

		// check delete,write,delete existing
		source = `txn Sender
byte "ALGO"
app_local_del
txn Sender
byte "ALGO"
int 0x78
app_local_put
txn Sender
byte "ALGO"
app_local_del
int 1
`
		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
		}
		delta, _ = testApp(t, source, ep)
		require.Equal(t, 0, len(delta.GlobalDelta))
		require.Equal(t, 1, len(delta.LocalDeltas))
		vd = delta.LocalDeltas[0]["ALGO"]
		require.Equal(t, basics.DeleteAction, vd.Action)
		require.Equal(t, uint64(0), vd.Uint)
		require.Equal(t, "", vd.Bytes)

		ledger.Reset()
		ledger.NoLocal(txn.Sender, 100, "ALGOA")
		ledger.NoLocal(txn.Sender, 100, "ALGO")

		ledger.NewLocal(txn.Sender, 100, "ALGO", algoValue)

		// check delete, write, delete non-existing
		source = `txn Sender
byte "ALGOA"
app_local_del
txn Sender
byte "ALGOA"
int 0x78
app_local_put
txn Sender
byte "ALGOA"
app_local_del
int 1
`
		if ep.Proto.LogicSigVersion < directRefEnabledVersion {
			source = strings.ReplaceAll(source, "txn Sender", "int 0")
		}
		delta, _ = testApp(t, source, ep)
		require.Equal(t, 0, len(delta.GlobalDelta))
		require.Equal(t, 1, len(delta.LocalDeltas))
		require.Equal(t, 1, len(delta.LocalDeltas[0]))
	})
}

type unnamedResourcePolicyEvent struct {
	eventType string
	args      []interface{}
}

func availableAccountEvent(addr basics.Address) unnamedResourcePolicyEvent {
	return unnamedResourcePolicyEvent{
		eventType: "AvailableAccount",
		args:      []interface{}{addr},
	}
}

func availableAssetEvent(aid basics.AssetIndex) unnamedResourcePolicyEvent {
	return unnamedResourcePolicyEvent{
		eventType: "AvailableAsset",
		args:      []interface{}{aid},
	}
}

func availableAppEvent(aid basics.AppIndex) unnamedResourcePolicyEvent {
	return unnamedResourcePolicyEvent{
		eventType: "AvailableApp",
		args:      []interface{}{aid},
	}
}

func allowsHoldingEvent(addr basics.Address, aid basics.AssetIndex) unnamedResourcePolicyEvent {
	return unnamedResourcePolicyEvent{
		eventType: "AllowsHolding",
		args:      []interface{}{addr, aid},
	}
}

func allowsLocalEvent(addr basics.Address, aid basics.AppIndex) unnamedResourcePolicyEvent {
	return unnamedResourcePolicyEvent{
		eventType: "AllowsLocal",
		args:      []interface{}{addr, aid},
	}
}

func availableBoxEvent(app basics.AppIndex, name string, operation BoxOperation, createSize uint64) unnamedResourcePolicyEvent {
	return unnamedResourcePolicyEvent{
		eventType: "AvailableBox",
		args:      []interface{}{app, name, operation, createSize},
	}
}

type mockUnnamedResourcePolicy struct {
	allowEverything bool
	events          []unnamedResourcePolicyEvent
}

func (p *mockUnnamedResourcePolicy) String() string {
	if p == nil {
		return "no policy"
	}
	return fmt.Sprintf("allowEverything=%t", p.allowEverything)
}

func (p *mockUnnamedResourcePolicy) AvailableAccount(addr basics.Address) bool {
	p.events = append(p.events, availableAccountEvent(addr))
	return p.allowEverything
}

func (p *mockUnnamedResourcePolicy) AvailableAsset(aid basics.AssetIndex) bool {
	p.events = append(p.events, availableAssetEvent(aid))
	return p.allowEverything
}

func (p *mockUnnamedResourcePolicy) AvailableApp(aid basics.AppIndex) bool {
	p.events = append(p.events, availableAppEvent(aid))
	return p.allowEverything
}

func (p *mockUnnamedResourcePolicy) AllowsHolding(addr basics.Address, aid basics.AssetIndex) bool {
	p.events = append(p.events, allowsHoldingEvent(addr, aid))
	return p.allowEverything
}

func (p *mockUnnamedResourcePolicy) AllowsLocal(addr basics.Address, aid basics.AppIndex) bool {
	p.events = append(p.events, allowsLocalEvent(addr, aid))
	return p.allowEverything
}

func (p *mockUnnamedResourcePolicy) AvailableBox(app basics.AppIndex, name string, operation BoxOperation, createSize uint64) bool {
	p.events = append(p.events, availableBoxEvent(app, name, operation, createSize))
	return p.allowEverything
}

func TestUnnamedResourceAccess(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	testcases := []struct {
		policy                 *mockUnnamedResourcePolicy
		allowsUnnamedResources bool
	}{
		{nil, false},
		{&mockUnnamedResourcePolicy{allowEverything: false}, false},
		{&mockUnnamedResourcePolicy{allowEverything: true}, true},
	}

	for _, tc := range testcases {
		tc := tc
		t.Run(tc.policy.String(), func(t *testing.T) {
			t.Parallel()
			// start at 4 for directRefEnabledVersion
			testLogicRange(t, 4, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
				tx.Accounts = nil
				tx.ForeignApps = nil
				tx.ForeignAssets = nil
				tx.Boxes = []transactions.BoxRef{{}} // provide write budget, but not access

				if tc.policy != nil {
					tc.policy.events = nil
					ep.UnnamedResources = tc.policy
				}

				var otherAccount basics.Address
				crypto.RandBytes(otherAccount[:])

				ledger.NewAccount(otherAccount, 1)
				ledger.NewApp(tx.Sender, 500, basics.AppParams{})
				ledger.NewGlobal(500, "global key", basics.TealValue{
					Type:  basics.TealBytesType,
					Bytes: "global value",
				})

				ledger.NewLocals(otherAccount, 500)
				ledger.NewLocal(otherAccount, 500, "local key", basics.TealValue{
					Type:  basics.TealBytesType,
					Bytes: "local value",
				})

				ledger.NewAsset(tx.Sender, 501, basics.AssetParams{Total: 501})
				ledger.NewHolding(otherAccount, 501, 2, false)

				ledger.NewApp(tx.Sender, tx.ApplicationID, basics.AppParams{})
				err := ledger.NewBox(tx.ApplicationID, "box key", []byte("box value"), tx.ApplicationID.Address())
				require.NoError(t, err)

				// Unaccessible account
				source := fmt.Sprintf("addr %s; balance; int 1; ==", otherAccount)
				if tc.allowsUnnamedResources {
					testApp(t, source, ep)
					if tc.policy != nil {
						expectedEvents := []unnamedResourcePolicyEvent{availableAccountEvent(otherAccount)}
						assert.Equal(t, expectedEvents, tc.policy.events)
						tc.policy.events = nil
					}
				} else {
					testApp(t, source, ep, fmt.Sprintf("invalid Account reference %s", otherAccount))
				}

				// Unaccessible app
				source = `int 500; byte "global key"; app_global_get_ex; assert; byte "global value"; ==`
				if tc.allowsUnnamedResources {
					testApp(t, source, ep)
					if tc.policy != nil {
						expectedEvents := []unnamedResourcePolicyEvent{availableAppEvent(500)}
						assert.Equal(t, expectedEvents, tc.policy.events)
						tc.policy.events = nil
					}
				} else {
					testApp(t, source, ep, "unavailable App 500")
				}
				if ep.Proto.LogicSigVersion >= 5 {
					// app_params_get introduced
					source = "int 500; app_params_get AppCreator; assert; txn Sender; =="
					if tc.allowsUnnamedResources {
						testApp(t, source, ep)
						if tc.policy != nil {
							expectedEvents := []unnamedResourcePolicyEvent{availableAppEvent(500)}
							assert.Equal(t, expectedEvents, tc.policy.events)
							tc.policy.events = nil
						}
					} else {
						testApp(t, source, ep, "unavailable App 500")
					}
				}
				if ep.Proto.LogicSigVersion >= 6 {
					// inner app calls introduced
					source = "itxn_begin; int 500; itxn_field ApplicationID; int 1"
					if tc.allowsUnnamedResources {
						testApp(t, source, ep)
						if tc.policy != nil {
							expectedEvents := []unnamedResourcePolicyEvent{availableAppEvent(500)}
							assert.Equal(t, expectedEvents, tc.policy.events)
							tc.policy.events = nil
						}
					} else {
						testApp(t, source, ep, "unavailable App 500")
					}
				}

				// Unaccessible app local
				source = fmt.Sprintf(`addr %s; int 500; byte "local key"; app_local_get_ex; assert; byte "local value"; ==`, otherAccount)
				if tc.allowsUnnamedResources {
					testApp(t, source, ep)
					if tc.policy != nil {
						var expectedEvents []unnamedResourcePolicyEvent
						if ep.Proto.LogicSigVersion < 9 {
							// before resource sharing
							expectedEvents = []unnamedResourcePolicyEvent{
								availableAccountEvent(otherAccount),
								availableAppEvent(500),
							}
						} else {
							// after resource sharing
							expectedEvents = []unnamedResourcePolicyEvent{
								availableAppEvent(500),
								availableAppEvent(500),
								availableAccountEvent(otherAccount),
								allowsLocalEvent(otherAccount, 500),
							}
							// The duplicate app events above are actually expected. This is because
							// EvalContext.localsReference calls resolveApp, then allowsLocals,
							// which calls resolveApp again.
						}
						assert.Equal(t, expectedEvents, tc.policy.events)
						tc.policy.events = nil
					}
				} else {
					problem := "unavailable Account %s"
					if ep.Proto.LogicSigVersion < 9 {
						// Message is difference before sharedResourcesVersion
						problem = "invalid Account reference %s"
					}
					testApp(t, source, ep, fmt.Sprintf(problem, otherAccount))
				}

				// Unaccessible asset
				source = "int 501; asset_params_get AssetTotal; assert; int 501; =="
				if tc.allowsUnnamedResources {
					testApp(t, source, ep)
					if tc.policy != nil {
						expectedEvents := []unnamedResourcePolicyEvent{availableAssetEvent(501)}
						assert.Equal(t, expectedEvents, tc.policy.events)
						tc.policy.events = nil
					}
				} else {
					testApp(t, source, ep, "unavailable Asset 501")
				}
				if ep.Proto.LogicSigVersion >= 5 {
					// inner calls introduced
					source = "itxn_begin; int 501; itxn_field XferAsset; int 1"
					if tc.allowsUnnamedResources {
						testApp(t, source, ep)
						if tc.policy != nil {
							expectedEvents := []unnamedResourcePolicyEvent{availableAssetEvent(501)}
							assert.Equal(t, expectedEvents, tc.policy.events)
							tc.policy.events = nil
						}
					} else {
						testApp(t, source, ep, "unavailable Asset 501")
					}
				}

				// Unaccessible asset holding
				source = fmt.Sprintf(`addr %s; int 501; asset_holding_get AssetBalance; assert; int 2; ==`, otherAccount)
				if tc.allowsUnnamedResources {
					testApp(t, source, ep)
					if tc.policy != nil {
						var expectedEvents []unnamedResourcePolicyEvent
						if ep.Proto.LogicSigVersion < 9 {
							// before resource sharing
							expectedEvents = []unnamedResourcePolicyEvent{
								availableAccountEvent(otherAccount),
								availableAssetEvent(501),
							}
						} else {
							// after resource sharing
							expectedEvents = []unnamedResourcePolicyEvent{
								availableAssetEvent(501),
								availableAccountEvent(otherAccount),
								availableAssetEvent(501),
								allowsHoldingEvent(otherAccount, 501),
							}
							// The duplicate asset events above are actually expected. This is
							// because EvalContext.holdingReference calls resolveAsset, then
							// allowsHolding, which calls resolveAsset again.
						}
						assert.Equal(t, expectedEvents, tc.policy.events)
						tc.policy.events = nil
					}
				} else {
					problem := "unavailable Account %s"
					if ep.Proto.LogicSigVersion < 9 {
						// Message is different before sharedResourcesVersion
						problem = "invalid Account reference %s"
					}
					testApp(t, source, ep, fmt.Sprintf(problem, otherAccount))
				}

				// Unaccessible box
				if ep.Proto.LogicSigVersion >= 8 {
					// Boxes introduced
					source = `byte "box key"; box_get; assert; byte "box value"; ==`
					if tc.allowsUnnamedResources {
						testApp(t, source, ep)
						if tc.policy != nil {
							expectedEvents := []unnamedResourcePolicyEvent{availableBoxEvent(tx.ApplicationID, "box key", BoxReadOperation, 0)}
							assert.Equal(t, expectedEvents, tc.policy.events)
							tc.policy.events = nil
						}
					} else {
						testApp(t, source, ep, fmt.Sprintf("invalid Box reference %#x", "box key"))
					}
					source = `byte "new box"; int 1; box_create`
					if tc.allowsUnnamedResources {
						testApp(t, source, ep)
						if tc.policy != nil {
							expectedEvents := []unnamedResourcePolicyEvent{availableBoxEvent(tx.ApplicationID, "new box", BoxCreateOperation, 1)}
							assert.Equal(t, expectedEvents, tc.policy.events)
							tc.policy.events = nil
						}
					} else {
						testApp(t, source, ep, fmt.Sprintf("invalid Box reference %#x", "new box"))
					}
				}
			})
		})
	}
}

func TestEnumFieldErrors(t *testing.T) { // nolint:paralleltest // manipulates txnFieldSpecs
	partitiontest.PartitionTest(t)

	source := `txn Amount`
	origSpec := txnFieldSpecs[Amount]
	changed := origSpec
	changed.ftype = StackBytes
	txnFieldSpecs[Amount] = changed
	defer func() {
		txnFieldSpecs[Amount] = origSpec
	}()

	testLogic(t, source, AssemblerMaxVersion, nil, "Amount expected field type is []byte but got uint64")
	testApp(t, source, nil, "Amount expected field type is []byte but got uint64")

	source = `global MinTxnFee`

	origMinTxnFs := globalFieldSpecs[MinTxnFee]
	badMinTxnFs := origMinTxnFs
	badMinTxnFs.ftype = StackBytes
	globalFieldSpecs[MinTxnFee] = badMinTxnFs
	defer func() {
		globalFieldSpecs[MinTxnFee] = origMinTxnFs
	}()

	testLogic(t, source, AssemblerMaxVersion, nil, "MinTxnFee expected field type is []byte but got uint64")
	testApp(t, source, nil, "MinTxnFee expected field type is []byte but got uint64")

	ep, tx, ledger := makeSampleEnv()
	ledger.NewAccount(tx.Sender, 1)
	params := basics.AssetParams{
		Total:         1000,
		Decimals:      2,
		DefaultFrozen: false,
		UnitName:      "ALGO",
		AssetName:     "",
		URL:           string(protocol.PaymentTx),
		Manager:       tx.Sender,
		Reserve:       tx.Receiver,
		Freeze:        tx.Receiver,
		Clawback:      tx.Receiver,
	}
	ledger.NewAsset(tx.Sender, 55, params)

	source = `txn Sender
int 55
asset_holding_get AssetBalance
assert
`
	origBalanceFs := assetHoldingFieldSpecs[AssetBalance]
	badBalanceFs := origBalanceFs
	badBalanceFs.ftype = StackBytes
	assetHoldingFieldSpecs[AssetBalance] = badBalanceFs
	defer func() {
		assetHoldingFieldSpecs[AssetBalance] = origBalanceFs
	}()

	testApp(t, source, ep, "AssetBalance expected field type is []byte but got uint64")

	source = `int 55
asset_params_get AssetTotal
assert
`
	origTotalFs := assetParamsFieldSpecs[AssetTotal]
	badTotalFs := origTotalFs
	badTotalFs.ftype = StackBytes
	assetParamsFieldSpecs[AssetTotal] = badTotalFs
	defer func() {
		assetParamsFieldSpecs[AssetTotal] = origTotalFs
	}()

	testApp(t, source, ep, "AssetTotal expected field type is []byte but got uint64")
}

func TestReturnTypes(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	// Generate a plausible (and consistent) value for a given StackType
	typeToArg := func(t StackType) string {
		switch t.AVMType {
		case avmUint64:
			if t.Bound[0] > 0 {
				return fmt.Sprintf("int %d\n", t.Bound[0])
			}
			return "int 1\n"
		case avmAny:
			return "int 1\n"
		case avmBytes:
			if t.Bound[0] > 0 {
				return fmt.Sprintf("byte 0x%s\n", strings.Repeat("33", int(t.Bound[0])))
			}
			return "byte 0x33343536\n" // Which is the string "3456"
		}
		panic(t)
	}

	// We try to form a snippet that will test every opcode, by sandwiching it
	// between arguments that correspond to the opcode's input types, and then
	// check to see if the proper output types end up on the stack.  But many
	// opcodes require more specific inputs than a constant string or the number
	// 1 for ints.  Defaults are also supplied for immediate arguments.  For
	// opcodes that need to set up their own stack inputs, a ": at the front of
	// the string means "start with an empty stack".
	specialCmd := map[string]string{
		"gaids":          ": int 0; gaids",
		"gloads":         ": int 0; gloads 0",       // Needs txn index = 0 to work
		"gloadss":        ": int 0; int 1; gloadss", // Needs txn index = 0 to work
		"intc":           "intcblock 0; intc 0",
		"intc_0":         "intcblock 0; intc_0",
		"intc_1":         "intcblock 0 0; intc_1",
		"intc_2":         "intcblock 0 0 0; intc_2",
		"intc_3":         "intcblock 0 0 0 0; intc_3",
		"bytec":          "bytecblock 0x32; bytec 0",
		"bytec_0":        "bytecblock 0x32; bytec_0",
		"bytec_1":        "bytecblock 0x32 0x33; bytec_1",
		"bytec_2":        "bytecblock 0x32 0x33 0x34; bytec_2",
		"bytec_3":        "bytecblock 0x32 0x33 0x34 0x35; bytec_3",
		"substring":      "substring 0 2",
		"extract_uint32": ": byte 0x0102030405; int 1; extract_uint32",
		"extract_uint64": ": byte 0x010203040506070809; int 1; extract_uint64",
		"replace2":       ": byte 0x0102030405; byte 0x0809; replace2 2",
		"replace3":       ": byte 0x0102030405; int 2; byte 0x0809; replace3",
		"gtxnsa":         ": int 0; gtxnsa ApplicationArgs 0",
		"extract":        "extract 0 2",
		"gtxnsas":        ": int 0; int 0; gtxnsas ApplicationArgs",
		"divw":           ": int 1; int 2; int 3; divw",

		// opcodes that require addresses, not just bytes
		"balance":         ": txn Sender; balance",
		"min_balance":     ": txn Sender; min_balance",
		"acct_params_get": ": txn Sender; acct_params_get AcctMinBalance",

		// Use "bury" here to take advantage of args pushed on stack by test
		"app_local_get":    "txn Accounts 1; bury 2; app_local_get",
		"app_local_get_ex": "txn Accounts 1; bury 3; app_local_get_ex",
		"app_local_del":    "txn Accounts 1; bury 2; app_local_del",
		"app_local_put":    "txn Accounts 1; bury 3; app_local_put",
		"app_opted_in":     "txn Sender; bury 2; app_opted_in",

		"asset_params_get":  ": int 400; asset_params_get AssetUnitName",
		"asset_holding_get": ": txn Sender; int 400; asset_holding_get AssetBalance",
		"app_params_get":    "app_params_get AppGlobalNumUint",

		"itxn_field":  "itxn_begin; itxn_field TypeEnum",
		"itxn_next":   "itxn_begin; int pay; itxn_field TypeEnum; itxn_next",
		"itxn_submit": "itxn_begin; int pay; itxn_field TypeEnum; itxn_submit",
		"itxn":        "itxn_begin; int pay; itxn_field TypeEnum; itxn_submit; itxn CreatedAssetID",
		"itxna":       "itxn_begin; int pay; itxn_field TypeEnum; itxn_submit; itxna Accounts 0",
		"itxnas":      ": itxn_begin; int pay; itxn_field TypeEnum; itxn_submit; int 0; itxnas Accounts",
		"gitxn":       "itxn_begin; int pay; itxn_field TypeEnum; itxn_submit; gitxn 0 Sender",
		"gitxna":      "itxn_begin; int pay; itxn_field TypeEnum; itxn_submit; gitxna 0 Accounts 0",
		"gitxnas":     ": itxn_begin; int pay; itxn_field TypeEnum; itxn_submit; int 0; gitxnas 0 Accounts",

		"json_ref": `: byte "{\"k\": 7}"; byte "k"; json_ref JSONUint64`,

		"proto": "callsub p; p: proto 0 3",
		"bury":  ": int 1; int 2; int 3; bury 2; pop; pop;",

		"box_create": "int 9; +; box_create",                 // make the size match the 10 in CreateBox
		"box_put":    "byte 0x010203040506; concat; box_put", // make the 4 byte arg into a 10
	}

	/* Make sure the specialCmd tests the opcode in question */
	for opcode, cmd := range specialCmd {
		assert.Contains(t, cmd, opcode)
	}

	// these have strange stack semantics or require special input data /
	// context, so they must be tested separately
	skipCmd := map[string]bool{
		"retsub": true,
		"err":    true,
		"return": true,

		// panics unless the pk is proper
		"ecdsa_pk_decompress": true,

		"frame_dig":  true, // would need a "proto" subroutine
		"frame_bury": true, // would need a "proto" subroutine

		// These should not remain here, we should be able to construct example
		"ec_add":              true,
		"ec_scalar_mul":       true,
		"ec_pairing_check":    true,
		"ec_multi_scalar_mul": true,
		"ec_subgroup_check":   true,
		"ec_map_to":           true,
	}

	byName := OpsByName[LogicVersion]
	for _, m := range []RunMode{ModeSig, ModeApp} {
		for name, spec := range byName {
			// Only try an opcode in its modes
			if (m & spec.Modes) == 0 {
				continue
			}
			if skipCmd[name] || spec.trusted {
				continue
			}
			m, name, spec := m, name, spec
			t.Run(fmt.Sprintf("mode=%s,opcode=%s", m, name), func(t *testing.T) {
				t.Parallel()

				provideStackInput := true
				cmd := name
				if special, ok := specialCmd[name]; ok {
					if strings.HasPrefix(special, ":") {
						cmd = special[1:]
						provideStackInput = false
					} else {
						cmd = special
					}
				} else {
					for _, imm := range spec.OpDetails.Immediates {
						if imm.Group != nil {
							for _, name := range imm.Group.Names {
								// missing names exist because of array vs normal opcodes
								if name != "" {
									cmd += " " + name
									break
								}
							}
						} else {
							switch imm.kind {
							case immByte:
								cmd += " 0"
							case immInt8:
								cmd += " -2"
							case immInt:
								cmd += " 10"
							case immInts:
								cmd += " 11 12 13"
							case immBytes:
								cmd += " 0x123456"
							case immBytess:
								cmd += " 0x12 0x34 0x56"
							case immLabel:
								cmd += " done; done: ;"
							case immLabels:
								cmd += " done1 done2; done1: ; done2: ;"
							default:
								require.Fail(t, "bad immediate", "%s", imm)
							}
						}
					}
				}
				var sb strings.Builder
				if provideStackInput {
					for _, t := range spec.Arg.Types {
						sb.WriteString(typeToArg(t))
					}
				}
				sb.WriteString(cmd + "\n")
				ops := testProg(t, sb.String(), AssemblerMaxVersion)

				tx0 := makeSampleTxn()
				tx0.Txn.Type = protocol.ApplicationCallTx
				tx0.Txn.ApplicationID = 300
				tx0.Txn.ForeignApps = []basics.AppIndex{300}
				tx0.Txn.ForeignAssets = []basics.AssetIndex{400}
				tx0.Txn.Boxes = []transactions.BoxRef{{Name: []byte("3")}} // The arg given for boxName type
				tx0.Lsig.Args = [][]byte{
					[]byte("aoeu"),
					[]byte("aoeu"),
					[]byte("aoeu2"),
					[]byte("aoeu3"),
				}
				tx0.Lsig.Logic = ops.Program
				// We are going to run with GroupIndex=1, so make tx1 interesting too (so
				// `txn` opcode can look at things)
				tx1 := tx0

				sep, aep := defaultEvalParams(tx0, tx1)
				ledger := aep.Ledger.(*Ledger)

				tx := tx0.Txn
				ledger.NewAccount(tx.Sender, 1)
				params := basics.AssetParams{
					Total:         1000,
					Decimals:      2,
					DefaultFrozen: false,
					UnitName:      "ALGO",
					AssetName:     "",
					URL:           string(protocol.PaymentTx),
					Manager:       tx.Sender,
					Reserve:       tx.Receiver,
					Freeze:        tx.Receiver,
					Clawback:      tx.Receiver,
				}
				ledger.NewAsset(tx.Sender, 400, params)
				ledger.NewApp(tx.Sender, 300, basics.AppParams{})
				ledger.NewAccount(tx.Receiver, 1000000)
				ledger.NewLocals(tx.Receiver, 300)
				key, err := hex.DecodeString("33343536")
				require.NoError(t, err)
				algoValue := basics.TealValue{Type: basics.TealUintType, Uint: 0x77}
				ledger.NewLocal(tx.Receiver, 300, string(key), algoValue)
				ledger.NewAccount(appAddr(300), 1000000)

				// these allows the box_* opcodes that to work
				ledger.CreateBox(300, "3", 10)

				// We are running gi=1, but we never ran gi=0.  Set things up as
				// if we did, so they can be accessed with gtxn, gload, gaid
				aep.pastScratch[0] = &scratchSpace{}
				aep.TxnGroup[0].ConfigAsset = 100
				*aep.PooledApplicationBudget = 10_000 // so we can run verifies

				var cx *EvalContext
				if m == ModeApp {
					_, cx, err = EvalContract(ops.Program, 1, 300, aep)
				} else {
					_, cx, err = EvalSignatureFull(1, sep)
				}
				// These little programs need not pass. We are just trying to
				// examine cx.Stack for proper types/size after executing the
				// opcode. But if it fails for any *other* reason, we're not
				// doing a good test.
				if err != nil {
					// Allow the kinds of errors we expect, but fail for stuff
					// that indicates the opcode itself failed.
					reason := err.Error()
					if !strings.Contains(reason, "stack finished with bytes not int") &&
						!strings.Contains(reason, "stack len is") {
						require.NoError(t, err, "%s: %s\n%s", name, err, cx.Trace)
					}
				}
				require.Len(t, cx.Stack, len(spec.Return.Types), "%s", cx.Trace)
				for i := 0; i < len(spec.Return.Types); i++ {
					stackType := cx.Stack[i].stackType()
					retType := spec.Return.Types[i]
					require.True(
						t, stackType.overlaps(retType),
						"%s expected to return %s but actual is %s", spec.Name, retType, stackType,
					)
				}
			})
		}
	}
}

func TestTxnEffects(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	ep, _, _ := makeSampleEnv()
	// We don't allow the effects fields to see the current or future transactions
	testApp(t, "byte 0x32; log; txn NumLogs; int 1; ==", ep, "txn effects can only be read from past txns")
	testApp(t, "byte 0x32; log; txn Logs 0; byte 0x32; ==", ep, "txn effects can only be read from past txns")
	testApp(t, "byte 0x32; log; txn LastLog; byte 0x32; ==", ep, "txn effects can only be read from past txns")
	testApp(t, "byte 0x32; log; gtxn 0 NumLogs; int 1; ==", ep, "txn effects can only be read from past txns")
	testApp(t, "byte 0x32; log; gtxn 0 Logs 0; byte 0x32; ==", ep, "txn effects can only be read from past txns")
	testApp(t, "byte 0x32; log; gtxn 0 LastLog; byte 0x32; ==", ep, "txn effects can only be read from past txns")

	// Look at the logs of tx 0
	testApps(t, []string{"", "byte 0x32; log; gtxn 0 LastLog; byte 0x; =="}, nil, nil, nil)
	testApps(t, []string{"byte 0x33; log; int 1", "gtxn 0 LastLog; byte 0x33; =="}, nil, nil, nil)
	testApps(t, []string{"byte 0x33; dup; log; log; int 1", "gtxn 0 NumLogs; int 2; =="}, nil, nil, nil)
	testApps(t, []string{"byte 0x37; log; int 1", "gtxn 0 Logs 0; byte 0x37; =="}, nil, nil, nil)
	testApps(t, []string{"byte 0x37; log; int 1", "int 0; gtxnas 0 Logs; byte 0x37; =="}, nil, nil, nil)

	// Look past the logs of tx 0
	testApps(t, []string{"byte 0x37; log; int 1", "gtxna 0 Logs 1; byte 0x37; =="}, nil, nil, nil,
		exp(1, "invalid Logs index 1"))
	testApps(t, []string{"byte 0x37; log; int 1", "int 6; gtxnas 0 Logs; byte 0x37; =="}, nil, nil, nil,
		exp(1, "invalid Logs index 6"))
}
func TestLog(t *testing.T) {
	partitiontest.PartitionTest(t)

	t.Parallel()
	var txn transactions.SignedTxn
	txn.Txn.Type = protocol.ApplicationCallTx
	ledger := NewLedger(nil)
	ledger.NewApp(txn.Txn.Receiver, 0, basics.AppParams{})
	ep := defaultAppParams(txn)
	testCases := []struct {
		source string
		loglen int
	}{
		{
			source: `byte  "a logging message"; log; int 1`,
			loglen: 1,
		},
		{
			source: `byte  "a logging message"; log; byte  "a logging message"; log; int 1`,
			loglen: 2,
		},
		{
			source: fmt.Sprintf(`%s int 1`, strings.Repeat(`byte "a logging message"; log; `, maxLogCalls)),
			loglen: maxLogCalls,
		},
		{
			source: `int 1; loop: byte "a logging message"; log; int 1; +; dup; int 30; <=; bnz loop;`,
			loglen: 30,
		},
		{
			source: fmt.Sprintf(`byte "%s"; log; int 1`, strings.Repeat("a", maxLogSize)),
			loglen: 1,
		},
	}

	//track expected number of logs in cx.EvalDelta.Logs
	for i, s := range testCases {
		delta, _ := testApp(t, s.source, ep)
		require.Len(t, delta.Logs, s.loglen)
		if i == len(testCases)-1 {
			require.Equal(t, strings.Repeat("a", maxLogSize), delta.Logs[0])
		} else {
			for _, l := range delta.Logs {
				require.Equal(t, "a logging message", l)
			}
		}
	}

	msg := strings.Repeat("a", 400)
	failCases := []struct {
		source      string
		errContains string
		// For cases where assembly errors, we manually put in the bytes
		assembledBytes []byte
	}{
		{
			source:      fmt.Sprintf(`byte  "%s"; log; int 1`, strings.Repeat("a", maxLogSize+1)),
			errContains: fmt.Sprintf(">  %d bytes limit", maxLogSize),
		},
		{
			source:      fmt.Sprintf(`byte  "%s"; log; byte  "%s"; log; byte  "%s"; log; int 1`, msg, msg, msg),
			errContains: fmt.Sprintf(">  %d bytes limit", maxLogSize),
		},
		{
			source:      fmt.Sprintf(`%s; int 1`, strings.Repeat(`byte "a"; log; `, maxLogCalls+1)),
			errContains: "too many log calls",
		},
		{
			source:      `int 1; loop: byte "a"; log; int 1; +; dup; int 35; <; bnz loop;`,
			errContains: "too many log calls",
		},
		{
			source:      fmt.Sprintf(`int 1; loop: byte "%s"; log; int 1; +; dup; int 6; <; bnz loop;`, strings.Repeat(`a`, 400)),
			errContains: fmt.Sprintf(">  %d bytes limit", maxLogSize),
		},
		{
			source:         `load 0; log`,
			errContains:    "log arg 0 wanted []byte but got uint64",
			assembledBytes: []byte{byte(ep.Proto.LogicSigVersion), 0x34, 0x00, 0xb0},
		},
	}

	for _, c := range failCases {
		if c.assembledBytes == nil {
			testApp(t, c.source, ep, c.errContains)
		} else {
			testAppBytes(t, c.assembledBytes, ep, c.errContains)
		}
	}
}

func TestGaid(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	check0 := testProg(t, "gaid 0; int 100; ==", 4)
	appTxn := makeSampleTxn()
	appTxn.Txn.Type = protocol.ApplicationCallTx
	targetTxn := makeSampleTxn()
	targetTxn.Txn.Type = protocol.AssetConfigTx
	ep := defaultAppParams(targetTxn, appTxn, makeSampleTxn())

	// should fail when no creatable was created
	_, err := EvalApp(check0.Program, 1, 888, ep)
	require.ErrorContains(t, err, "did not create anything")

	ep.TxnGroup[0].ApplyData.ConfigAsset = 100
	pass, err := EvalApp(check0.Program, 1, 888, ep)
	if !pass || err != nil {
		t.Log(ep.Trace.String())
	}
	require.NoError(t, err)
	require.True(t, pass)

	// should fail when accessing future transaction in group
	check2 := testProg(t, "gaid 2; int 0; >", 4)
	_, err = EvalApp(check2.Program, 1, 888, ep)
	require.ErrorContains(t, err, "gaid can't get creatable ID of txn ahead of the current one")

	// should fail when accessing self
	_, err = EvalApp(check0.Program, 0, 888, ep)
	require.ErrorContains(t, err, "gaid is only for accessing creatable IDs of previous txns")

	// should fail on non-creatable
	ep.TxnGroup[0].Txn.Type = protocol.PaymentTx
	_, err = EvalApp(check0.Program, 1, 888, ep)
	require.ErrorContains(t, err, "can't use gaid on txn that is not an app call nor an asset config txn")
	ep.TxnGroup[0].Txn.Type = protocol.AssetConfigTx
}

func TestRound(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	ep, _, _ := makeSampleEnv()
	source := "global Round; int 1; >="
	testApp(t, source, ep)
}

func TestLatestTimestamp(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	ep, _, _ := makeSampleEnv()
	source := "global LatestTimestamp; int 1; >="
	testApp(t, source, ep)
}

func TestGenHash(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	ep, _, _ := makeSampleEnv()
	source := fmt.Sprintf("global GenesisHash; byte 0x%s; ==", hex.EncodeToString(testGenHash[:]))
	testApp(t, source, ep)
}

func TestBlockSeed(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	ep, txn, l := makeSampleEnv()

	// makeSampleEnv creates txns with fv, lv that don't actually fit the round
	// in l.  Nothing in most tests cares. But the rule for `block` is related
	// to lv and fv, so we set the fv,lv more realistically.
	txn.FirstValid = l.Round() - 10
	txn.LastValid = l.Round() + 10

	// Keep in mind that proto.MaxTxnLife is 1500 in the test proto

	// l.round() is 0xffffffff+5 = 4294967300 in test ledger

	// These first two tests show that current-1 is not available now, though a
	// resonable extension is to allow such access for apps (not sigs).
	testApp(t, "int 4294967299; block BlkSeed; len; int 32; ==", ep,
		"not available") // current - 1
	testApp(t, "int 4294967300; block BlkSeed; len; int 32; ==", ep,
		"not available") // can't get current round's blockseed

	testApp(t, "int 4294967300; int 1500; -; block BlkSeed; len; int 32; ==", ep,
		"not available") // 1500 back from current is more than 1500 back from lv
	testApp(t, "int 4294967310; int 1500; -; block BlkSeed; len; int 32; ==", ep) // 1500 back from lv is legal
	testApp(t, "int 4294967310; int 1501; -; block BlkSeed; len; int 32; ==", ep) // 1501 back from lv is legal
	testApp(t, "int 4294967310; int 1502; -; block BlkSeed; len; int 32; ==", ep,
		"not available") // 1501 back from lv is not

	// A little silly, as it only tests the test ledger: ensure sameness and differentness
	testApp(t, "int 0xfffffff0; block BlkSeed; int 0xfffffff0; block BlkSeed; ==", ep)
	testApp(t, "int 0xfffffff0; block BlkSeed; int 0xfffffff1; block BlkSeed; !=", ep)

	// `block` should also work in LogicSigs, to drive home the point, blot out
	// the normal Ledger
	ep.runMode = ModeSig
	ep.Ledger = nil
	testLogic(t, "int 0xfffffff0; block BlkTimestamp", randomnessVersion, ep)
}

func TestCurrentApplicationID(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	ep, tx, _ := makeSampleEnv()
	tx.ApplicationID = 42
	source := "global CurrentApplicationID; int 42; =="
	testApp(t, source, ep)
}

func TestAppLoop(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	ep, _, _ := makeSampleEnv()

	stateful := "global CurrentApplicationID; pop;"

	// Double until > 10. Should be 16
	testApp(t, stateful+"int 1; loop: int 2; *; dup; int 10; <; bnz loop; int 16; ==", ep)

	// Infinite loop because multiply by one instead of two
	testApp(t, stateful+"int 1; loop:; int 1; *; dup; int 10; <; bnz loop; int 16; ==", ep, "dynamic cost")
}

func TestPooledAppCallsVerifyOp(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	source := `
	global CurrentApplicationID
	pop
	byte 0x01
	byte "ZC9KNzlnWTlKZ1pwSkNzQXVzYjNBcG1xTU9YbkRNWUtIQXNKYVk2RzRBdExPakQx"
	addr DROUIZXGT3WFJR3QYVZWTR5OJJXJCMOLS7G4FUGZDSJM5PNOVOREH6HIZE
	ed25519verify
	pop
	int 1`

	ledger := NewLedger(nil)
	call := transactions.SignedTxn{Txn: transactions.Transaction{Type: protocol.ApplicationCallTx}}
	// Simulate test with 2 grouped txn
	testApps(t, []string{source, ""}, []transactions.SignedTxn{call, call}, nil, ledger,
		exp(0, "pc=107 dynamic cost budget exceeded, executing ed25519verify: local program cost was 5"))

	// Simulate test with 3 grouped txn
	testApps(t, []string{source, "", ""}, []transactions.SignedTxn{call, call, call}, nil, ledger)
}

func appAddr(id int) basics.Address {
	return basics.AppIndex(id).Address()
}

func TestAppInfo(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	ep, tx, ledger := makeSampleEnv()
	require.Equal(t, 888, int(tx.ApplicationID))
	ledger.NewApp(tx.Receiver, 888, basics.AppParams{})
	testApp(t, "global CurrentApplicationID; int 888; ==;", ep)
	source := fmt.Sprintf("global CurrentApplicationAddress; addr %s; ==;", appAddr(888))
	testApp(t, source, ep)

	source = fmt.Sprintf("int 0; app_params_get AppAddress; assert; addr %s; ==;", appAddr(888))
	testApp(t, source, ep)

	// To document easy construction:
	// python -c 'import algosdk.encoding as e; print(e.encode_address(e.checksum(b"appID"+(888).to_bytes(8, "big"))))'
	a := "U7C5FUHZM5PL5EIS2KHHLL456GS66DZBEEKL2UBQLMKH2X5X5I643ZIM6U"
	source = fmt.Sprintf("int 0; app_params_get AppAddress; assert; addr %s; ==;", a)
	testApp(t, source, ep)
}

func TestAppBudget(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	source := func(budget int) string {
		return fmt.Sprintf(`
global OpcodeBudget
int %d
==
assert
global OpcodeBudget
int %d
==
`, budget-1, budget-5)
	}
	testApp(t, source(700), nil)

	// with pooling a two app call starts with 1400
	testApps(t, []string{source(1400), source(1393)}, nil, nil, nil)

	// without, they get base 700
	testApps(t, []string{source(700), source(700)}, nil,
		func(p *config.ConsensusParams) { p.EnableAppCostPooling = false }, nil)

}

func TestSelfMutateV8(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	ep, _, ledger := makeSampleEnvWithVersion(8)

	/* In order to test the added protection of mutableAccountReference, we're
	   going to set up a ledger in which an app account is opted into
	   itself. That was impossible before v6, and indeed we did not have the
	   extra mutable reference check then. */
	ledger.NewLocals(basics.AppIndex(888).Address(), 888)
	ledger.NewLocal(basics.AppIndex(888).Address(), 888, "hey",
		basics.TealValue{Type: basics.TealUintType, Uint: 77})

	source := `
global CurrentApplicationAddress
byte "hey"
int 42
app_local_put
`
	testApp(t, source, ep, "invalid Account reference for mutation")

	source = `
global CurrentApplicationAddress
byte "hey"
app_local_del
`
	testApp(t, source, ep, "invalid Account reference for mutation")

	/* But let's just check read access is working properly. */
	source = `
global CurrentApplicationAddress
byte "hey"
app_local_get
int 77
==
`
	testApp(t, source, ep)
}

// TestSelfMutateV9AndUp tests that apps can mutate their own app's local state
// starting with v9. Includes tests to the EvalDelta created.
func TestSelfMutateV9AndUp(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	// start at 9, when such mutation became legal
	testLogicRange(t, 9, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
		/* In order to test that apps can now mutate their own app's local state,
		   we're going to set up a ledger in which an app account is opted into
		   itself. */
		ledger.NewLocals(basics.AppIndex(888).Address(), 888)
		ledger.NewLocal(basics.AppIndex(888).Address(), 888, "hey",
			basics.TealValue{Type: basics.TealUintType, Uint: 77})

		// and we'll modify the passed account's locals, to better check the ED
		ledger.NewLocals(tx.Accounts[0], 888)

		source := `
global CurrentApplicationAddress
byte "hey"
int 42
app_local_put
txn Accounts 1
byte "acct"
int 43
app_local_put
int 1
`
		delta, _ := testApp(t, source, ep)
		require.Len(t, tx.Accounts, 1) // Sender + 1 tx.Accounts means LocalDelta index should be 2
		require.Equal(t, map[uint64]basics.StateDelta{
			1: {
				"acct": {
					Action: basics.SetUintAction,
					Uint:   43,
				},
			},
			2: {
				"hey": {
					Action: basics.SetUintAction,
					Uint:   42,
				},
			},
		}, delta.LocalDeltas)
		require.Equal(t, []basics.Address{tx.ApplicationID.Address()}, delta.SharedAccts)

		/* Confirm it worked. */
		source = `
global CurrentApplicationAddress
byte "hey"
app_local_get
int 42
==
`
		testApp(t, source, ep)

		source = `
global CurrentApplicationAddress
byte "hey"
int 10
app_local_put					// this will get wiped out by del
global CurrentApplicationAddress
byte "hey"
app_local_del
txn Accounts 1
byte "acct"
int 7
app_local_put
int 1
`
		delta, _ = testApp(t, source, ep)
		require.Len(t, tx.Accounts, 1) // Sender + 1 tx.Accounts means LocalDelta index should be 2
		require.Equal(t, map[uint64]basics.StateDelta{
			1: {
				"acct": {
					Action: basics.SetUintAction,
					Uint:   7,
				},
			},
			2: {
				"hey": {
					Action: basics.DeleteAction,
				},
			},
		}, delta.LocalDeltas)
		require.Equal(t, []basics.Address{tx.ApplicationID.Address()}, delta.SharedAccts)

		// Now, repeat the "put" test with multiple keys, to ensure only one
		// address is added to SharedAccts and we'll modify the Sender too, to
		// better check the ED
		ledger.NewLocals(tx.Sender, 888)

		source = `
txn Sender
byte "hey"
int 40
app_local_put

global CurrentApplicationAddress
byte "hey"
int 42
app_local_put

global CurrentApplicationAddress
byte "joe"
int 21
app_local_put
int 1
`
		delta, _ = testApp(t, source, ep)
		require.Len(t, tx.Accounts, 1) // Sender + 1 tx.Accounts means LocalDelta index should be 2
		require.Equal(t, map[uint64]basics.StateDelta{
			0: {
				"hey": {
					Action: basics.SetUintAction,
					Uint:   40,
				},
			},
			2: {
				"hey": {
					Action: basics.SetUintAction,
					Uint:   42,
				},
				"joe": {
					Action: basics.SetUintAction,
					Uint:   21,
				},
			},
		}, delta.LocalDeltas)

		require.Equal(t, []basics.Address{tx.ApplicationID.Address()}, delta.SharedAccts)
	})
}

func TestInfiniteRecursion(t *testing.T) { // nolint:paralleltest // manipulates maxAppCallDepth
	partitiontest.PartitionTest(t)

	// test needs AppApprovalProgram, available in 7
	TestLogicRange(t, 7, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
		v := ep.Proto.LogicSigVersion
		source := `
itxn_begin
int appl; itxn_field TypeEnum
int 0; app_params_get AppApprovalProgram
assert
itxn_field ApprovalProgram

int 0; app_params_get AppClearStateProgram
assert
itxn_field ClearStateProgram

itxn_submit
`
		// This app looks itself up in the ledger, so we need to put it in there.
		ledger.NewApp(tx.Sender, 888, basics.AppParams{
			ApprovalProgram:   testProg(t, source, v).Program,
			ClearStateProgram: testProg(t, "int 1", v).Program,
		})
		// We're testing if this can recur forever. It's hard to fund all these
		// apps, but we can put a huge credit in the ep.
		*ep.FeeCredit = 1_000_000_000

		testApp(t, source, ep, "appl depth (8) exceeded")

		was := maxAppCallDepth
		defer func() {
			maxAppCallDepth = was
		}()
		maxAppCallDepth = 10_000_000

		testApp(t, source, ep, "too many inner transactions 1 with 0 left")
	})
}

func TestTxnaLimits(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()
	// txna came in v2, but Apps and Assets in v3.
	TestLogicRange(t, 3, 0, func(t *testing.T, ep *EvalParams, tx *transactions.Transaction, ledger *Ledger) {
		testApp(t, "txna Accounts "+strconv.Itoa(len(tx.Accounts))+";len", ep)
		testApp(t, "txna Accounts "+strconv.Itoa(len(tx.Accounts)+1)+";len", ep, "invalid Accounts index")

		testApp(t, "txna Applications "+strconv.Itoa(len(tx.ForeignApps)), ep)
		testApp(t, "txna Applications "+strconv.Itoa(len(tx.ForeignApps)+1), ep, "invalid Applications index")

		// Assets and AppArgs have no implicit 0 index, so everything shifts
		testApp(t, "txna Assets "+strconv.Itoa(len(tx.ForeignAssets)-1), ep)
		testApp(t, "txna Assets "+strconv.Itoa(len(tx.ForeignAssets)), ep, "invalid Assets index")

		testApp(t, "txna ApplicationArgs "+strconv.Itoa(len(tx.ApplicationArgs)-1)+";len", ep)
		testApp(t, "txna ApplicationArgs "+strconv.Itoa(len(tx.ApplicationArgs))+";len", ep, "invalid ApplicationArgs index")
	})
}