summaryrefslogtreecommitdiff
path: root/ledger/apptxn_test.go
blob: 167d22f2dcc93185e12e98967f0501700750faf8 (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
// 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 ledger

import (
	"encoding/hex"
	"fmt"
	"strconv"
	"testing"

	"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/data/transactions/logic"
	"github.com/algorand/go-algorand/data/txntest"
	ledgertesting "github.com/algorand/go-algorand/ledger/testing"
	"github.com/algorand/go-algorand/protocol"
	"github.com/algorand/go-algorand/test/partitiontest"
)

// TestPayAction ensures a pay in teal affects balances
func TestPayAction(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// Inner txns start in v30
	ledgertesting.TestConsensusRange(t, 30, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		ai := dl.fundedApp(addrs[0], 200000, // account min balance, plus fees
			main(`
         itxn_begin
         int pay
         itxn_field TypeEnum
         int 5000
         itxn_field Amount
         txn Accounts 1
         itxn_field Receiver
         itxn_submit
        `))

		payout1 := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: ai,
			Accounts:      []basics.Address{addrs[1]}, // pay self
		}

		dl.fullBlock(&payout1)

		ad0 := micros(dl.t, dl.generator, addrs[0])
		ad1 := micros(dl.t, dl.generator, addrs[1])
		app := micros(dl.t, dl.generator, ai.Address())

		genAccounts := genBalances.Balances
		// create(1000) and fund(1000 + 200000)
		require.Equal(t, uint64(202000), genAccounts[addrs[0]].MicroAlgos.Raw-ad0)
		// paid 5000, but 1000 fee
		require.Equal(t, uint64(4000), ad1-genAccounts[addrs[1]].MicroAlgos.Raw)
		// app still has 194000 (paid out 5000, and paid fee to do it)
		require.Equal(t, uint64(194000), app)

		// Build up Residue in RewardsState so it's ready to pay
		for i := 1; i < 10; i++ {
			dl.fullBlock()
		}

		payout2 := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: ai,
			Accounts:      []basics.Address{addrs[2]}, // pay other
		}
		vb := dl.fullBlock(&payout2)
		// confirm that modifiedAccounts can see account in inner txn

		deltas := vb.Delta()
		require.Contains(t, deltas.Accts.ModifiedAccounts(), addrs[2])

		payInBlock := vb.Block().Payset[0]
		rewards := payInBlock.ApplyData.SenderRewards.Raw
		require.Greater(t, rewards, uint64(2000)) // some biggish number
		inners := payInBlock.ApplyData.EvalDelta.InnerTxns
		require.Len(t, inners, 1)

		// addr[2] is going to get the same rewards as addr[1], who
		// originally sent the top-level txn.  Both had their algo balance
		// touched and has very nearly the same balance.
		require.Equal(t, rewards, inners[0].ReceiverRewards.Raw)
		// app gets none, because it has less than 1A
		require.Equal(t, uint64(0), inners[0].SenderRewards.Raw)

		ad1 = micros(dl.t, dl.validator, addrs[1])
		ad2 := micros(dl.t, dl.validator, addrs[2])
		app = micros(dl.t, dl.validator, ai.Address())

		// paid 5000, in first payout (only), but paid 1000 fee in each payout txn
		require.Equal(t, rewards+3000, ad1-genAccounts[addrs[1]].MicroAlgos.Raw)
		// app still has 188000 (paid out 10000, and paid 2k fees to do it)
		// no rewards because owns less than an algo
		require.Equal(t, uint64(200000)-10000-2000, app)

		// paid 5000 by payout2, never paid any fees, got same rewards
		require.Equal(t, rewards+uint64(5000), ad2-genAccounts[addrs[2]].MicroAlgos.Raw)

		// Now fund the app account much more, so we can confirm it gets rewards.
		tenkalgos := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: ai.Address(),
			Amount:   10 * 1000 * 1000000, // account min balance, plus fees
		}
		dl.fullBlock(&tenkalgos)
		beforepay := micros(dl.t, dl.validator, ai.Address())

		// Build up Residue in RewardsState so it's ready to pay again
		for i := 1; i < 10; i++ {
			dl.fullBlock()
		}
		tib := dl.txn(payout2.Noted("2"))

		afterpay := micros(dl.t, dl.validator, ai.Address())

		inners = tib.ApplyData.EvalDelta.InnerTxns
		require.Len(t, inners, 1)

		appreward := inners[0].SenderRewards.Raw
		require.Greater(t, appreward, uint64(1000))

		require.Equal(t, beforepay+appreward-5000-1000, afterpay)
	})
}

// TestAxferAction ensures axfers in teal have the intended effects
func TestAxferAction(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// Inner txns start in v30
	ledgertesting.TestConsensusRange(t, 30, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		asa := txntest.Txn{
			Type:   "acfg",
			Sender: addrs[0],
			AssetParams: basics.AssetParams{
				Total:     1000000,
				Decimals:  3,
				UnitName:  "oz",
				AssetName: "Gold",
				URL:       "https://gold.rush/",
			},
		}

		source := main(`
         itxn_begin
         int axfer
         itxn_field TypeEnum
         txn Assets 0
         itxn_field XferAsset

         txn ApplicationArgs 0
         byte "optin"
         ==
         bz withdraw
         // let AssetAmount default to 0
         global CurrentApplicationAddress
         itxn_field AssetReceiver
         b submit
withdraw:
         txn ApplicationArgs 0
         byte "close"
         ==
         bz noclose
         txn Accounts 1
         itxn_field AssetCloseTo
         b skipamount
noclose: int 10000
         itxn_field AssetAmount
skipamount:
         txn Accounts 1
         itxn_field AssetReceiver
submit:  itxn_submit
`)

		asaID := dl.txn(&asa).ApplyData.ConfigAsset
		// account min balance, optin min balance, plus fees
		// stay under 1M, to avoid rewards complications
		appID := dl.fundedApp(addrs[0], 300_000, source)

		fundgold := txntest.Txn{
			Type:          "axfer",
			Sender:        addrs[0],
			XferAsset:     asaID,
			AssetReceiver: appID.Address(),
			AssetAmount:   20000,
		}

		// Fail, because app account is not opted in.
		dl.txn(&fundgold, fmt.Sprintf("asset %d missing", asaID))

		amount, in := holding(t, dl.generator, appID.Address(), asaID)
		require.False(t, in)
		require.Zero(t, amount)

		// Tell the app to opt itself in.
		optin := txntest.Txn{
			Type:            "appl",
			ApplicationID:   appID,
			Sender:          addrs[0],
			ApplicationArgs: [][]byte{[]byte("optin")},
			ForeignAssets:   []basics.AssetIndex{asaID},
		}
		dl.txn(&optin)

		amount, in = holding(t, dl.generator, appID.Address(), asaID)
		require.True(t, in)
		require.Zero(t, amount)

		// Now, succeed, because opted in.
		dl.txn(&fundgold)

		amount, in = holding(t, dl.generator, appID.Address(), asaID)
		require.True(t, in)
		require.Equal(t, uint64(20000), amount)

		withdraw := txntest.Txn{
			Type:            "appl",
			ApplicationID:   appID,
			Sender:          addrs[0],
			ApplicationArgs: [][]byte{[]byte("withdraw")},
			ForeignAssets:   []basics.AssetIndex{asaID},
			Accounts:        []basics.Address{addrs[0]},
		}
		dl.txn(&withdraw)

		amount, in = holding(t, dl.generator, appID.Address(), asaID)
		require.True(t, in)
		require.Equal(t, uint64(10000), amount)

		dl.txn(withdraw.Noted("2"))

		amount, in = holding(t, dl.generator, appID.Address(), asaID)
		require.True(t, in) // Zero left, but still opted in
		require.Zero(t, amount)

		dl.txn(withdraw.Noted("3"), "underflow on subtracting")

		amount, in = holding(t, dl.generator, appID.Address(), asaID)
		require.True(t, in) // Zero left, but still opted in
		require.Zero(t, amount)

		close := txntest.Txn{
			Type:            "appl",
			ApplicationID:   appID,
			Sender:          addrs[0],
			ApplicationArgs: [][]byte{[]byte("close")},
			ForeignAssets:   []basics.AssetIndex{asaID},
			Accounts:        []basics.Address{addrs[0]},
		}

		dl.txn(&close)

		amount, in = holding(t, dl.generator, appID.Address(), asaID)
		require.False(t, in) // Zero left, not opted in
		require.Zero(t, amount)

		// Now, fail again, opted out
		dl.txn(fundgold.Noted("2"), fmt.Sprintf("asset %d missing", asaID))

		// Do it all again, so we can test closeTo when we have a non-zero balance
		// Tell the app to opt itself in.
		dl.txns(optin.Noted("a"), fundgold.Noted("a"))

		amount, _ = holding(t, dl.generator, appID.Address(), asaID)
		require.Equal(t, uint64(20000), amount)
		left, _ := holding(t, dl.generator, addrs[0], asaID)

		dl.txn(close.Noted("a"))

		amount, _ = holding(t, dl.generator, appID.Address(), asaID)
		require.Zero(t, amount)
		back, _ := holding(t, dl.generator, addrs[0], asaID)
		require.Equal(t, uint64(20000), back-left)
	})
}

// TestClawbackAction ensures an app address can act as clawback address.
func TestClawbackAction(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 31 allowed inner appl.
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		app := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: main(`
         itxn_begin
          int axfer;       itxn_field TypeEnum
          txn Assets 0;    itxn_field XferAsset
          txn Accounts 1;  itxn_field AssetSender
          txn Accounts 2;  itxn_field AssetReceiver
          int 1000;        itxn_field AssetAmount
         itxn_submit
`),
		}
		appID := dl.txn(&app).ApplyData.ApplicationID

		asa := txntest.Txn{
			Type:   "acfg",
			Sender: addrs[0],
			AssetParams: basics.AssetParams{
				Total:    1005,
				Clawback: appID.Address(),
			},
		}
		asaID := dl.txn(&asa).ApplyData.ConfigAsset

		optin := txntest.Txn{
			Type:          "axfer",
			Sender:        addrs[1],
			AssetReceiver: addrs[1],
			XferAsset:     asaID,
		}
		dl.txn(&optin)

		bystander := addrs[2] // Has no authority of its own
		overpay := txntest.Txn{
			Type:     "pay",
			Sender:   bystander,
			Receiver: bystander,
			Fee:      2000, // Overpay fee so that app account can be unfunded
		}
		clawmove := txntest.Txn{
			Type:          "appl",
			Sender:        bystander,
			ApplicationID: appID,
			ForeignAssets: []basics.AssetIndex{asaID},
			Accounts:      []basics.Address{addrs[0], addrs[1]},
		}
		dl.txgroup("", &overpay, &clawmove)

		amount, _ := holding(t, dl.generator, addrs[1], asaID)
		require.EqualValues(t, 1000, amount)
		amount, _ = holding(t, dl.generator, addrs[0], asaID)
		require.EqualValues(t, 5, amount)
	})
}

// TestRekeyAction ensures an app can transact for a rekeyed account
func TestRekeyAction(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 30 allowed inner txns.
	ledgertesting.TestConsensusRange(t, 30, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		ezpayer := txntest.Txn{
			Type:   "appl",
			Sender: addrs[5],
			ApprovalProgram: main(`
         itxn_begin
          int pay;         itxn_field TypeEnum
          int 5000;        itxn_field Amount
          txn Accounts 1;  itxn_field Sender
          txn Accounts 2;  itxn_field Receiver
          txn NumAccounts
          int 3
          ==
          bz skipclose
          txn Accounts 3;  itxn_field CloseRemainderTo
skipclose:
         itxn_submit
`),
		}
		appID := dl.txn(&ezpayer).ApplyData.ApplicationID

		rekey := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: addrs[0],
			RekeyTo:  appID.Address(),
		}

		dl.txn(&rekey)

		useacct := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: appID,
			Accounts:      []basics.Address{addrs[0], addrs[2]}, // pay 2 from 0 (which was rekeyed)
		}
		dl.txn(&useacct)

		// App was never funded (didn't spend from it's own acct)
		require.Zero(t, micros(t, dl.generator, appID.Address()))
		// addrs[2] got paid
		require.Equal(t, uint64(5000), micros(t, dl.generator, addrs[2])-micros(t, dl.generator, addrs[6]))
		// addrs[0] paid 5k + rekey fee + inner txn fee
		require.Equal(t, uint64(7000), micros(t, dl.generator, addrs[6])-micros(t, dl.generator, addrs[0]))

		baduse := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: appID,
			Accounts:      []basics.Address{addrs[2], addrs[0]}, // pay 0 from 2
		}
		dl.txn(&baduse, "unauthorized")

		// Now, we close addrs[0], which wipes its rekey status.  Reopen
		// it, and make sure the app can't spend.

		close := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: appID,
			Accounts:      []basics.Address{addrs[0], addrs[2], addrs[3]}, // close to 3
		}
		dl.txn(&close)

		require.Zero(t, micros(t, dl.generator, addrs[0]))

		payback := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[3],
			Receiver: addrs[0],
			Amount:   10_000_000,
		}
		dl.txn(&payback)

		require.Equal(t, uint64(10_000_000), micros(t, dl.generator, addrs[0]))

		dl.txn(useacct.Noted("2"), "unauthorized")
	})
}

// TestRekeyActionCloseAccount ensures closing and reopening a rekeyed account in a single app call
// properly removes the app as an authorizer for the account
func TestRekeyActionCloseAccount(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 30 allowed inner txs.
	ledgertesting.TestConsensusRange(t, 30, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		// use addrs[5] for creation, so addr[0] will be closeable
		appID := dl.fundedApp(addrs[5], 1_000_000,
			main(`
         // pay from, and close, account 1
         itxn_begin
          int pay;         itxn_field TypeEnum
          txn Accounts 1;  itxn_field Sender
          txn Accounts 2;  itxn_field CloseRemainderTo
         itxn_submit

         // reopen account 1
         itxn_begin
          int pay;         itxn_field TypeEnum
          int 5000;        itxn_field Amount
          txn Accounts 1;  itxn_field Receiver
         itxn_submit

         // send from account 1 again (should fail because closing an account erases rekeying)
         itxn_begin
          int pay;         itxn_field TypeEnum
          int 1;           itxn_field Amount
          txn Accounts 1;  itxn_field Sender
          txn Accounts 2;  itxn_field Receiver
         itxn_submit
`))

		// rekey addr[1] to the app
		dl.txn(&txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: addrs[0],
			RekeyTo:  appID.Address(),
		})

		useacct := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: appID,
			Accounts:      []basics.Address{addrs[0], addrs[2]},
		}
		dl.txn(&useacct, "unauthorized")
		// do it again, to ensure the lack of authorization is in the right
		// place, by matching on the opcode that comes before the itxn_submit we
		// want to know failed (it'll be in the error).
		dl.txn(&useacct, "itxn_field Receiver")
	})
}

// TestDuplicatePayAction shows two pays with same parameters can be done as inner tarnsactions
func TestDuplicatePayAction(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// Inner txns start in v30
	ledgertesting.TestConsensusRange(t, 30, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		source := main(`
         itxn_begin
          int pay;         itxn_field TypeEnum
          int 5000;        itxn_field Amount
          txn Accounts 1;  itxn_field Receiver
         itxn_submit
         itxn_begin
          int pay;         itxn_field TypeEnum
          int 5000;        itxn_field Amount
          txn Accounts 1;  itxn_field Receiver
         itxn_submit
`)
		appID := dl.fundedApp(addrs[0], 200_000, source)

		paytwice := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: appID,
			Accounts:      []basics.Address{addrs[1]}, // pay self
		}

		dl.txn(&paytwice)
		copyID := dl.fundedApp(addrs[0], 200_000, source)
		require.Equal(t, appID+5, copyID) // 4 between (fund, outer, two innner pays)

		ad0 := micros(t, dl.generator, addrs[0])
		ad1 := micros(t, dl.generator, addrs[1])
		app := micros(t, dl.generator, appID.Address())

		// create(1000) and fund(1000 + 200000), extra create+fund (1000 + 201000)
		require.Equal(t, 404000, int(genBalances.Balances[addrs[0]].MicroAlgos.Raw-ad0))
		// paid 10000, but 1000 fee on tx
		require.Equal(t, 9000, int(ad1-genBalances.Balances[addrs[1]].MicroAlgos.Raw))
		// app still has 188000 (paid out 10000, and paid 2 x fee to do it)
		require.Equal(t, 188000, int(app))

		// Now create another app, and see if it gets the ID we expect (2
		// higher, because of the intervening fund txn)
		finalID := dl.fundedApp(addrs[0], 200_000, source)
		require.Equal(t, copyID+2, finalID)
	})
}

// TestInnerTxCount ensures that inner transactions increment the TxnCounter
func TestInnerTxnCount(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 30 allowed inner txs.
	ledgertesting.TestConsensusRange(t, 30, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		appID := dl.fundedApp(addrs[0], 200000, // account min balance, plus fees
			main(`
         itxn_begin
         int pay
         itxn_field TypeEnum
         int 5000
         itxn_field Amount
         txn Accounts 1
         itxn_field Receiver
         itxn_submit
`))

		payout1 := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: appID,
			Accounts:      []basics.Address{addrs[1]}, // pay self
		}

		vb := dl.fullBlock(&payout1)
		before := vb.Block().TxnCounter
		vb = dl.fullBlock(payout1.Noted("again"))
		require.Equal(t, before+2, vb.Block().TxnCounter)
	})
}

// TestAcfgAction ensures assets can be created and configured in teal
func TestAcfgAction(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 30 allowed inner txs.
	ledgertesting.TestConsensusRange(t, 30, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		appID := dl.fundedApp(addrs[0], 200_000, // exactly account min balance + one asset
			main(`
         itxn_begin
         int acfg
         itxn_field TypeEnum

         txn ApplicationArgs 0
         byte "create"
         ==
         bz manager
		 int 1000000
		 itxn_field ConfigAssetTotal
		 int 3
		 itxn_field ConfigAssetDecimals
		 byte "oz"
		 itxn_field ConfigAssetUnitName
		 byte "Gold"
		 itxn_field ConfigAssetName
		 byte "https://gold.rush/"
		 itxn_field ConfigAssetURL

         global CurrentApplicationAddress
         dup
         dup2
         itxn_field ConfigAssetManager
         itxn_field ConfigAssetReserve
         itxn_field ConfigAssetFreeze
         itxn_field ConfigAssetClawback
         b submit
manager:
         // Put the current values in the itxn
         txn Assets 0
         asset_params_get AssetManager
         assert // exists
		 itxn_field ConfigAssetManager

         txn Assets 0
         asset_params_get AssetReserve
         assert // exists
		 itxn_field ConfigAssetReserve

         txn Assets 0
         asset_params_get AssetFreeze
         assert // exists
		 itxn_field ConfigAssetFreeze

         txn Assets 0
         asset_params_get AssetClawback
         assert // exists
		 itxn_field ConfigAssetClawback


         txn ApplicationArgs 0
         byte "manager"
         ==
         bz reserve
         txn Assets 0
         itxn_field ConfigAsset
         txn ApplicationArgs 1
		 itxn_field ConfigAssetManager
         b submit
reserve:
         txn ApplicationArgs 0
         byte "reserve"
         ==
         bz freeze
         txn Assets 0
         itxn_field ConfigAsset
         txn ApplicationArgs 1
		 itxn_field ConfigAssetReserve
         b submit
freeze:
         txn ApplicationArgs 0
         byte "freeze"
         ==
         bz clawback
         txn Assets 0
         itxn_field ConfigAsset
         txn ApplicationArgs 1
		 itxn_field ConfigAssetFreeze
         b submit
clawback:
         txn ApplicationArgs 0
         byte "clawback"
         ==
         bz error
         txn Assets 0
         itxn_field ConfigAsset
         txn ApplicationArgs 1
		 itxn_field ConfigAssetClawback
         b submit
error:   err
submit:  itxn_submit
`))

		createAsa := txntest.Txn{
			Type:            "appl",
			Sender:          addrs[1],
			ApplicationID:   appID,
			ApplicationArgs: [][]byte{[]byte("create")},
		}

		// Can't create an asset if you have exactly 200,000 and need to pay fee
		dl.txn(&createAsa, "balance 199000 below min 200000")
		// add some more
		dl.txn(&txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: appID.Address(),
			Amount:   10_000,
		})
		asaID := dl.txn(&createAsa).EvalDelta.InnerTxns[0].ConfigAsset
		require.NotZero(t, asaID)

		asaParams, err := asaParams(t, dl.generator, asaID)
		require.NoError(t, err)

		require.Equal(t, 1_000_000, int(asaParams.Total))
		require.Equal(t, 3, int(asaParams.Decimals))
		require.Equal(t, "oz", asaParams.UnitName)
		require.Equal(t, "Gold", asaParams.AssetName)
		require.Equal(t, "https://gold.rush/", asaParams.URL)

		require.Equal(t, appID.Address(), asaParams.Manager)

		for _, a := range []string{"reserve", "freeze", "clawback", "manager"} {
			check := txntest.Txn{
				Type:            "appl",
				Sender:          addrs[1],
				ApplicationID:   appID,
				ApplicationArgs: [][]byte{[]byte(a), []byte("junkjunkjunkjunkjunkjunkjunkjunk")},
				ForeignAssets:   []basics.AssetIndex{asaID},
			}
			t.Log(a)
			dl.txn(&check)
		}
		// Not the manager anymore so this won't work
		nodice := txntest.Txn{
			Type:            "appl",
			Sender:          addrs[1],
			ApplicationID:   appID,
			ApplicationArgs: [][]byte{[]byte("freeze"), []byte("junkjunkjunkjunkjunkjunkjunkjunk")},
			ForeignAssets:   []basics.AssetIndex{asaID},
		}
		dl.txn(&nodice, "this transaction should be issued by the manager")
	})
}

// TestAsaDuringInit ensures an ASA can be made while initilizing an
// app.  In practice, this is impossible, because you would not be
// able to prefund the account - you don't know the app id.  But here
// we can know, so it helps exercise txncounter changes.
func TestAsaDuringInit(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 30 allowed inner txs.
	ledgertesting.TestConsensusRange(t, 30, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		appID := basics.AppIndex(2)
		if ver >= 38 { // AppForbidLowResources
			appID += 1000
		}
		prefund := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: appID.Address(),
			Amount:   300000, // plenty for min balances, fees
		}

		app := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: `
         itxn_begin
         int acfg;      itxn_field TypeEnum
		  int 1000000;  itxn_field ConfigAssetTotal
		  byte "oz";	itxn_field ConfigAssetUnitName
		  byte "Gold";  itxn_field ConfigAssetName
         itxn_submit
         itxn CreatedAssetID
         int ` + strconv.Itoa(int(appID+1)) + `
         ==
         assert
         itxn CreatedApplicationID; int 0; ==; assert
         itxn NumLogs; int 0; ==`,
		}

		payset := dl.txns(&prefund, &app)
		require.Equal(t, appID, payset[1].ApplicationID)

		asaID := payset[1].EvalDelta.InnerTxns[0].ConfigAsset
		require.EqualValues(t, appID+1, asaID)
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 31 allowed inner rekeys.
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		appID := dl.fundedApp(addrs[0], 1_000_000,
			main(`
  itxn_begin
   int pay
   itxn_field TypeEnum
   int 1
   itxn_field Amount
   global CurrentApplicationAddress
   itxn_field Receiver
   int 31
   bzero
   byte 0x01
   concat
   itxn_field RekeyTo
  itxn_submit
`))
		require.NotZero(t, appID)

		rekey := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: appID,
		}
		dl.fullBlock(&rekey)
		dl.txn(rekey.Noted("2"), "unauthorized")
	})
}

// TestInnerAppCreateAndOptin tests a weird way to create an app and opt it into
// an ASA all from one top-level transaction. Part of the trick is to use an
// inner helper app.  The app being created rekeys itself to the inner app,
// which funds the outer app and opts it into the ASA. It could have worked
// differently - the inner app could have just funded the outer app, and then
// the outer app could have opted-in.  But this technique tests something
// interesting, that the inner app can perform an opt-in on the outer app, which
// tests that the newly created app's holdings are available. In practice, the
// helper shold rekey it back, but we don't bother here.
func TestInnerAppCreateAndOptin(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// v31 allows inner appl and inner rekey
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		createasa := txntest.Txn{
			Type:        "acfg",
			Sender:      addrs[0],
			AssetParams: basics.AssetParams{Total: 2, UnitName: "$"},
		}
		asaID := dl.txn(&createasa).ApplyData.ConfigAsset
		require.NotZero(t, asaID)

		// helper app, is called during the creation of an app.  When such an
		// app is created, it rekeys itself to this helper and calls it. The
		// helpers opts the caller into an ASA, and funds the MBR the caller
		// needs for that optin.
		helper := dl.fundedApp(addrs[0], 1_000_000,
			main(`
  itxn_begin
   int axfer; itxn_field TypeEnum
   int `+strconv.Itoa(int(asaID))+`; itxn_field XferAsset
   txn Sender; itxn_field Sender // call as the caller! (works because of rekey by caller)
   txn Sender; itxn_field AssetReceiver // 0 to self == opt-in
  itxn_next
   int pay;	   itxn_field TypeEnum // pay 200kmAlgo to the caller, for MBR
   int 200000; itxn_field Amount
   txn Sender; itxn_field Receiver
  itxn_submit
`))
		// Don't use `main` here, we want to do the work during creation. Rekey
		// to the helper and invoke it, trusting it to opt us into the ASA.
		createapp := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			Fee:    3 * 1000, // to pay for self, call to helper, and helper's axfer
			ApprovalProgram: `
  itxn_begin
   int appl;      itxn_field TypeEnum
   addr ` + helper.Address().String() + `; itxn_field RekeyTo
   int ` + strconv.Itoa(int(helper)) + `; itxn_field ApplicationID
   txn Assets 0; itxn_field Assets
  itxn_submit
  int 1
`,
			ForeignApps:   []basics.AppIndex{helper},
			ForeignAssets: []basics.AssetIndex{asaID},
		}
		appID := dl.txn(&createapp).ApplyData.ApplicationID
		require.NotZero(t, appID)
	})
}

// TestParentGlobals tests that a newly created app can call an inner app, and
// the inner app will have access to the parent globals, even if the originally
// created app ID isn't passed down, because the rule is that "pending" created
// apps are available, starting from v38
func TestParentGlobals(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// v38 allows parent access, but we start with v31 to make sure we don't mistakenly change it
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		// helper app, is called during the creation of an app.  this app tries
		// to access its parent's globals, by using `global CallerApplicationID`
		helper := dl.fundedApp(addrs[0], 1_000_000,
			main(`
  global CallerApplicationID
  byte "X"
  app_global_get_ex; pop; pop;	// we only care that it didn't panic
`))

		// Don't use `main` here, we want to do the work during creation.
		createProgram := `
  itxn_begin
   int appl;      itxn_field TypeEnum
   int ` + strconv.Itoa(int(helper)) + `; itxn_field ApplicationID
  itxn_submit
  int 1
`
		createapp := txntest.Txn{
			Type:            "appl",
			Sender:          addrs[0],
			Fee:             2 * 1000, // to pay for self and call to helper
			ApprovalProgram: createProgram,
			ForeignApps:     []basics.AppIndex{helper},
		}
		var creator basics.AppIndex
		if ver >= 38 {
			creator = dl.txn(&createapp).ApplyData.ApplicationID
			require.NotZero(t, creator)
		} else {
			dl.txn(&createapp, "unavailable App")
		}

		// Now, test the same pattern, but do it all inside of yet another outer
		// app, to show that the parent is available even if it was, itself
		// created as an inner.  To do so, we also need to get 0.2 MBR to the
		// outer app, since it will be creating the "middle" app.

		outerAppAddress := (creator + 3).Address() // creator called an inner, so next is creator+2, then fund
		outer := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			Fee:    3 * 1000, // to pay for self, call to inner create, and its call to helper
			ApprovalProgram: `
  itxn_begin
   int appl;      itxn_field TypeEnum
   byte 0x` + hex.EncodeToString(createapp.SignedTxn().Txn.ApprovalProgram) + `; itxn_field ApprovalProgram
   byte 0x` + hex.EncodeToString(createapp.SignedTxn().Txn.ClearStateProgram) + `; itxn_field ClearStateProgram
  itxn_submit
  int 1
`,
			ForeignApps: []basics.AppIndex{creator, helper},
		}
		fund := txntest.Txn{
			Type:     "pay",
			Amount:   200_000,
			Sender:   addrs[0],
			Receiver: outerAppAddress,
		}
		if ver >= 38 {
			dl.txgroup("", &fund, &outer)
		} else {
			dl.txn(&createapp, "unavailable App")
		}

	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 31 allowed inner note setting.
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		appID := dl.fundedApp(addrs[0], 1_000_000,
			main(`
  itxn_begin
   int pay
   itxn_field TypeEnum
   int 0
   itxn_field Amount
   global CurrentApplicationAddress
   itxn_field Receiver
   byte "abcdefghijklmnopqrstuvwxyz01234567890"
   itxn_field Note
  itxn_submit
`))

		note := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: appID,
		}

		alphabet := dl.txn(&note).EvalDelta.InnerTxns[0].Txn.Note
		require.Equal(t, "abcdefghijklmnopqrstuvwxyz01234567890", string(alphabet))
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	l := newTestLedger(t, genBalances)
	defer l.Close()

	app := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  txn ApplicationArgs 0
  byte "pay"
  ==
  bz nonpart
  itxn_begin
   int pay
   itxn_field TypeEnum
   int 1
   itxn_field Amount
   txn Sender
   itxn_field Receiver
  itxn_submit
  int 1
  return
nonpart:
  itxn_begin
   int keyreg
   itxn_field TypeEnum
   int 1
   itxn_field Nonparticipation
  itxn_submit
`),
	}

	// Create the app
	eval := nextBlock(t, l)
	txns(t, l, eval, &app)
	vb := endBlock(t, l, eval)
	appID := vb.Block().Payset[0].ApplicationID
	require.NotZero(t, appID)

	// Give the app a lot of money
	fund := txntest.Txn{
		Type:     "pay",
		Sender:   addrs[0],
		Receiver: appID.Address(),
		Amount:   1_000_000_000,
	}
	eval = nextBlock(t, l)
	txn(t, l, eval, &fund)
	endBlock(t, l, eval)

	require.Equal(t, 1_000_000_000, int(micros(t, l, appID.Address())))

	// Build up Residue in RewardsState so it's ready to pay
	for i := 1; i < 10; i++ {
		eval := nextBlock(t, l)
		endBlock(t, l, eval)
	}

	// pay a little
	pay := txntest.Txn{
		Type:            "appl",
		Sender:          addrs[0],
		ApplicationID:   appID,
		ApplicationArgs: [][]byte{[]byte("pay")},
	}
	eval = nextBlock(t, l)
	txn(t, l, eval, &pay)
	endBlock(t, l, eval)
	// 2000 was earned in rewards (- 1000 fee, -1 pay)
	require.Equal(t, 1_000_000_999, int(micros(t, l, appID.Address())))

	// Go nonpart
	nonpart := txntest.Txn{
		Type:            "appl",
		Sender:          addrs[0],
		ApplicationID:   appID,
		ApplicationArgs: [][]byte{[]byte("nonpart")},
	}
	eval = nextBlock(t, l)
	txn(t, l, eval, &nonpart)
	endBlock(t, l, eval)
	require.Equal(t, 999_999_999, int(micros(t, l, appID.Address())))

	// Build up Residue in RewardsState so it's ready to pay AGAIN
	// But expect no rewards
	for i := 1; i < 100; i++ {
		eval := nextBlock(t, l)
		endBlock(t, l, eval)
	}
	eval = nextBlock(t, l)
	txn(t, l, eval, pay.Noted("again"))
	txn(t, l, eval, nonpart.Noted("again"), "cannot change online/offline")
	endBlock(t, l, eval)
	// Paid fee + 1.  Did not get rewards
	require.Equal(t, 999_998_998, int(micros(t, l, appID.Address())))
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	l := newTestLedger(t, genBalances)
	defer l.Close()

	app0 := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  itxn_begin
   int pay
   itxn_field TypeEnum
   int 1
   itxn_field Amount
   txn Sender
   itxn_field Receiver
  itxn_submit
`),
	}
	eval := nextBlock(t, l)
	txn(t, l, eval, &app0)
	vb := endBlock(t, l, eval)
	id0 := vb.Block().Payset[0].ApplicationID

	app1 := txntest.Txn{
		Type:   "appl",
		Sender: addrs[1],
		ApprovalProgram: main(`
  itxn_begin
   int appl
   itxn_field TypeEnum
   txn Applications 1
   itxn_field ApplicationID
  itxn_submit
`),
	}

	eval = nextBlock(t, l)
	txns(t, l, eval, &app1)
	vb = endBlock(t, l, eval)
	id1 := vb.Block().Payset[0].ApplicationID

	fund0 := txntest.Txn{
		Type:     "pay",
		Sender:   addrs[0],
		Receiver: id0.Address(),
		Amount:   1_000_000_000,
	}
	fund1 := fund0
	fund1.Receiver = id1.Address()

	call1 := txntest.Txn{
		Type:          "appl",
		Sender:        addrs[2],
		ApplicationID: id1,
		ForeignApps:   []basics.AppIndex{id0},
	}
	eval = nextBlock(t, l)
	txns(t, l, eval, &fund0, &fund1, &call1)
	endBlock(t, l, eval)

}

// TestInnerAppManipulate ensures that apps called from inner transactions make
// the changes expected when invoked.
func TestInnerAppManipulate(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 31 allowed inner appl.
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		callee := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			// This app set a global key arg[1] to arg[2] or get arg[1] and log it
			ApprovalProgram: main(`
 txn ApplicationArgs 0
 byte "set"
 ==
 bz next1
 txn ApplicationArgs 1
 txn ApplicationArgs 2
 app_global_put
 b end
next1:
 txn ApplicationArgs 0
 byte "get"
 ==
 bz next2
 txn ApplicationArgs 1
 app_global_get
 log							// Fails if key didn't exist, b/c TOS = 0
 b end
next2:
 err
`),
			GlobalStateSchema: basics.StateSchema{
				NumByteSlice: 1,
			},
		}

		calleeIndex := dl.txn(&callee).ApplyData.ApplicationID
		require.NotZero(t, calleeIndex)

		fund := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: calleeIndex.Address(),
			Amount:   1_000_000,
		}
		dl.fullBlock(&fund)

		callerIndex := dl.fundedApp(addrs[0], 1_000_000, main(`
 itxn_begin
   int appl
   itxn_field TypeEnum
   txn Applications 1
   itxn_field ApplicationID
   byte "set"
   itxn_field ApplicationArgs
   byte "X"
   itxn_field ApplicationArgs
   byte "A"
   itxn_field ApplicationArgs
  itxn_submit
  itxn NumLogs
  int 0
  ==
  assert
  b end
`))

		call := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[0],
			ApplicationID: callerIndex,
			ForeignApps:   []basics.AppIndex{calleeIndex},
		}
		tib := dl.txn(&call)
		// No changes in the top-level EvalDelta
		require.Empty(t, tib.EvalDelta.GlobalDelta)
		require.Empty(t, tib.EvalDelta.LocalDeltas)

		inner := tib.EvalDelta.InnerTxns[0]
		require.Empty(t, inner.EvalDelta.LocalDeltas)

		require.Len(t, inner.EvalDelta.GlobalDelta, 1)
		require.Equal(t, basics.ValueDelta{
			Action: basics.SetBytesAction,
			Bytes:  "A",
		}, inner.EvalDelta.GlobalDelta["X"])
	})
}

// TestCreateAndUse checks that an ASA can be created in an early tx, and then
// used in a later app call tx (in the same group).  This was not allowed until
// teal 6 (v31), because of the strict adherence to the foreign-arrays rules.
func TestCreateAndUse(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// At 30 the asset reference is illegal, then from v31 it works.
	ledgertesting.TestConsensusRange(t, 30, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		appID := dl.fundedApp(addrs[0], 1_000_000, main(`
         itxn_begin
          int axfer; itxn_field TypeEnum
          int 0;     itxn_field Amount
          gaid 0;    itxn_field XferAsset
          global CurrentApplicationAddress;  itxn_field Sender
          global CurrentApplicationAddress;  itxn_field AssetReceiver
         itxn_submit
`))

		createasa := txntest.Txn{
			Type:   "acfg",
			Sender: addrs[0],
			AssetParams: basics.AssetParams{
				Total: 1000000,
			},
		}
		asaID := basics.AssetIndex(appID + 2) // accounts for intervening fund txn

		use := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[0],
			ApplicationID: appID,
			// The point of this test is to show the following (psychic) setting is unnecessary.
			//ForeignAssets: []basics.AssetIndex{asaID},
		}

		if ver == 30 {
			dl.txgroup("unavailable Asset", &createasa, &use)
			return
		}
		// v31 onward, create & use works
		payset := dl.txgroup("", &createasa, &use)
		require.Equal(t, asaID, payset[0].ApplyData.ConfigAsset)
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// At 30 `gtxn CreatedAssetID` is illegal, then from v31 it works.
	ledgertesting.TestConsensusRange(t, 30, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		// needed in very first app, so hardcode
		asaID := basics.AssetIndex(3)
		if ver >= 38 {
			asaID += 1000
		}
		appID := dl.fundedApp(addrs[0], 1_000_000, main(`
         gtxn 0 CreatedAssetID
         int `+strconv.Itoa(int(asaID))+`
         ==
         assert`))

		createasa := txntest.Txn{
			Type:   "acfg",
			Sender: addrs[0],
			AssetParams: basics.AssetParams{
				Total:     1000000,
				Decimals:  3,
				UnitName:  "oz",
				AssetName: "Gold",
				URL:       "https://gold.rush/",
			},
		}
		see := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[0],
			ApplicationID: appID,
		}

		if ver == 30 {
			dl.txgroup("Unable to obtain effects from top-level transactions", &createasa, &see)
			return
		}
		payset := dl.txgroup("", &createasa, &see)
		require.Equal(t, asaID, payset[0].ApplyData.ConfigAsset)
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		app0 := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: main(`
  itxn_begin
   int appl
   itxn_field TypeEnum
   txn Applications 1
   itxn_field ApplicationID
  itxn_submit`),
		}
		id0 := dl.txn(&app0).ApplyData.ApplicationID

		call1 := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[2],
			ApplicationID: id0,
			ForeignApps:   []basics.AppIndex{id0},
		}
		dl.txn(&call1, "self-call")
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	l := newTestLedger(t, genBalances)
	defer l.Close()

	app0 := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  itxn_begin
   int appl
   itxn_field TypeEnum
   txn Applications 1
   itxn_field ApplicationID
   txn Applications 2
   itxn_field Applications
  itxn_submit
`),
	}
	eval := nextBlock(t, l)
	txn(t, l, eval, &app0)
	vb := endBlock(t, l, eval)
	id0 := vb.Block().Payset[0].ApplicationID

	fund := txntest.Txn{
		Type:     "pay",
		Sender:   addrs[0],
		Receiver: id0.Address(),
		Amount:   1_000_000,
	}

	app1 := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  itxn_begin
   int appl
   itxn_field TypeEnum
   txn Applications 1
   itxn_field ApplicationID
  itxn_submit
`),
	}
	eval = nextBlock(t, l)
	txns(t, l, eval, &app1, &fund)
	vb = endBlock(t, l, eval)
	id1 := vb.Block().Payset[0].ApplicationID

	call1 := txntest.Txn{
		Type:          "appl",
		Sender:        addrs[0],
		ApplicationID: id0,
		ForeignApps:   []basics.AppIndex{id1, id0},
	}
	eval = nextBlock(t, l)
	txn(t, l, eval, &call1, "attempt to re-enter")
	endBlock(t, l, eval)
}

// TestValidAppReentry tests a valid form of reentry (which may not be the correct word here).
// When A calls B then returns to A then A calls C which calls B, the execution
// should not produce an error because B doesn't occur in the call stack twice.
func TestValidAppReentry(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	l := newTestLedger(t, genBalances)
	defer l.Close()

	app0 := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  itxn_begin
   int appl
   itxn_field TypeEnum
   txn Applications 2
   itxn_field ApplicationID
  itxn_submit

  itxn_begin
   int appl
   itxn_field TypeEnum
   txn Applications 1
   itxn_field ApplicationID
   txn Applications 2
   itxn_field Applications
  itxn_submit
`),
	}
	eval := nextBlock(t, l)
	txn(t, l, eval, &app0)
	vb := endBlock(t, l, eval)
	id0 := vb.Block().Payset[0].ApplicationID

	fund0 := txntest.Txn{
		Type:     "pay",
		Sender:   addrs[0],
		Receiver: id0.Address(),
		Amount:   1_000_000,
	}

	app1 := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  int 3
  int 3
  ==
  assert
`),
	}
	eval = nextBlock(t, l)
	txns(t, l, eval, &app1, &fund0)
	vb = endBlock(t, l, eval)
	id1 := vb.Block().Payset[0].ApplicationID

	app2 := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  itxn_begin
   int appl
   itxn_field TypeEnum
   txn Applications 1
   itxn_field ApplicationID
  itxn_submit
`),
	}
	eval = nextBlock(t, l)
	txn(t, l, eval, &app2)
	vb = endBlock(t, l, eval)
	id2 := vb.Block().Payset[0].ApplicationID

	fund2 := txntest.Txn{
		Type:     "pay",
		Sender:   addrs[0],
		Receiver: id2.Address(),
		Amount:   1_000_000,
	}

	eval = nextBlock(t, l)
	txn(t, l, eval, &fund2)
	_ = endBlock(t, l, eval)

	call1 := txntest.Txn{
		Type:          "appl",
		Sender:        addrs[0],
		ApplicationID: id0,
		ForeignApps:   []basics.AppIndex{id2, id1, id0},
	}
	eval = nextBlock(t, l)
	txn(t, l, eval, &call1)
	endBlock(t, l, eval)
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// v31 = inner appl
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		program := `
txn ApplicationArgs 0
btoi
store 0
int 1
loop:
itxn_begin
  int appl
  itxn_field TypeEnum
  txn Applications 1
  itxn_field ApplicationID
itxn_submit
int 1
+
dup
load 0
<=
bnz loop
load 0
int 1
+
==
assert
`

		app0 := txntest.Txn{
			Type:            "appl",
			Sender:          addrs[0],
			ApprovalProgram: main(program),
		}
		id0 := dl.txn(&app0).ApplyData.ApplicationID

		fund0 := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: id0.Address(),
			Amount:   1_000_000,
		}

		app1 := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: main(`
  int 3
  int 3
  ==
  assert
`),
		}

		payset := dl.txns(&app1, &fund0)
		id1 := payset[0].ApplicationID

		callTxGroup := make([]*txntest.Txn, 16)
		callTxGroup[0] = &txntest.Txn{
			Type:            "appl",
			Sender:          addrs[0],
			ApplicationID:   id0,
			ForeignApps:     []basics.AppIndex{id1},
			ApplicationArgs: [][]byte{{1, 0}}, // 256 inner calls
		}
		for i := 1; i < 16; i++ {
			callTxGroup[i] = &txntest.Txn{
				Type:          "appl",
				Sender:        addrs[0],
				ApplicationID: id1,
				Note:          []byte{byte(i)},
			}
		}
		dl.txgroup("", callTxGroup...)

		// Can't do it twice in a single group
		dl.txgroup("too many inner", callTxGroup[0], callTxGroup[0].Noted("another"))

		// Don't need all those extra top-levels to be allowed to do 256 in tx0
		callTxGroup[0].Group = crypto.Digest{}
		dl.fullBlock(callTxGroup[0])

		// Can't do 257 txns
		callTxGroup[0].ApplicationArgs[0][1] = 1
		dl.txn(callTxGroup[0], "too many inner")
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	l := newTestLedger(t, genBalances)
	defer l.Close()

	app0 := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
itxn_begin
  int appl
  itxn_field TypeEnum
  txn Applications 1
  itxn_field ApplicationID
itxn_submit
int 1
int 1
==
assert
`),
	}
	eval := nextBlock(t, l)
	txn(t, l, eval, &app0)
	vb := endBlock(t, l, eval)
	id0 := vb.Block().Payset[0].ApplicationID

	fund0 := txntest.Txn{
		Type:     "pay",
		Sender:   addrs[0],
		Receiver: id0.Address(),
		Amount:   1_000_000,
	}

	app1 := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  int 3
  int 2
  ==
  assert
`),
	}
	eval = nextBlock(t, l)
	txns(t, l, eval, &app1, &fund0)
	vb = endBlock(t, l, eval)
	id1 := vb.Block().Payset[0].ApplicationID

	callTx := txntest.Txn{
		Type:          "appl",
		Sender:        addrs[0],
		ApplicationID: id0,
		ForeignApps:   []basics.AppIndex{id1},
	}

	eval = nextBlock(t, l)
	txn(t, l, eval, &callTx, "logic eval error")
	endBlock(t, l, eval)
}

// TestSelfCheckHoldingNewApp checks whether a newly created app can check its
// own holdings.  There can't really be any value in it from before this group,
// since it could not have opted in. But it should be legal to look.
func TestSelfCheckHoldingNewApp(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 31 allowed inner appls.
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		asset := txntest.Txn{
			Type:        "acfg",
			Sender:      addrs[0],
			ConfigAsset: 0,
			AssetParams: basics.AssetParams{
				Total:     10,
				Decimals:  1,
				UnitName:  "X",
				AssetName: "TEN",
			},
		}
		assetID := dl.txn(&asset).ApplyData.ConfigAsset

		selfcheck := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: `
 global CurrentApplicationAddress
 txn Assets 0
 asset_holding_get AssetBalance
 !; assert				// is not opted in, so exists=0
 !						// value is also 0
`,
			ForeignAssets: []basics.AssetIndex{assetID},
		}
		selfcheck.ApplicationID = dl.txn(&selfcheck).ApplicationID

		dl.txn(&selfcheck)

	})
}

// TestCheckHoldingNewApp checks whether a newly created app (account) can have
// its holding value checked in a later txn.  There can't really be any value in
// it from before this group, since it could not have opted in. But it should be
// legal to look.
func TestCheckHoldingNewApp(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 31 allowed inner appls.
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		asset := txntest.Txn{
			Type:        "acfg",
			Sender:      addrs[0],
			ConfigAsset: 0,
			AssetParams: basics.AssetParams{
				Total:     10,
				Decimals:  1,
				UnitName:  "X",
				AssetName: "TEN",
			},
		}
		assetID := dl.txn(&asset).ApplyData.ConfigAsset

		check := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: main(`
 gaid 0
 app_params_get AppAddress
 assert
 txn Assets 0
 asset_holding_get AssetBalance
 !; assert						// is not opted in, so exists=0
 !; assert						// value is also 0
`),
			ForeignAssets: []basics.AssetIndex{assetID},
		}
		check.ApplicationID = dl.txn(&check).ApplyData.ApplicationID

		create := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: 0,
		}
		dl.txgroup("", &create, &check)
	})
}

// TestInnerAppVersionCalling ensure that inner app calls must be the >=v6 apps
func TestInnerAppVersionCalling(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 31 allowed inner appls. v34 lowered proto.MinInnerApplVersion
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		three, err := logic.AssembleStringWithVersion("int 1", 3)
		require.NoError(t, err)
		five, err := logic.AssembleStringWithVersion("int 1", 5)
		require.NoError(t, err)
		six, err := logic.AssembleStringWithVersion("int 1", 6)
		require.NoError(t, err)

		create5 := txntest.Txn{
			Type:              "appl",
			Sender:            addrs[0],
			ApprovalProgram:   five.Program,
			ClearStateProgram: five.Program,
		}

		create6 := txntest.Txn{
			Type:              "appl",
			Sender:            addrs[0],
			ApprovalProgram:   six.Program,
			ClearStateProgram: six.Program,
		}

		create5with3 := txntest.Txn{
			Type:              "appl",
			Sender:            addrs[0],
			ApprovalProgram:   five.Program,
			ClearStateProgram: three.Program,
		}

		payset := dl.txns(&create5, &create6, &create5with3)
		v5id := payset[0].ApplicationID
		v6id := payset[1].ApplicationID
		v5withv3csp := payset[2].ApplicationID

		call := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			// don't use main. do the test at creation time
			ApprovalProgram: `
itxn_begin
	int appl
	itxn_field TypeEnum
	txn Applications 1
	itxn_field ApplicationID
itxn_submit`,
			ForeignApps: []basics.AppIndex{v5id},
		}

		// optin is the same as call, except also sets OnCompletion to optin
		optin := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			// don't use main. do the test at creation time
			ApprovalProgram: `
itxn_begin
	int appl
	itxn_field TypeEnum
	txn Applications 1
	itxn_field ApplicationID
    int OptIn
    itxn_field OnCompletion
itxn_submit`,
			ForeignApps: []basics.AppIndex{v5id},
		}

		// createAndOptin tries to create and optin to args[0], args[1] programs
		createAndOptin := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			// don't use main. do the test at creation time
			ApprovalProgram: `
itxn_begin
	int appl
	itxn_field TypeEnum
	txn ApplicationArgs 0
    itxn_field ApprovalProgram
	txn ApplicationArgs 1
    itxn_field ClearStateProgram
    int OptIn
    itxn_field OnCompletion
itxn_submit`,
		}

		if ver <= 33 {
			dl.txn(&call, "inner app call with version v5 < v6")
			call.ForeignApps[0] = v6id
			dl.txn(&call, "overspend") // it tried to execute, but test doesn't bother funding

			// Can't create a v3 app from inside an app, because that is calling
			createAndOptin.ApplicationArgs = [][]byte{three.Program, three.Program}
			dl.txn(&createAndOptin, "inner app call with version v3 < v6")

			// nor v5 in proto ver 33
			createAndOptin.ApplicationArgs = [][]byte{five.Program, five.Program}
			dl.txn(&createAndOptin, "inner app call with version v5 < v6")

			// 6 is good
			createAndOptin.ApplicationArgs = [][]byte{six.Program, six.Program}
			dl.txn(&createAndOptin, "overspend") // passed the checks, but is an overspend
		} else {
			// after 33 proto.MinInnerApplVersion is lowered to 4, so calls and optins to v5 are ok
			dl.txn(&call, "overspend")         // it tried to execute, but test doesn't bother funding
			dl.txn(&optin, "overspend")        // it tried to execute, but test doesn't bother funding
			optin.ForeignApps[0] = v5withv3csp // but we can't optin to a v5 if it has an old csp
			dl.txn(&optin, "CSP v3 < v4")      // it tried to execute, but test doesn't bother funding

			// Can't create a v3 app from inside an app, because that is calling
			createAndOptin.ApplicationArgs = [][]byte{three.Program, five.Program}
			dl.txn(&createAndOptin, "inner app call with version v3 < v4")
			// Can't create and optin to a v5/v3 app from inside an app
			createAndOptin.ApplicationArgs = [][]byte{five.Program, three.Program}
			dl.txn(&createAndOptin, "inner app call opt-in with CSP v3 < v4")

			createAndOptin.ApplicationArgs = [][]byte{five.Program, five.Program}
			dl.txn(&createAndOptin, "overspend") // passed the checks, but is an overspend
		}
	})

}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	l := newTestLedger(t, genBalances)
	defer l.Close()

	four, err := logic.AssembleStringWithVersion("int 1", 4)
	require.NoError(t, err)
	five, err := logic.AssembleStringWithVersion("int 1", 5)
	require.NoError(t, err)
	six, err := logic.AssembleStringWithVersion("int 1", 6)
	require.NoError(t, err)

	create := txntest.Txn{
		Type:              "appl",
		Sender:            addrs[0],
		ApprovalProgram:   five.Program,
		ClearStateProgram: five.Program,
	}

	eval := nextBlock(t, l)
	txn(t, l, eval, &create)
	endBlock(t, l, eval)

	create.ClearStateProgram = six.Program

	eval = nextBlock(t, l)
	txn(t, l, eval, &create, "version mismatch")
	endBlock(t, l, eval)

	create.ApprovalProgram = six.Program

	eval = nextBlock(t, l)
	txn(t, l, eval, &create)
	endBlock(t, l, eval)

	create.ClearStateProgram = four.Program

	eval = nextBlock(t, l)
	txn(t, l, eval, &create, "version mismatch")
	endBlock(t, l, eval)

	// four doesn't match five, but it doesn't have to
	create.ApprovalProgram = five.Program

	eval = nextBlock(t, l)
	txn(t, l, eval, &create)
	endBlock(t, l, eval)
}

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

	two, err := logic.AssembleStringWithVersion("int 1", 2)
	require.NoError(t, err)
	three, err := logic.AssembleStringWithVersion("int 1", 3)
	require.NoError(t, err)
	four, err := logic.AssembleStringWithVersion("int 1", 4)
	require.NoError(t, err)
	five, err := logic.AssembleStringWithVersion("int 1", 5)
	require.NoError(t, err)
	six, err := logic.AssembleStringWithVersion("int 1", 6)
	require.NoError(t, err)

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// Confirm that in old protocol version, downgrade is legal
	// Start at 28 because we want to v4 app to downgrade to v3
	ledgertesting.TestConsensusRange(t, 28, 30, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		create := txntest.Txn{
			Type:              "appl",
			Sender:            addrs[0],
			ApprovalProgram:   four.Program,
			ClearStateProgram: four.Program,
		}

		app := dl.txn(&create).ApplicationID

		update := txntest.Txn{
			Type:              "appl",
			ApplicationID:     app,
			OnCompletion:      transactions.UpdateApplicationOC,
			Sender:            addrs[0],
			ApprovalProgram:   three.Program,
			ClearStateProgram: three.Program,
		}

		// No change - legal
		dl.fullBlock(&update)

		update.ApprovalProgram = two.Program
		// Also legal, and let's check mismatched version while we're at it.
		dl.fullBlock(&update)
	})

	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		create := txntest.Txn{
			Type:              "appl",
			Sender:            addrs[0],
			ApprovalProgram:   four.Program,
			ClearStateProgram: four.Program,
		}

		app := dl.txn(&create).ApplicationID

		update := txntest.Txn{
			Type:              "appl",
			ApplicationID:     app,
			OnCompletion:      transactions.UpdateApplicationOC,
			Sender:            addrs[0],
			ApprovalProgram:   four.Program,
			ClearStateProgram: four.Program,
		}

		// No change - legal
		dl.fullBlock(&update)

		// Upgrade just the approval. Sure (because under 6, no need to match)
		update.ApprovalProgram = five.Program
		dl.fullBlock(&update)

		// Upgrade just the clear state. Now they match
		update.ClearStateProgram = five.Program
		dl.fullBlock(&update)

		// Downgrade (allowed for pre 6 programs until MinInnerApplVersion was lowered)
		update.ClearStateProgram = four.Program
		if ver <= 33 {
			dl.fullBlock(update.Noted("actually a repeat of first upgrade"))
		} else {
			dl.txn(update.Noted("actually a repeat of first upgrade"), "clearstate program version downgrade")
		}

		// Try to upgrade (at 6, must match)
		update.ApprovalProgram = six.Program
		dl.txn(&update, "version mismatch")

		// Do both
		update.ClearStateProgram = six.Program
		dl.fullBlock(&update)

		// Try to downgrade. Fails because it was 6.
		update.ApprovalProgram = five.Program
		update.ClearStateProgram = five.Program
		dl.txn(update.Noted("repeat of 3rd update"), "downgrade")
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// 31 allowed inner appl.
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		ops, err := logic.AssembleStringWithVersion("int 1\nint 1\nassert", dl.generator.GenesisProto().LogicSigVersion)
		require.NoError(t, err)
		program := "byte 0x" + hex.EncodeToString(ops.Program)

		appID := dl.fundedApp(addrs[0], 1_000_000,
			main(`
		 itxn_begin
		  int appl;    itxn_field TypeEnum
		  `+program+`; itxn_field ApprovalProgram
		  `+program+`; itxn_field ClearStateProgram
		  int 1;       itxn_field GlobalNumUint
		  int 2;       itxn_field LocalNumByteSlice
		  int 3;       itxn_field LocalNumUint
		 itxn_submit`))

		callCreator := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[0],
			ApplicationID: appID,
		}

		tib := dl.txn(&callCreator)
		createdID := tib.ApplyData.EvalDelta.InnerTxns[0].ApplyData.ApplicationID
		require.NotZero(t, createdID)

		callCreated := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[0],
			ApplicationID: createdID,
		}

		dl.txn(&callCreated)
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// v31 = inner appl
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		// make an app, which we'll try to use without setting up foreign array
		tib := dl.txn(&txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
		})
		appID := tib.ApplyData.ApplicationID

		// an app that tries to access appID when called
		app0 := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: main(`
itxn_begin
	int appl
	itxn_field TypeEnum
	int ` + strconv.Itoa(int(appID)) + `
	itxn_field ApplicationID
itxn_submit`),
		}
		callerID := dl.txn(&app0).ApplicationID

		fundCaller := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: callerID.Address(),
			Amount:   1_000_000,
		}
		dl.fullBlock(&fundCaller)

		callTx := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[0],
			ApplicationID: callerID,
		}

		dl.txn(&callTx, "unavailable App "+strconv.Itoa(int(appID)))

		// confirm everything is done right if ForeignApps _is_ set up
		callTx.ForeignApps = []basics.AppIndex{appID}
		dl.txn(&callTx)
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	// v31 = inner appl
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		createasa := txntest.Txn{
			Type:   "acfg",
			Sender: addrs[0],
			AssetParams: basics.AssetParams{
				Total:     1000000,
				UnitName:  "oz",
				AssetName: "Gold",
				URL:       "https://gold.rush/",
			},
		}
		asaID := dl.txn(&createasa).ConfigAsset
		require.NotZero(t, asaID)

		appID := dl.fundedApp(addrs[0], 1_000_000,
			main(`
			itxn_begin
			int axfer; itxn_field TypeEnum
			int 0;     itxn_field Amount
			int `+strconv.Itoa(int(asaID))+`;     itxn_field XferAsset
			global CurrentApplicationAddress;  itxn_field Sender
			global CurrentApplicationAddress;  itxn_field AssetReceiver
			itxn_submit
`))

		use := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[0],
			ApplicationID: appID,
		}

		dl.txn(&use, "unavailable Asset "+strconv.Itoa(int(asaID)))
		// confirm everything is done right if ForeignAssets _is_ set up
		use.ForeignAssets = []basics.AssetIndex{asaID}
		dl.txn(&use)

	})
}

func executeMegaContract(b *testing.B) {
	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	vTest := config.Consensus[protocol.ConsensusFuture]
	vTest.MaxAppProgramCost = 20000
	var cv protocol.ConsensusVersion = "temp test"
	config.Consensus[cv] = vTest

	cfg := config.GetDefaultLocal()
	l := newSimpleLedgerWithConsensusVersion(b, genBalances, cv, cfg)
	defer l.Close()
	defer delete(config.Consensus, cv)

	// app must use maximum memory then recursively create a new app with the same approval program.
	// recursion is terminated when a depth of 256 is reached
	// fill scratch space
	// fill stack
	depth := 255
	createapp := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: `
		int 0
		loop:
		dup
		int 4096
		bzero
		stores
		int 1
		+
		dup
		int 256
		<
		bnz loop
		pop
		int 0
		loop2:
		int 4096
		bzero
		swap
		int 1
		+
		dup
		int 994
		<=
		bnz loop2
		txna ApplicationArgs 0
		btoi
		int 1
		-
		dup
		int 0
		<=
		bnz done
		itxn_begin
		itob
		itxn_field ApplicationArgs
		int appl
		itxn_field TypeEnum
		txn ApprovalProgram
		itxn_field ApprovalProgram
		txn ClearStateProgram
		itxn_field ClearStateProgram
		itxn_submit
		done:
		int 1
		return`,
		ApplicationArgs:   [][]byte{{byte(depth)}},
		ExtraProgramPages: 3,
	}

	funds := make([]*txntest.Txn, 256)
	for i := 257; i <= 2*256; i++ {
		funds[i-257] = &txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: basics.AppIndex(i).Address(),
			Amount:   1_000_000,
		}
	}

	eval := nextBlock(b, l)
	txns(b, l, eval, funds...)
	endBlock(b, l, eval)

	app1 := txntest.Txn{
		Type:            "appl",
		Sender:          addrs[0],
		ApprovalProgram: `int 1`,
	}

	eval = nextBlock(b, l)
	err := txgroup(b, l, eval, &createapp, &app1, &app1, &app1, &app1, &app1, &app1)
	require.NoError(b, err)
	endBlock(b, l, eval)
}

func BenchmarkMaximumCallStackDepth(b *testing.B) {
	for i := 0; i < b.N; i++ {
		executeMegaContract(b)
	}
}

// TestInnerClearState ensures inner ClearState performs close out properly, even if rejects.
func TestInnerClearState(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	l := newTestLedger(t, genBalances)
	defer l.Close()

	// inner will be an app that we opt into, then clearstate
	// note that clearstate rejects
	inner := txntest.Txn{
		Type:              "appl",
		Sender:            addrs[0],
		ApprovalProgram:   "int 1",
		ClearStateProgram: "int 0",
		LocalStateSchema: basics.StateSchema{
			NumUint:      2,
			NumByteSlice: 2,
		},
	}

	eval := nextBlock(t, l)
	txn(t, l, eval, &inner)
	vb := endBlock(t, l, eval)
	innerID := vb.Block().Payset[0].ApplicationID

	// Outer is a simple app that will invoke the given app (in ForeignApps[0])
	// with the given OnCompletion (in ApplicationArgs[0]).  Goal is to use it
	// to opt into, and the clear state, on the inner app.
	outer := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
itxn_begin
 int appl
 itxn_field TypeEnum
 txn Applications 1
 itxn_field ApplicationID
 txn ApplicationArgs 0
 btoi
 itxn_field OnCompletion
itxn_submit
`),
		ForeignApps: []basics.AppIndex{innerID},
	}

	eval = nextBlock(t, l)
	txn(t, l, eval, &outer)
	vb = endBlock(t, l, eval)
	outerID := vb.Block().Payset[0].ApplicationID

	fund := txntest.Txn{
		Type:     "pay",
		Sender:   addrs[0],
		Receiver: outerID.Address(),
		Amount:   1_000_000,
	}

	call := txntest.Txn{
		Type:            "appl",
		Sender:          addrs[0],
		ApplicationID:   outerID,
		ApplicationArgs: [][]byte{{byte(transactions.OptInOC)}},
		ForeignApps:     []basics.AppIndex{innerID},
	}
	eval = nextBlock(t, l)
	txns(t, l, eval, &fund, &call)
	endBlock(t, l, eval)

	outerAcct := lookup(t, l, outerID.Address())
	require.Len(t, outerAcct.AppLocalStates, 1)
	require.Equal(t, outerAcct.TotalAppSchema, basics.StateSchema{
		NumUint:      2,
		NumByteSlice: 2,
	})

	call.ApplicationArgs = [][]byte{{byte(transactions.ClearStateOC)}}
	eval = nextBlock(t, l)
	txn(t, l, eval, &call)
	endBlock(t, l, eval)

	outerAcct = lookup(t, l, outerID.Address())
	require.Empty(t, outerAcct.AppLocalStates)
	require.Empty(t, outerAcct.TotalAppSchema)

}

// TestInnerClearStateBadCallee ensures that inner clear state programs are not
// allowed to use more than 700 (MaxAppProgramCost)
func TestInnerClearStateBadCallee(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	l := newTestLedger(t, genBalances)
	defer l.Close()

	// badCallee tries to run down your budget, so an inner clear must be
	// protected from exhaustion
	badCallee := txntest.Txn{
		Type:            "appl",
		Sender:          addrs[0],
		ApprovalProgram: "int 1",
		ClearStateProgram: `top:
int 1
pop
b top
`,
	}

	eval := nextBlock(t, l)
	txn(t, l, eval, &badCallee)
	vb := endBlock(t, l, eval)
	badID := vb.Block().Payset[0].ApplicationID

	// Outer is a simple app that will invoke the given app (in ForeignApps[0])
	// with the given OnCompletion (in ApplicationArgs[0]).  Goal is to use it
	// to opt into, and then clear state,  the bad app
	outer := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
itxn_begin
 int appl
 itxn_field TypeEnum
 txn Applications 1
 itxn_field ApplicationID
 txn ApplicationArgs 0
 btoi
 itxn_field OnCompletion
 global OpcodeBudget
 store 0
itxn_submit
global OpcodeBudget
store 1

txn ApplicationArgs 0
btoi
int ClearState
!=
bnz skip						// Don't do budget checking during optin
 load 0
 load 1
 int 3							// OpcodeBudget lines were 3 instructions apart
 +								// ClearState got 700 added to budget, tried to take all,
 ==								// but ended up just using that 700
 assert
skip:
`),
		ForeignApps: []basics.AppIndex{badID},
	}

	eval = nextBlock(t, l)
	txn(t, l, eval, &outer)
	vb = endBlock(t, l, eval)
	outerID := vb.Block().Payset[0].ApplicationID

	fund := txntest.Txn{
		Type:     "pay",
		Sender:   addrs[0],
		Receiver: outerID.Address(),
		Amount:   1_000_000,
	}

	call := txntest.Txn{
		Type:            "appl",
		Sender:          addrs[0],
		ApplicationID:   outerID,
		ApplicationArgs: [][]byte{{byte(transactions.OptInOC)}},
		ForeignApps:     []basics.AppIndex{badID},
	}
	eval = nextBlock(t, l)
	txns(t, l, eval, &fund, &call)
	endBlock(t, l, eval)

	outerAcct := lookup(t, l, outerID.Address())
	require.Len(t, outerAcct.AppLocalStates, 1)

	// When doing a clear state, `call` checks that budget wasn't stolen
	call.ApplicationArgs = [][]byte{{byte(transactions.ClearStateOC)}}
	eval = nextBlock(t, l)
	txn(t, l, eval, &call)
	endBlock(t, l, eval)

	// Clearstate took effect, despite failure from infinite loop
	outerAcct = lookup(t, l, outerID.Address())
	require.Empty(t, outerAcct.AppLocalStates)
}

// TestInnerClearStateBadCaller ensures that inner clear state programs cannot
// be called with less than 700 (MaxAppProgramCost)) OpcodeBudget.
func TestInnerClearStateBadCaller(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	l := newTestLedger(t, genBalances)
	defer l.Close()

	inner := txntest.Txn{
		Type:            "appl",
		Sender:          addrs[0],
		ApprovalProgram: "int 1",
		ClearStateProgram: `global OpcodeBudget
itob
log
int 1`,
		LocalStateSchema: basics.StateSchema{
			NumUint:      1,
			NumByteSlice: 2,
		},
	}

	// waster allows tries to get the budget down below 100 before returning
	waster := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
global OpcodeBudget
itob
log
top:
global OpcodeBudget
int 100
<
bnz done
 byte "junk"
 sha256
 pop
 b top
done:
global OpcodeBudget
itob
log
`),
		LocalStateSchema: basics.StateSchema{
			NumUint:      3,
			NumByteSlice: 4,
		},
	}

	eval := nextBlock(t, l)
	txns(t, l, eval, &inner, &waster)
	vb := endBlock(t, l, eval)
	innerID := vb.Block().Payset[0].ApplicationID
	wasterID := vb.Block().Payset[1].ApplicationID

	// Grouper is a simple app that will invoke the given apps (in
	// ForeignApps[0,1]) as a group, with the given OnCompletion (in
	// ApplicationArgs[0]).
	grouper := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
itxn_begin
 int appl
 itxn_field TypeEnum
 txn Applications 1
 itxn_field ApplicationID
 txn ApplicationArgs 0
 btoi
 itxn_field OnCompletion
itxn_next
 int appl
 itxn_field TypeEnum
 txn Applications 2
 itxn_field ApplicationID
 txn ApplicationArgs 1
 btoi
 itxn_field OnCompletion
itxn_submit
`),
	}

	eval = nextBlock(t, l)
	txn(t, l, eval, &grouper)
	vb = endBlock(t, l, eval)
	grouperID := vb.Block().Payset[0].ApplicationID

	fund := txntest.Txn{
		Type:     "pay",
		Sender:   addrs[0],
		Receiver: grouperID.Address(),
		Amount:   1_000_000,
	}

	call := txntest.Txn{
		Type:            "appl",
		Sender:          addrs[0],
		ApplicationID:   grouperID,
		ApplicationArgs: [][]byte{{byte(transactions.OptInOC)}, {byte(transactions.OptInOC)}},
		ForeignApps:     []basics.AppIndex{wasterID, innerID},
	}
	eval = nextBlock(t, l)
	txns(t, l, eval, &fund, &call)
	endBlock(t, l, eval)

	gAcct := lookup(t, l, grouperID.Address())
	require.Len(t, gAcct.AppLocalStates, 2)

	call.ApplicationArgs = [][]byte{{byte(transactions.CloseOutOC)}, {byte(transactions.ClearStateOC)}}
	eval = nextBlock(t, l)
	txn(t, l, eval, &call, "ClearState execution with low OpcodeBudget")
	vb = endBlock(t, l, eval)
	require.Len(t, vb.Block().Payset, 0)

	// Clearstate did not take effect, since the caller tried to shortchange the CSP
	gAcct = lookup(t, l, grouperID.Address())
	require.Len(t, gAcct.AppLocalStates, 2)
}

// TestClearStateInnerPay ensures that ClearState programs can run inner txns in
// v30, but not in vFuture. (Test should add v31 after it exists.)
func TestClearStateInnerPay(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	tests := []struct {
		consensus protocol.ConsensusVersion
		approval  string
	}{
		{protocol.ConsensusFuture, "int 1"},
		{protocol.ConsensusV30, "int 1"},
		{protocol.ConsensusFuture, "int 0"},
		{protocol.ConsensusV30, "int 0"},
	}

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

			genBalances, addrs, _ := ledgertesting.NewTestGenesis()
			cfg := config.GetDefaultLocal()
			l := newSimpleLedgerWithConsensusVersion(t, genBalances, test.consensus, cfg)
			defer l.Close()

			app0 := txntest.Txn{
				Type:   "appl",
				Sender: addrs[0],
				ApprovalProgram: main(`
itxn_begin
	int pay
	itxn_field TypeEnum
	int 3000
	itxn_field Amount
    txn Sender
    itxn_field Receiver
itxn_submit`),
				ClearStateProgram: `
itxn_begin
	int pay
	itxn_field TypeEnum
	int 2000
	itxn_field Amount
    txn Sender
    itxn_field Receiver
itxn_submit
` + test.approval,
			}
			eval := nextBlock(t, l)
			txn(t, l, eval, &app0)
			vb := endBlock(t, l, eval)
			id0 := vb.Block().Payset[0].ApplicationID

			fund0 := txntest.Txn{
				Type:     "pay",
				Sender:   addrs[0],
				Receiver: id0.Address(),
				Amount:   1_000_000,
			}

			optin := txntest.Txn{
				Type:          "appl",
				Sender:        addrs[1],
				ApplicationID: id0,
				OnCompletion:  transactions.OptInOC,
			}

			eval = nextBlock(t, l)
			txns(t, l, eval, &fund0, &optin)
			vb = endBlock(t, l, eval)

			// Check that addrs[1] got paid during optin, and pay txn is in block
			ad1 := micros(t, l, addrs[1])

			// paid 3000, but 1000 fee, 2000 bump
			require.Equal(t, uint64(2000), ad1-genBalances.Balances[addrs[1]].MicroAlgos.Raw)
			// InnerTxn in block ([1] position, because followed fund0)
			require.Len(t, vb.Block().Payset[1].EvalDelta.InnerTxns, 1)
			require.Equal(t, vb.Block().Payset[1].EvalDelta.InnerTxns[0].Txn.Amount.Raw, uint64(3000))

			clear := txntest.Txn{
				Type:          "appl",
				Sender:        addrs[1],
				ApplicationID: id0,
				OnCompletion:  transactions.ClearStateOC,
			}

			eval = nextBlock(t, l)
			txns(t, l, eval, &clear)
			vb = endBlock(t, l, eval)

			// Check if addrs[1] got paid during clear, and pay txn is in block
			ad1 = micros(t, l, addrs[1])

			// The pay only happens if the clear state approves (and it was legal back in V30)
			if test.approval == "int 1" && test.consensus == protocol.ConsensusV30 {
				// had 2000 bump, now paid 2k, charge 1k, left with 3k total bump
				require.Equal(t, uint64(3000), ad1-genBalances.Balances[addrs[1]].MicroAlgos.Raw)
				// InnerTxn in block
				require.Equal(t, vb.Block().Payset[0].Txn.ApplicationID, id0)
				require.Equal(t, vb.Block().Payset[0].Txn.OnCompletion, transactions.ClearStateOC)
				require.Len(t, vb.Block().Payset[0].EvalDelta.InnerTxns, 1)
				require.Equal(t, vb.Block().Payset[0].EvalDelta.InnerTxns[0].Txn.Amount.Raw, uint64(2000))
			} else {
				// Only the fee is paid because pay is "erased", so goes from 2k down to 1k
				require.Equal(t, uint64(1000), ad1-genBalances.Balances[addrs[1]].MicroAlgos.Raw)
				// no InnerTxn in block
				require.Equal(t, vb.Block().Payset[0].Txn.ApplicationID, id0)
				require.Equal(t, vb.Block().Payset[0].Txn.OnCompletion, transactions.ClearStateOC)
				require.Len(t, vb.Block().Payset[0].EvalDelta.InnerTxns, 0)
			}
		})
	}
}

// TestGlobalChangesAcrossApps ensures that state changes are seen by other app
// calls when using inners.
func TestGlobalChangesAcrossApps(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	l := newTestLedger(t, genBalances)
	defer l.Close()

	appA := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
            // Call B : No arguments means: set your global "X" to "ABC"
			itxn_begin
			int appl;               itxn_field TypeEnum
			txn Applications 1;     itxn_field ApplicationID
			itxn_submit

            // Call C : Checks that B's global X is ABC
			itxn_begin
			int appl;               itxn_field TypeEnum
			txn Applications 2;     itxn_field ApplicationID
            txn Applications 1;     itxn_field Applications // Pass on access to B
			itxn_submit

            // Call B again:  1 arg means it checks if X == ABC
			itxn_begin
			int appl;               itxn_field TypeEnum
			txn Applications 1;     itxn_field ApplicationID
            byte "check, please";   itxn_field ApplicationArgs
			itxn_submit

            // Check B's state for X
            txn Applications 1
            byte "X"
            app_global_get_ex
            assert
            byte "ABC"
            ==
            assert
`),
	}

	appB := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  txn NumAppArgs
  bnz check						// 1 arg means check
  // set
  byte "X"
  byte "ABC"
  app_global_put
  b end
check:
  byte "X"
  app_global_get
  byte "ABC"
  ==
  assert
  b end
`),
		GlobalStateSchema: basics.StateSchema{
			NumByteSlice: 1,
		},
	}

	appC := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  txn Applications 1
  byte "X"
  app_global_get_ex
  assert
  byte "ABC"
  ==
  assert
`),
	}

	eval := nextBlock(t, l)
	txns(t, l, eval, &appA, &appB, &appC)
	vb := endBlock(t, l, eval)
	idA := vb.Block().Payset[0].ApplicationID
	idB := vb.Block().Payset[1].ApplicationID
	idC := vb.Block().Payset[2].ApplicationID

	fundA := txntest.Txn{
		Type:     "pay",
		Sender:   addrs[0],
		Receiver: idA.Address(),
		Amount:   1_000_000,
	}

	callA := txntest.Txn{
		Type:          "appl",
		Sender:        addrs[0],
		ApplicationID: idA,
		ForeignApps:   []basics.AppIndex{idB, idC},
	}

	eval = nextBlock(t, l)
	txns(t, l, eval, &fundA, &callA)
	endBlock(t, l, eval)
}

// TestLocalChangesAcrossApps ensures that state changes are seen by other app
// calls when using inners.
func TestLocalChangesAcrossApps(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	l := newTestLedger(t, genBalances)
	defer l.Close()

	appA := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
            // Call B : No arguments means: set caller's local "X" to "ABC"
			itxn_begin
			int appl;               itxn_field TypeEnum
			txn Applications 1;     itxn_field ApplicationID
            int OptIn;              itxn_field OnCompletion
			itxn_submit

            // Call C : Checks that caller's local X for app B is ABC
			itxn_begin
			int appl;               itxn_field TypeEnum
			txn Applications 2;     itxn_field ApplicationID
            txn Applications 1;     itxn_field Applications // Pass on access to B
			itxn_submit

            // Call B again:  1 arg means it checks if caller's local X == ABC
			itxn_begin
			int appl;               itxn_field TypeEnum
			txn Applications 1;     itxn_field ApplicationID
            byte "check, please";   itxn_field ApplicationArgs
			itxn_submit

            // Check self local state for B
            global CurrentApplicationAddress
            txn Applications 1
            byte "X"
            app_local_get_ex
            assert
            byte "ABC"
            ==
            assert
`),
	}

	appB := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  txn NumAppArgs
  bnz check						// 1 arg means check
  // set
  txn Sender
  byte "X"
  byte "ABC"
  app_local_put
  b end
check:
  txn Sender
  byte "X"
  app_local_get
  byte "ABC"
  ==
  assert
  b end
`),
		LocalStateSchema: basics.StateSchema{
			NumByteSlice: 1,
		},
	}

	appC := txntest.Txn{
		Type:   "appl",
		Sender: addrs[0],
		ApprovalProgram: main(`
  txn Sender
  txn Applications 1
  byte "X"
  app_local_get_ex
  assert
  byte "ABC"
  ==
  assert
`),
	}

	eval := nextBlock(t, l)
	txns(t, l, eval, &appA, &appB, &appC)
	vb := endBlock(t, l, eval)
	idA := vb.Block().Payset[0].ApplicationID
	idB := vb.Block().Payset[1].ApplicationID
	idC := vb.Block().Payset[2].ApplicationID

	fundA := txntest.Txn{
		Type:     "pay",
		Sender:   addrs[0],
		Receiver: idA.Address(),
		Amount:   1_000_000,
	}

	callA := txntest.Txn{
		Type:          "appl",
		Sender:        addrs[0],
		ApplicationID: idA,
		ForeignApps:   []basics.AppIndex{idB, idC},
	}

	eval = nextBlock(t, l)
	txns(t, l, eval, &fundA, &callA)
	endBlock(t, l, eval)
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	ledgertesting.TestConsensusRange(t, 32, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		appA := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
		}

		appB := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: main(`
itxn_begin
	int pay;                itxn_field TypeEnum
	int 100;     		    itxn_field Amount
	txn Applications 1
	app_params_get AppAddress
	assert
	itxn_field Receiver
itxn_submit
`),
		}

		payset := dl.txns(&appA, &appB)
		id0 := payset[0].ApplicationID
		id1 := payset[1].ApplicationID

		fund1 := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: id1.Address(),
			Amount:   1_000_000_000,
		}
		fund0 := fund1
		fund0.Receiver = id0.Address()

		callTx := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[2],
			ApplicationID: id1,
			ForeignApps:   []basics.AppIndex{id0},
		}

		if ver <= 33 {
			dl.txgroup("unavailable Account", &fund0, &fund1, &callTx)
			return
		}
		payset = dl.txgroup("", &fund0, &fund1, &callTx)
		require.Equal(t, id0.Address(), payset[2].EvalDelta.InnerTxns[0].Txn.Receiver)
		require.Equal(t, uint64(100), payset[2].EvalDelta.InnerTxns[0].Txn.Amount.Raw)
	})
}

// While accounts of foreign apps are available in most contexts, they still
// cannot be used as mutable references; ie the accounts cannot be used by
// opcodes that modify local storage.
func TestForeignAppAccountsImmutable(t *testing.T) {
	partitiontest.PartitionTest(t)

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	ledgertesting.TestConsensusRange(t, 32, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		appA := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: main(`
itxn_begin
int appl;               itxn_field TypeEnum
txn Applications 1;     itxn_field ApplicationID
int OptIn;              itxn_field OnCompletion
itxn_submit
`),
		}

		appB := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: main(`
txn NumApplications				// allow "bare" optin
bz end
txn Applications 1
app_params_get AppAddress
assert
byte "X"
byte "ABC"
app_local_put
`),
			LocalStateSchema: basics.StateSchema{NumByteSlice: 1},
		}

		payset := dl.txns(&appA, &appB)
		id0 := payset[0].ApplicationID
		id1 := payset[1].ApplicationID

		fund1 := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: id1.Address(),
			Amount:   1_000_000_000,
		}
		fund0 := fund1
		fund0.Receiver = id0.Address()

		optin := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[2],
			ApplicationID: id0,
			ForeignApps:   []basics.AppIndex{id1},
		}

		callTx := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[2],
			ApplicationID: id1,
			ForeignApps:   []basics.AppIndex{id0},
		}

		var problem string
		switch {
		case ver < 34: // before v7, app accounts not available at all
			problem = "invalid Account reference " + id0.Address().String()
		case ver < 38: // as of v7, it's the mutation that's the problem
			problem = "invalid Account reference for mutation"
		}
		dl.txgroup(problem, &fund0, &fund1, &optin, &callTx)
	})
}

// In the case where the foreign app account is also provided in the
// transaction's account field, mutable references should be allowed.
func TestForeignAppAccountsMutable(t *testing.T) {
	partitiontest.PartitionTest(t)

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	ledgertesting.TestConsensusRange(t, 32, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		appA := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: main(`
itxn_begin
	int appl
	itxn_field TypeEnum
	txn Applications 1
	itxn_field ApplicationID
	int OptIn
	itxn_field OnCompletion
itxn_submit
`),
		}

		appB := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: main(`
txn OnCompletion
int OptIn
==
bnz done
txn Applications 1
app_params_get AppAddress
assert
byte "X"
byte "Y"
app_local_put
done:
`),
			LocalStateSchema: basics.StateSchema{
				NumByteSlice: 1,
			},
		}

		payset := dl.txns(&appA, &appB)
		id0 := payset[0].ApplicationID
		id1 := payset[1].ApplicationID

		fund1 := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: id1.Address(),
			Amount:   1_000_000_000,
		}
		fund0 := fund1
		fund0.Receiver = id0.Address()
		fund1.Receiver = id1.Address()

		callA := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[2],
			ApplicationID: id0,
			ForeignApps:   []basics.AppIndex{id1},
		}

		callB := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[2],
			ApplicationID: id1,
			ForeignApps:   []basics.AppIndex{id0},
			Accounts:      []basics.Address{id0.Address()},
		}

		payset = dl.txns(&fund0, &fund1, &callA, &callB)
		require.Equal(t, "Y", payset[3].EvalDelta.LocalDeltas[1]["X"].Bytes)
	})
}

// TestReloadWithTxns confirms that the ledger can be reloaded from "disk" when
// doing so requires replaying some interesting AVM txns.
func TestReloadWithTxns(t *testing.T) {
	partitiontest.PartitionTest(t)

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	ledgertesting.TestConsensusRange(t, 34, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		dl.fullBlock() // So that the `block` opcode has a block to inspect

		lookHdr := txntest.Txn{
			Type:            "appl",
			Sender:          addrs[0],
			ApprovalProgram: "txn FirstValid;  int 1;  -;  block BlkTimestamp",
		}

		dl.fullBlock(&lookHdr)

		dl.reloadLedgers()
	})
}

// TestEvalAppState ensures txns in a group can't violate app state schema
// limits. It ensures that commitToParent -> applyChild copies child's cow state
// usage counts into parent and the usage counts are correctly propagated from
// parent cow to child cow and back. When limits are not violated, the test
// ensures that the updates are correct.
func TestEvalAppState(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// v24 = apps
	ledgertesting.TestConsensusRange(t, 24, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		appID := basics.AppIndex(1)
		if ver >= 38 { // AppForbidLowResources
			appID += 1000
		}
		appcall1 := txntest.Txn{
			Type:              protocol.ApplicationCallTx,
			Sender:            addrs[0],
			GlobalStateSchema: basics.StateSchema{NumByteSlice: 1},
			ApprovalProgram: `#pragma version 2
	txn ApplicationID
	bz create
	byte "caller"
	txn Sender
	app_global_put
	b ok
create:
	byte "creator"
	txn Sender
	app_global_put
ok:
	int 1`,
			ClearStateProgram: "#pragma version 2\nint 1",
		}

		appcall2 := txntest.Txn{
			Type:          protocol.ApplicationCallTx,
			Sender:        addrs[0],
			ApplicationID: appID,
		}

		dl.beginBlock()
		dl.txgroup("store bytes count 2 exceeds schema bytes count 1", &appcall1, &appcall2)

		appcall1.GlobalStateSchema = basics.StateSchema{NumByteSlice: 2}
		dl.txgroup("", &appcall1, &appcall2)
		vb := dl.endBlock()
		deltas := vb.Delta()

		params, _ := deltas.Accts.GetAppParams(addrs[0], appID)
		require.Equal(t, basics.TealKeyValue{
			"caller":  {Type: basics.TealBytesType, Bytes: string(addrs[0][:])},
			"creator": {Type: basics.TealBytesType, Bytes: string(addrs[0][:])},
		}, params.Params.GlobalState)
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// v24 = apps
	ledgertesting.TestConsensusRange(t, 24, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		createTxn := txntest.Txn{
			Type:              "appl",
			Sender:            addrs[0],
			ApprovalProgram:   "int 1",
			ClearStateProgram: []byte{},
		}

		dl.txn(&createTxn, "invalid program (empty)")

		createTxn.ClearStateProgram = []byte{0xfe} // bad uvarint
		dl.txn(&createTxn, "invalid version")
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// v15 put rewards into ApplyData
	ledgertesting.TestConsensusRange(t, 11, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		payTxn := txntest.Txn{Type: protocol.PaymentTx, Sender: addrs[0], Receiver: addrs[1]}
		nonpartTxn := txntest.Txn{Type: protocol.KeyRegistrationTx, Sender: addrs[2], Nonparticipation: true}
		payNonPart := txntest.Txn{Type: protocol.PaymentTx, Sender: addrs[0], Receiver: addrs[2]}

		if ver < 18 { // Nonpart reyreg happens in v18
			dl.txn(&nonpartTxn, "tries to mark an account as nonparticipating")
		} else {
			dl.fullBlock(&nonpartTxn)
		}

		// Build up Residue in RewardsState so it's ready to pay
		for i := 1; i < 10; i++ {
			dl.fullBlock()
		}

		payset := dl.txns(&payTxn, &payNonPart)
		payInBlock := payset[0]
		nonPartInBlock := payset[1]
		if ver >= 15 {
			require.Greater(t, payInBlock.ApplyData.SenderRewards.Raw, uint64(1000))
			require.Greater(t, payInBlock.ApplyData.ReceiverRewards.Raw, uint64(1000))
			require.Equal(t, payInBlock.ApplyData.SenderRewards, payInBlock.ApplyData.ReceiverRewards)
			// Sender is not due for more, and Receiver is nonpart
			require.Zero(t, nonPartInBlock.ApplyData.SenderRewards)
			if ver < 18 {
				require.Greater(t, nonPartInBlock.ApplyData.ReceiverRewards.Raw, uint64(1000))
			} else {
				require.Zero(t, nonPartInBlock.ApplyData.ReceiverRewards)
			}
		} else {
			require.Zero(t, payInBlock.ApplyData.SenderRewards)
			require.Zero(t, payInBlock.ApplyData.ReceiverRewards)
			require.Zero(t, nonPartInBlock.ApplyData.SenderRewards)
			require.Zero(t, nonPartInBlock.ApplyData.ReceiverRewards)
		}
	})
}

// TestDeleteNonExistentKeys checks if the EvalDeltas from deleting missing keys are correct
func TestDeleteNonExistentKeys(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// AVM v4 start, so we can use `txn Sender`
	ledgertesting.TestConsensusRange(t, 28, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		createTxn := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: main(`
byte "missing_global"
app_global_del
txn Sender
byte "missing_local"
app_local_del
`),
		}

		appID := dl.txn(&createTxn).ApplyData.ApplicationID

		optInTxn := txntest.Txn{
			Type:          "appl",
			Sender:        addrs[1],
			ApplicationID: appID,
			OnCompletion:  transactions.OptInOC,
		}

		tib := dl.txn(&optInTxn)
		require.Len(t, tib.EvalDelta.GlobalDelta, 0)
		// For a while, we encoded an empty localdelta
		deltas := 1
		if ver >= 27 {
			deltas = 0
		}
		require.Len(t, tib.EvalDelta.LocalDeltas, deltas)
	})
}

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

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	ledgertesting.TestConsensusRange(t, 11, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		pay := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: addrs[1],
			Amount:   10,
		}
		dl.txn(&pay)
		dl.txn(&pay, "transaction already in ledger")

		// Test same transaction in a later block
		dl.txn(&pay, "transaction already in ledger")

		// Change the note so it can go in again
		pay.Note = []byte("1")
		dl.txn(&pay)

		// Change note again, but try the txn twice in same group
		if dl.generator.GenesisProto().MaxTxGroupSize > 1 {
			pay.Note = []byte("2")
			dl.txgroup("transaction already in ledger", &pay, &pay)
		}
	})
}

// TestHeaderAccess tests FirstValidTime and `block` which can access previous
// block headers.
func TestHeaderAccess(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// Added in v34
	ledgertesting.TestConsensusRange(t, 34, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		fvt := txntest.Txn{
			Type:            "appl",
			Sender:          addrs[0],
			FirstValid:      0,
			ApprovalProgram: "txn FirstValidTime",
		}
		dl.txn(&fvt, "round 0 is not available")

		// advance current to 2
		pay := txntest.Txn{Type: "pay", Sender: addrs[0], Receiver: addrs[0]}
		dl.fullBlock(&pay)

		fvt.FirstValid = 1
		dl.txn(&fvt, "round 0 is not available")

		fvt.FirstValid = 2
		dl.txn(&fvt) // current becomes 3

		// Advance current round far enough to test access MaxTxnLife ago
		for i := 0; i < int(config.Consensus[cv].MaxTxnLife); i++ {
			dl.fullBlock()
		}

		// current should be 1003. Confirm.
		require.EqualValues(t, 1002, dl.generator.Latest())
		require.EqualValues(t, 1002, dl.validator.Latest())

		fvt.FirstValid = 1003
		fvt.LastValid = 1010
		dl.txn(&fvt) // success advances the round
		// now we're confident current is 1004, so construct a txn that is as
		// old as possible, and confirm access.
		fvt.FirstValid = 1004 - basics.Round(config.Consensus[cv].MaxTxnLife)
		fvt.LastValid = 1004
		dl.txn(&fvt)
	})

}

// TestLogsInBlock ensures that logs appear in the block properly
func TestLogsInBlock(t *testing.T) {
	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	// Run tests from v30 onward
	ledgertesting.TestConsensusRange(t, 30, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		createTxn := txntest.Txn{
			Type:            "appl",
			Sender:          addrs[0],
			ApprovalProgram: "byte \"APP\"\n log\n int 1",
			// Fail the clear state
			ClearStateProgram: "byte \"CLR\"\n log\n int 0",
		}
		createInBlock := dl.txn(&createTxn)
		appID := createInBlock.ApplyData.ApplicationID
		require.Equal(t, "APP", createInBlock.ApplyData.EvalDelta.Logs[0])

		optInTxn := txntest.Txn{
			Type:          protocol.ApplicationCallTx,
			Sender:        addrs[1],
			ApplicationID: appID,
			OnCompletion:  transactions.OptInOC,
		}
		optInInBlock := dl.txn(&optInTxn)
		require.Equal(t, "APP", optInInBlock.ApplyData.EvalDelta.Logs[0])

		clearTxn := txntest.Txn{
			Type:          protocol.ApplicationCallTx,
			Sender:        addrs[1],
			ApplicationID: appID,
			OnCompletion:  transactions.ClearStateOC,
		}
		clearInBlock := dl.txn(&clearTxn)
		// Logs do not appear if the ClearState failed
		require.Len(t, clearInBlock.ApplyData.EvalDelta.Logs, 0)
	})
}

// TestUnfundedSenders confirms that accounts that don't even exist
// can be the Sender in some situations.  If some other transaction
// covers the fee, and the transaction itself does not require an
// asset or a min balance, it's fine.
func TestUnfundedSenders(t *testing.T) {
	/*
		In a 0-fee transaction from unfunded sender, we still call balances.Move
		to “pay” the fee.  Move() does not short-circuit a Move of 0 (for good
		reason, it allows compounding rewards).  Therefore, in Move, we do
		rewards processing on the unfunded account.  Before
		proto.UnfundedSenders, the rewards procesing would set the RewardsBase,
		which would require the account be written to DB, and therefore the MBR
		check would kick in (and fail). Now it skips the update if the account
		has less than RewardsUnit, as the update is meaningless anyway.
	*/

	partitiontest.PartitionTest(t)
	t.Parallel()

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()

	ledgertesting.TestConsensusRange(t, 24, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		ghost := basics.Address{0x01}

		asaCreate := txntest.Txn{
			Type:   "acfg",
			Sender: addrs[0],
			AssetParams: basics.AssetParams{
				Total:    10,
				Clawback: ghost,
				Freeze:   ghost,
				Manager:  ghost,
			},
		}

		appCreate := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
		}

		payset := dl.txns(&asaCreate, &appCreate)
		asaID := payset[0].ApplyData.ConfigAsset
		// we are testing some versions before ApplyData.ConfigAsset was
		// populated. At that time, initial ID was 1, so we can hardcode.
		if asaID == 0 {
			asaID = 1
		}
		appID := payset[1].ApplyData.ApplicationID
		if appID == 0 {
			appID = 2
		}

		// Advance so that rewardsLevel increases
		for i := 1; i < 10; i++ {
			dl.fullBlock()
		}

		benefactor := txntest.Txn{
			Type:     "pay",
			Sender:   addrs[0],
			Receiver: addrs[0],
			Fee:      2000,
		}

		ephemeral := []txntest.Txn{
			{
				Type:     "pay",
				Amount:   0,
				Sender:   ghost,
				Receiver: ghost,
				Fee:      0,
			},
			{ // Axfer of 0
				Type:          "axfer",
				AssetAmount:   0,
				Sender:        ghost,
				AssetReceiver: basics.Address{0x02},
				XferAsset:     basics.AssetIndex(1),
				Fee:           0,
			},
			{ // Clawback
				Type:          "axfer",
				AssetAmount:   0,
				Sender:        ghost,
				AssetReceiver: addrs[0],
				AssetSender:   addrs[1],
				XferAsset:     asaID,
				Fee:           0,
			},
			{ // Freeze
				Type:          "afrz",
				Sender:        ghost,
				FreezeAccount: addrs[0], // creator, therefore is opted in
				FreezeAsset:   asaID,
				AssetFrozen:   true,
				Fee:           0,
			},
			{ // Unfreeze
				Type:          "afrz",
				Sender:        ghost,
				FreezeAccount: addrs[0], // creator, therefore is opted in
				FreezeAsset:   asaID,
				AssetFrozen:   false,
				Fee:           0,
			},
			{ // App call
				Type:          "appl",
				Sender:        ghost,
				ApplicationID: appID,
				Fee:           0,
			},
			{ // App creation (only works because it's also deleted)
				Type:         "appl",
				Sender:       ghost,
				OnCompletion: transactions.DeleteApplicationOC,
				Fee:          0,
			},
		}

		// v34 enabled UnfundedSenders
		var problem string
		if ver < 34 {
			// In the old days, balances.Move would try to increase the rewardsState on the unfunded account
			problem = "balance 0 below min"
		}
		for i, e := range ephemeral {
			dl.txgroup(problem, benefactor.Noted(strconv.Itoa(i)), &e)
		}
	})
}

// TestAppCallAppDuringInit is similar to TestUnfundedSenders test, but now the
// unfunded sender is a newly created app.  The fee has been paid by the outer
// transaction, so the app should be able to make an app call as that requires
// no min balance.
func TestAppCallAppDuringInit(t *testing.T) {
	partitiontest.PartitionTest(t)

	genBalances, addrs, _ := ledgertesting.NewTestGenesis()
	ledgertesting.TestConsensusRange(t, 31, 0, func(t *testing.T, ver int, cv protocol.ConsensusVersion, cfg config.Local) {
		dl := NewDoubleLedger(t, genBalances, cv, cfg)
		defer dl.Close()

		approve := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
		}

		// construct a simple approval app
		approveID := dl.txn(&approve).ApplicationID

		// Advance so that rewardsLevel increases
		for i := 1; i < 10; i++ {
			dl.fullBlock()
		}

		// now make a new app that calls it during init
		callInInit := txntest.Txn{
			Type:   "appl",
			Sender: addrs[0],
			ApprovalProgram: `
			  itxn_begin
			  int appl
			  itxn_field TypeEnum
			  txn Applications 1
			  itxn_field ApplicationID
			  itxn_submit
              int 1
            `,
			ForeignApps: []basics.AppIndex{approveID},
			Fee:         2000, // Enough to have the inner fee paid for
		}
		// v34 is the likely version for UnfundedSenders. Change if that doesn't happen.
		var problem string
		if ver < 34 {
			// In the old days, balances.Move would try to increase the rewardsState on the unfunded account
			problem = "balance 0 below min"
		}
		dl.txn(&callInInit, problem)
	})
}