miden-testing 0.17.0

Miden protocol testing tools
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use std::collections::BTreeMap;

use anyhow::Context;
use assert_matches::assert_matches;
use miden_crypto::rand::{FeltRng, RandomCoin};
use miden_processor::{ExecutionError, Word};
use miden_protocol::Hasher;
use miden_protocol::account::auth::AuthScheme;
use miden_protocol::account::component::AccountComponentMetadata;
use miden_protocol::account::{
    Account,
    AccountBuilder,
    AccountCode,
    AccountCodeUpgrade,
    AccountComponent,
    AccountId,
    AccountProcedureRoot,
    AccountStorage,
    AccountType,
    StorageMap,
    StorageMapKey,
    StorageMapPatch,
    StorageSlot,
    StorageSlotContent,
    StorageSlotId,
    StorageSlotName,
    StorageSlotPatch,
    StorageSlotType,
    StorageValuePatch,
};
use miden_protocol::assembly::diagnostics::reporting::PrintDiagnostic;
use miden_protocol::assembly::{DefaultSourceManager, Linkage, ModuleKind, ModuleParser, Path};
use miden_protocol::asset::{Asset, AssetId, FungibleAsset};
use miden_protocol::errors::MasmError;
use miden_protocol::errors::tx_kernel::{
    ERR_ACCOUNT_AUTH_PROCEDURE_MUST_NOT_BE_DUPLICATED,
    ERR_ACCOUNT_CODE_COMMITMENT_MISMATCH,
    ERR_ACCOUNT_ID_SUFFIX_LEAST_SIGNIFICANT_BYTE_MUST_BE_ZERO,
    ERR_ACCOUNT_ID_SUFFIX_MOST_SIGNIFICANT_BIT_MUST_BE_ZERO,
    ERR_ACCOUNT_ID_UNKNOWN_VERSION,
    ERR_ACCOUNT_NONCE_AT_MAX,
    ERR_ACCOUNT_NONCE_CAN_ONLY_BE_INCREMENTED_ONCE,
    ERR_ACCOUNT_NOT_ENOUGH_PROCEDURES,
    ERR_ACCOUNT_PATCH_NONCE_MUST_BE_INCREMENTED_IF_STATE_CHANGED,
    ERR_ACCOUNT_PROCEDURES_MUST_BE_SORTED_AND_UNIQUE,
    ERR_ACCOUNT_STORAGE_SLOT_TYPE_IS_INVALID,
    ERR_ACCOUNT_UNKNOWN_STORAGE_SLOT_NAME,
    ERR_ACCOUNT_UPGRADE_CODE_ALREADY_SET,
    ERR_ACCOUNT_UPGRADE_NOT_ALLOWED_FOR_NEW_ACCOUNT,
    ERR_ACCOUNT_UPGRADE_STORAGE_UPGRADES_UNSUPPORTED,
};
use miden_protocol::field::PrimeField64;
use miden_protocol::note::NoteType;
use miden_protocol::testing::account_id::{
    ACCOUNT_ID_PRIVATE_NON_FUNGIBLE_FAUCET,
    ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET,
    ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1,
    ACCOUNT_ID_REGULAR_PRIVATE_ACCOUNT_UPDATABLE_CODE,
    ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE,
    ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_UPDATABLE_CODE,
    ACCOUNT_ID_SENDER,
};
use miden_protocol::testing::add_component::AddComponent;
use miden_protocol::testing::storage::{MOCK_MAP_SLOT, MOCK_VALUE_SLOT0, MOCK_VALUE_SLOT1};
use miden_protocol::transaction::memory::{
    CODE_UPGRADE_COMMITMENT_PTR,
    STORAGE_UPGRADE_COMMITMENT_PTR,
};
use miden_protocol::transaction::{RawOutputNote, TransactionKernel, TransactionScript};
use miden_protocol::utils::sync::LazyLock;
use miden_protocol::vm::Package;
use miden_standards::code_builder::CodeBuilder;
use miden_standards::testing::account_component::{IncrNonceAuthComponent, MockAccountComponent};
use miden_standards::testing::mock_account::MockAccountExt;
use miden_tx::{LocalTransactionProver, TransactionKernelError};
use rand::random;

use super::{Felt, StackInputs, ZERO};
use crate::executor::CodeExecutor;
use crate::kernel_tests::tx::ExecutionOutputExt;
use crate::utils::create_public_p2any_note;
use crate::{
    Auth,
    ExecError,
    MockChain,
    TestTransactionBuilder,
    assert_execution_error,
    assert_transaction_executor_error,
};

// ACCOUNT COMMITMENT TESTS
// ================================================================================================

#[tokio::test]
pub async fn compute_commitment() -> anyhow::Result<()> {
    let account = Account::mock(ACCOUNT_ID_REGULAR_PRIVATE_ACCOUNT_UPDATABLE_CODE, Auth::IncrNonce);

    // Precompute a commitment to a changed account so we can assert it during tx script execution.
    let mut account_clone = account.clone();
    let key = StorageMapKey::from_array([1, 2, 3, 4]);
    let value = Word::from([2, 3, 4, 5u32]);
    let mock_map_slot = &*MOCK_MAP_SLOT;
    account_clone.storage_mut().set_map_item(mock_map_slot, key, value).unwrap();
    let expected_commitment = account_clone.to_commitment();

    let tx_script = format!(
        r#"
        use miden::core::word

        use mock::account as mock_account

        const MOCK_MAP_SLOT = word("{mock_map_slot}")

        @transaction_script
        pub proc main
            call.mock_account::get_initial_commitment
            # => [INITIAL_COMMITMENT, pad(12)]
            swapdw dropw dropw swapw dropw
            # => [INITIAL_COMMITMENT]

            call.mock_account::compute_commitment
            # => [CURRENT_COMMITMENT, INITIAL_COMMITMENT, pad(8)]
            swapdw dropw dropw
            # => [CURRENT_COMMITMENT, INITIAL_COMMITMENT]

            assert_eqw.err="initial and current commitment should be equal when no changes have been made"
            # => []

            call.mock_account::compute_storage_commitment
            # => [STORAGE_COMMITMENT0, pad(12)]
            swapdw dropw dropw swapw dropw
            # => [STORAGE_COMMITMENT0]

            # update a value in the storage map
            padw push.0.0.0
            push.{value}
            push.{key}
            push.MOCK_MAP_SLOT[0..2]
            # => [slot_id_suffix, slot_id_prefix, KEY, VALUE, pad(7)]
            call.mock_account::set_map_item
            dropw dropw dropw dropw
            # => [STORAGE_COMMITMENT0]

            # compute the commitment which will recompute the storage commitment
            call.mock_account::compute_commitment
            # => [CURRENT_COMMITMENT, STORAGE_COMMITMENT0, pad(8)]
            swapdw dropw dropw
            # => [CURRENT_COMMITMENT, STORAGE_COMMITMENT0]

            push.{expected_commitment}
            assert_eqw.err="current commitment should match expected one"
            # => [STORAGE_COMMITMENT0]

            padw padw padw padw
            call.mock_account::compute_storage_commitment
            # => [STORAGE_COMMITMENT1, pad(12), STORAGE_COMMITMENT0]
            swapdw dropw dropw swapw dropw
            # => [STORAGE_COMMITMENT1, STORAGE_COMMITMENT0]

            # assert that the commitment has changed
            exec.word::eq
            assertz.err="storage commitment should have been updated by compute_commitment"
            # => []
        end
    "#,
        key = key,
        value = value,
        expected_commitment = expected_commitment,
    );

    let mock_tx_builder = TestTransactionBuilder::new(account);
    let tx_script = CodeBuilder::with_mock_packages().compile_tx_script(tx_script)?;
    let mock_tx = mock_tx_builder.tx_script(tx_script).build()?;

    mock_tx
        .execute()
        .await
        .map_err(|err| anyhow::anyhow!("failed to execute transaction: {err}"))?;

    Ok(())
}

/// State changes are visible before authentication increments the nonce, and reverting storage
/// restores the initial commitment.
#[tokio::test]
async fn has_state_changed() -> anyhow::Result<()> {
    let account = Account::mock(ACCOUNT_ID_REGULAR_PRIVATE_ACCOUNT_UPDATABLE_CODE, Auth::IncrNonce);
    let mock_map_slot = &*MOCK_MAP_SLOT;
    let key = StorageMapKey::from_array([1, 2, 3, 4]);
    let original_value = account.storage().get_map_item(mock_map_slot, key)?;
    let changed_value = Word::from([2, 3, 4, 5u32]);
    assert_ne!(original_value, changed_value);

    let tx_script = format!(
        r#"
        use mock::account as mock_account

        const MOCK_MAP_SLOT = word("{mock_map_slot}")

        @transaction_script
        pub proc main
            call.mock_account::has_state_changed
            assertz.err="the native account should initially be unchanged"
            dropw dropw dropw drop drop drop

            push.{changed_value} push.{key} push.MOCK_MAP_SLOT[0..2]
            call.mock_account::set_map_item
            dropw dropw dropw dropw

            call.mock_account::has_state_changed
            assert.err="storage changes should be detected before incrementing the nonce"
            dropw dropw dropw drop drop drop

            push.{original_value} push.{key} push.MOCK_MAP_SLOT[0..2]
            call.mock_account::set_map_item
            dropw dropw dropw dropw

            call.mock_account::has_state_changed
            assertz.err="restoring storage should restore the initial commitment"
            dropw dropw dropw drop drop drop
        end
        "#,
    );
    let tx_script = CodeBuilder::with_mock_packages().compile_tx_script(tx_script)?;

    TestTransactionBuilder::new(account)
        .tx_script(tx_script)
        .build()?
        .execute()
        .await?;

    Ok(())
}

/// Native-account commitment APIs still require an account procedure as their caller.
#[rstest::rstest]
#[case::compute_commitment("compute_commitment")]
#[case::has_state_changed("has_state_changed")]
#[tokio::test]
async fn native_account_commitment_from_tx_script_is_rejected(
    #[case] procedure: &str,
) -> anyhow::Result<()> {
    let tx_script = CodeBuilder::default().compile_tx_script(format!(
        r#"
        use miden::core::sys
        use miden::protocol::native_account

        @transaction_script
        pub proc main
            # keep this script's root distinct from the mock account's wrapper
            push.1 drop
            exec.native_account::{procedure}
            exec.sys::truncate_stack
        end
        "#,
    ))?;

    let result = TestTransactionBuilder::with_existing_mock_account()
        .tx_script(tx_script)
        .build()?
        .execute()
        .await;

    assert_transaction_executor_error!(
        result,
        matches ExecutionError::EventError { error: ref event_err, .. }
            if matches!(
                event_err.downcast_ref::<TransactionKernelError>(),
                Some(TransactionKernelError::UnknownAccountProcedure(_))
            )
    );

    Ok(())
}

// ACCOUNT ID TESTS
// ================================================================================================

/// Splits a raw account ID into its suffix and prefix felts.
fn account_id_felts(account_id: &u128) -> anyhow::Result<(Felt, Felt)> {
    let prefix = Felt::try_from((account_id / (1u128 << 64)) as u64)?;
    let suffix = Felt::try_from((account_id % (1u128 << 64)) as u64)?;
    Ok((prefix, suffix))
}

#[tokio::test]
async fn test_account_validate_id() -> anyhow::Result<()> {
    let test_cases = [
        (ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE, None),
        (ACCOUNT_ID_REGULAR_PRIVATE_ACCOUNT_UPDATABLE_CODE, None),
        (ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET, None),
        (ACCOUNT_ID_PRIVATE_NON_FUNGIBLE_FAUCET, None),
        (
            // The zero account ID should be invalid by construction.
            0,
            Some(ERR_ACCOUNT_ID_UNKNOWN_VERSION),
        ),
        (
            // Set version to another unsupported value (10).
            (ACCOUNT_ID_REGULAR_PRIVATE_ACCOUNT_UPDATABLE_CODE & !(0x0f << 64)) | (0x0a << 64),
            Some(ERR_ACCOUNT_ID_UNKNOWN_VERSION),
        ),
        (
            // Set most significant bit to `1`.
            ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET | (0x80 << 56),
            Some(ERR_ACCOUNT_ID_SUFFIX_MOST_SIGNIFICANT_BIT_MUST_BE_ZERO),
        ),
        (
            // Set lower 8 bits to a non-zero value (1).
            ACCOUNT_ID_PRIVATE_NON_FUNGIBLE_FAUCET | 1,
            Some(ERR_ACCOUNT_ID_SUFFIX_LEAST_SIGNIFICANT_BYTE_MUST_BE_ZERO),
        ),
    ];

    for (account_id, expected_error) in test_cases.iter() {
        // Manually split the account ID into prefix and suffix since we can't use AccountId methods
        // on invalid ids.
        let (prefix, suffix) = account_id_felts(account_id)?;

        let code = "
            use miden::tx_kernel_core::account

            begin
                exec.account::validate_id
            end
            ";

        let result = CodeExecutor::with_default_host()
            .stack_inputs(StackInputs::new(&[suffix, prefix]).unwrap())
            .run(code)
            .await;

        match (result.map_err(ExecError::into_execution_error), expected_error) {
            (Ok(_), None) => (),
            (Ok(_), Some(err)) => {
                anyhow::bail!("expected error {err} but validation was successful")
            },
            (
                Err(ExecutionError::OperationError {
                    err:
                        miden_processor::operation::OperationError::FailedAssertion {
                            err_code,
                            err_msg,
                        },
                    ..
                }),
                Some(err),
            ) => {
                if err_code != err.code() {
                    anyhow::bail!(
                        "actual error \"{}\" (code: {err_code}) did not match expected error {err}",
                        err_msg.as_ref().map(AsRef::as_ref).unwrap_or("<no message>")
                    );
                }
            },
            (Err(err), None) => {
                return Err(anyhow::anyhow!(
                    "validation is supposed to succeed but error occurred: {}",
                    PrintDiagnostic::new(&err)
                ));
            },
            (Err(err), Some(_)) => {
                return Err(anyhow::anyhow!(
                    "unexpected different error than expected: {}",
                    PrintDiagnostic::new(&err)
                ));
            },
        }
    }

    Ok(())
}

/// `account_id::validate_structure` enforces the version-independent structural requirements of an
/// account ID without constraining the version, so IDs carrying a future (currently unsupported)
/// version pass as long as their suffix is well-formed.
#[tokio::test]
async fn test_account_validate_structure_ignores_version() -> anyhow::Result<()> {
    let test_cases = [
        // A regular version-one ID is structurally valid.
        (ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE, None),
        (
            // An unsupported version (10) is still accepted: the structure is validated, not the
            // version.
            (ACCOUNT_ID_REGULAR_PRIVATE_ACCOUNT_UPDATABLE_CODE & !(0x0f << 64)) | (0x0a << 64),
            None,
        ),
        (
            // Set most significant bit of the suffix to `1`.
            ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET | (0x80 << 56),
            Some(ERR_ACCOUNT_ID_SUFFIX_MOST_SIGNIFICANT_BIT_MUST_BE_ZERO),
        ),
        (
            // Set lower 8 bits of the suffix to a non-zero value (1).
            ACCOUNT_ID_PRIVATE_NON_FUNGIBLE_FAUCET | 1,
            Some(ERR_ACCOUNT_ID_SUFFIX_LEAST_SIGNIFICANT_BYTE_MUST_BE_ZERO),
        ),
    ];

    for (account_id, expected_error) in test_cases.iter() {
        // Manually split the account ID into prefix and suffix since we can't use AccountId methods
        // on invalid ids.
        let (prefix, suffix) = account_id_felts(account_id)?;

        let code = "
            use miden::protocol::account_id

            begin
                exec.account_id::validate_structure
            end
            ";

        let result = CodeExecutor::with_default_host()
            .stack_inputs(StackInputs::new(&[suffix, prefix]).unwrap())
            .run(code)
            .await;

        match (result.map_err(ExecError::into_execution_error), expected_error) {
            (Ok(_), None) => (),
            (Ok(_), Some(err)) => {
                anyhow::bail!("expected error {err} but validation was successful")
            },
            (
                Err(ExecutionError::OperationError {
                    err:
                        miden_processor::operation::OperationError::FailedAssertion {
                            err_code,
                            err_msg,
                        },
                    ..
                }),
                Some(err),
            ) => {
                if err_code != err.code() {
                    anyhow::bail!(
                        "actual error \"{}\" (code: {err_code}) did not match expected error {err}",
                        err_msg.as_ref().map(AsRef::as_ref).unwrap_or("<no message>")
                    );
                }
            },
            (Err(err), None) => {
                return Err(anyhow::anyhow!(
                    "validation is supposed to succeed but error occurred: {}",
                    PrintDiagnostic::new(&err)
                ));
            },
            (Err(err), Some(_)) => {
                return Err(anyhow::anyhow!(
                    "unexpected different error than expected: {}",
                    PrintDiagnostic::new(&err)
                ));
            },
        }
    }

    Ok(())
}

/// Exercises the account ID comparison helpers -- `eq`, `eqz`, and `testz` -- in a single program.
#[tokio::test]
async fn test_account_id_comparison() -> anyhow::Result<()> {
    let (prefix_1, suffix_1) = account_id_felts(&ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_IMMUTABLE_CODE)?;
    let (prefix_2, suffix_2) = account_id_felts(&ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1)?;

    let code = format!(
        r#"
        use miden::protocol::account_id

        begin
            # eq: identical IDs are equal
            push.{prefix_1}.{suffix_1}.{prefix_1}.{suffix_1}
            exec.account_id::eq
            assert.err="eq: identical IDs should be equal"
            # => [pad(16)]

            # eq: different IDs are not equal
            push.{prefix_1}.{suffix_1}.{prefix_2}.{suffix_2}
            exec.account_id::eq
            assertz.err="eq: different IDs should not be equal"
            # => [pad(16)]

            # eqz: the zero address is zero
            push.0.0
            exec.account_id::eqz
            assert.err="eqz: the zero address should be zero"
            # => [pad(16)]

            # eqz: a valid ID is not zero
            push.{prefix_1}.{suffix_1}
            exec.account_id::eqz
            assertz.err="eqz: a valid ID should not be zero"
            # => [pad(16)]

            # testz: the zero address is zero
            push.0.0
            exec.account_id::testz
            assert.err="testz: the zero address should be zero"
            # => [pad(18)]

            # testz: a valid ID is not zero, leaving [suffix_1, prefix_1] on the stack
            push.{prefix_1}.{suffix_1}
            exec.account_id::testz
            assertz.err="testz: a valid ID should not be zero"
            # => [suffix_1, prefix_1, pad(18)]

            # truncate the stack
            swapw dropw
            # => [suffix_1, prefix_1, pad(14)]
        end
        "#
    );

    let exec_output = CodeExecutor::with_default_host()
        .run(&code)
        .await
        .map_err(ExecError::into_execution_error)?;

    // testz must preserve the account ID beneath the (already consumed) flag.
    assert_eq!(exec_output.get_stack_element(0), suffix_1, "testz must preserve the ID suffix");
    assert_eq!(exec_output.get_stack_element(1), prefix_1, "testz must preserve the ID prefix");

    Ok(())
}

// ACCOUNT CODE TESTS
// ================================================================================================

// TODO: update this test once the ability to change the account code will be implemented
#[tokio::test]
pub async fn test_compute_code_commitment() -> anyhow::Result<()> {
    let mock_tx = TestTransactionBuilder::with_existing_mock_account().build().unwrap();
    let account = mock_tx.account();

    let code = format!(
        r#"
        use miden::tx_kernel_core::prologue
        use mock::account as mock_account

        begin
            exec.prologue::prepare_transaction
            # get the code commitment
            call.mock_account::get_code_commitment
            push.{expected_code_commitment}
            assert_eqw.err="actual code commitment is not equal to the expected one"
        end
        "#,
        expected_code_commitment = account.code().commitment()
    );

    mock_tx.execute_code(&code).await?;

    Ok(())
}

// ACCOUNT STORAGE TESTS
// ================================================================================================

#[tokio::test]
async fn test_get_item() -> anyhow::Result<()> {
    for storage_item in [AccountStorage::mock_value_slot0(), AccountStorage::mock_value_slot1()] {
        let mock_tx = TestTransactionBuilder::with_existing_mock_account().build().unwrap();

        let code = format!(
            r#"
            use miden::tx_kernel_core::account
            use miden::tx_kernel_core::prologue

            const SLOT_NAME = word("{slot_name}")

            begin
                exec.prologue::prepare_transaction

                # push the account storage item index
                push.SLOT_NAME[0..2]
                # => [slot_id_suffix, slot_id_prefix]

                # assert the item value is correct
                exec.account::get_item
                push.{item_value}
                assert_eqw.err="expected item to have value {item_value}"
            end
            "#,
            slot_name = storage_item.name(),
            item_value = storage_item.content().value(),
        );

        mock_tx.execute_code(&code).await.unwrap();
    }

    Ok(())
}

#[tokio::test]
async fn test_get_map_item() -> anyhow::Result<()> {
    let slot = AccountStorage::mock_map_slot();
    let account = AccountBuilder::new(rand::random())
        .with_components(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_slots(vec![slot.clone()]))
        .build_existing()
        .unwrap();

    let mock_tx = TestTransactionBuilder::new(account).build().unwrap();

    let StorageSlotContent::Map(map) = slot.content() else {
        panic!("expected map")
    };

    for (key, expected_value) in map.entries() {
        let code = format!(
            r#"
            use miden::tx_kernel_core::prologue
            use mock::account

            const SLOT_NAME = word("{slot_name}")

            begin
                exec.prologue::prepare_transaction

                # get the map item
                push.{key}
                push.SLOT_NAME[0..2]
                call.account::get_map_item
                # => [VALUE]

                push.{expected_value}
                assert_eqw.err="value did not match {expected_value}"

                exec.::miden::core::sys::truncate_stack
            end
            "#,
            slot_name = slot.name(),
        );

        mock_tx.execute_code(&code).await?;
    }

    Ok(())
}

#[tokio::test]
async fn test_get_native_storage_slot_type() -> anyhow::Result<()> {
    for slot_name in [
        AccountStorage::mock_value_slot0().name(),
        AccountStorage::mock_value_slot1().name(),
        AccountStorage::mock_map_slot().name(),
    ] {
        let mock_tx = TestTransactionBuilder::with_existing_mock_account().build().unwrap();
        let (slot_idx, slot) = mock_tx
            .account()
            .storage()
            .slots()
            .iter()
            .enumerate()
            .find(|(_, slot)| slot.name() == slot_name)
            .unwrap();

        let code = format!(
            "
            use miden::tx_kernel_core::account
            use miden::tx_kernel_core::prologue

            begin
                exec.prologue::prepare_transaction

                # push the account storage slot index
                push.{slot_idx}

                # get the type of the respective storage slot
                exec.account::get_native_storage_slot_type

                # truncate the stack
                swap drop
            end
            ",
        );

        let exec_output = &mock_tx.execute_code(&code).await.unwrap();

        assert_eq!(
            slot.slot_type(),
            StorageSlotType::try_from(
                u8::try_from(exec_output.get_stack_element(0).as_canonical_u64()).unwrap()
            )
            .unwrap()
        );
        assert_eq!(exec_output.get_stack_element(1), ZERO, "the rest of the stack is empty");
        assert_eq!(exec_output.get_stack_element(2), ZERO, "the rest of the stack is empty");
        assert_eq!(exec_output.get_stack_element(3), ZERO, "the rest of the stack is empty");
        assert_eq!(exec_output.get_stack_word(4), Word::empty(), "the rest of the stack is empty");
        assert_eq!(exec_output.get_stack_word(8), Word::empty(), "the rest of the stack is empty");
        assert_eq!(exec_output.get_stack_word(12), Word::empty(), "the rest of the stack is empty");
    }

    Ok(())
}

/// Tests that `validate_storage` rejects a storage slot whose type is outside the supported set
/// (value or map) instead of silently committing it as a map (audit finding L-11).
#[tokio::test]
async fn validate_storage_rejects_unsupported_slot_type() -> anyhow::Result<()> {
    let mock_tx = TestTransactionBuilder::with_existing_mock_account().build().unwrap();

    // Overwrite the type element (offset 1) of the first storage slot with an unsupported type,
    // then run the new-account storage validation which must reject it.
    let code = "
        use miden::tx_kernel_core::account
        use miden::tx_kernel_core::memory
        use miden::tx_kernel_core::prologue

        begin
            exec.prologue::prepare_transaction

            push.2
            exec.memory::get_native_account_active_storage_slots_ptr add.1
            mem_store

            exec.account::validate_storage
        end
        ";

    let exec_output = mock_tx.execute_code(code).await;
    assert_execution_error!(exec_output, ERR_ACCOUNT_STORAGE_SLOT_TYPE_IS_INVALID);

    Ok(())
}

/// Tests that accessing an unknown slot fails with the expected error message.
///
/// This tests both accounts with empty storage and non-empty storage.
#[tokio::test]
async fn test_account_get_item_fails_on_unknown_slot() -> anyhow::Result<()> {
    let mut builder = MockChain::builder();

    let account_empty_storage = builder.add_existing_mock_account(Auth::IncrNonce)?;
    assert_eq!(account_empty_storage.storage().num_slots(), 0);

    let account_non_empty_storage = builder.add_existing_mock_account(Auth::BasicAuth {
        auth_scheme: AuthScheme::Falcon512Poseidon2,
    })?;
    assert_eq!(account_non_empty_storage.storage().num_slots(), 2);

    let chain = builder.build()?;

    let code = r#"
            use mock::account

            const UNKNOWN_SLOT_NAME = word("unknown::slot::name")

            @transaction_script
            pub proc main
                push.UNKNOWN_SLOT_NAME[0..2]
                call.account::get_item
            end
            "#;
    let tx_script = CodeBuilder::with_mock_packages().compile_tx_script(code)?;

    let result = chain
        .build_transaction(account_empty_storage)
        .tx_script(tx_script.clone())
        .build()?
        .execute()
        .await;
    assert_transaction_executor_error!(result, ERR_ACCOUNT_UNKNOWN_STORAGE_SLOT_NAME);

    let result = chain
        .build_transaction(account_non_empty_storage)
        .tx_script(tx_script)
        .build()?
        .execute()
        .await;
    assert_transaction_executor_error!(result, ERR_ACCOUNT_UNKNOWN_STORAGE_SLOT_NAME);

    Ok(())
}

#[tokio::test]
async fn test_is_slot_id_lt() -> anyhow::Result<()> {
    // Note that the slot IDs derived from the names are essentially randomly sorted, so these cover
    // "less than" and "greater than" outcomes.
    let mut test_cases = (0..100)
        .map(|i| {
            let prev_slot = StorageSlotName::mock(i).id();
            let curr_slot = StorageSlotName::mock(i + 1).id();
            (prev_slot, curr_slot)
        })
        .collect::<Vec<_>>();

    // Extend with special case where prefix matches and suffix determines the outcome.
    let prefix = Felt::from(100u32);
    test_cases.extend([
        // prev_slot == curr_slot
        (
            StorageSlotId::new(Felt::from(50u32), prefix),
            StorageSlotId::new(Felt::from(50u32), prefix),
        ),
        // prev_slot < curr_slot
        (
            StorageSlotId::new(Felt::from(50u32), prefix),
            StorageSlotId::new(Felt::from(51u32), prefix),
        ),
        // prev_slot > curr_slot
        (
            StorageSlotId::new(Felt::from(51u32), prefix),
            StorageSlotId::new(Felt::from(50u32), prefix),
        ),
    ]);

    for (prev_slot, curr_slot) in test_cases {
        let code = format!(
            r#"
            use miden::tx_kernel_core::account

            begin
                push.{curr_prefix}.{curr_suffix}.{prev_prefix}.{prev_suffix}
                # => [prev_slot_id_suffix, prev_slot_id_prefix, curr_slot_id_suffix, curr_slot_id_prefix]

                exec.account::is_slot_id_lt
                # => [is_slot_id_lt]

                push.{is_lt}
                assert_eq.err="is_slot_id_lt was not {is_lt}"
                # => []
            end
            "#,
            prev_prefix = prev_slot.prefix(),
            prev_suffix = prev_slot.suffix(),
            curr_prefix = curr_slot.prefix(),
            curr_suffix = curr_slot.suffix(),
            is_lt = u8::from(prev_slot < curr_slot)
        );

        CodeExecutor::with_default_host().run(&code).await?;
    }

    Ok(())
}

/// Returns the requested number of distinct procedure roots sorted in ascending order.
fn sorted_procedure_roots(num_procedures: usize) -> Vec<AccountProcedureRoot> {
    let mut rng = RandomCoin::new([num_procedures as u32, 0, 0, 0].into());
    let mut roots = (0..num_procedures as u32)
        .map(|_| AccountProcedureRoot::from_raw(rng.draw_word()))
        .collect::<Vec<_>>();
    roots.sort_unstable();

    roots
}

/// Returns a program that writes the provided procedure roots into the native account's code
/// section and validates them.
/// TODO: Refactor to create the custom procedure section in local memory and call
/// validate_procedures with a pointer, so it becomes simpler.
fn validate_procedures_program(procedure_roots: &[AccountProcedureRoot]) -> String {
    let procedure_writes = procedure_roots
        .iter()
        .enumerate()
        .map(|(index, root)| {
            format!(
                "push.{root}
                exec.memory::get_account_procedures_section_ptr add.{offset} mem_storew_le dropw",
                offset = index * Word::NUM_ELEMENTS
            )
        })
        .collect::<Vec<_>>()
        .join("\n");

    format!(
        r#"
        use miden::tx_kernel_core::account
        use miden::tx_kernel_core::memory

        begin
            exec.memory::set_active_account_data_ptr_to_native_account

            push.{num_procedures} exec.memory::set_num_account_procedures

            {procedure_writes}

            exec.memory::get_active_account_code_section_ptr
            exec.account::validate_procedures
        end
        "#,
        num_procedures = procedure_roots.len()
    )
}

/// The auth procedure at index 0 is exempt from the ordering, so it is validated against roots that
/// sort before, in between and after the other procedures.
#[rstest::rstest]
#[case::minimum_number_of_procedures(2, 0)]
#[case::auth_procedure_sorts_first(8, 0)]
#[case::auth_procedure_sorts_in_between(8, 4)]
#[case::auth_procedure_sorts_last(8, 7)]
#[tokio::test]
async fn test_validate_procedures_accepts_sorted_and_unique_procedures(
    #[case] num_procedures: usize,
    #[case] auth_procedure_index: usize,
) -> anyhow::Result<()> {
    let mut procedure_roots = sorted_procedure_roots(num_procedures);
    let auth_procedure_root = procedure_roots.remove(auth_procedure_index);
    procedure_roots.insert(0, auth_procedure_root);

    CodeExecutor::with_default_host()
        .run(&validate_procedures_program(&procedure_roots))
        .await?;

    Ok(())
}

#[rstest::rstest]
#[case::first_pair_swapped(1, 2)]
#[case::last_pair_swapped(6, 7)]
#[case::first_and_last_swapped(1, 7)]
#[tokio::test]
async fn test_validate_procedures_rejects_unsorted_procedures(
    #[case] left_index: usize,
    #[case] right_index: usize,
) -> anyhow::Result<()> {
    let mut procedure_roots = sorted_procedure_roots(8);
    procedure_roots.swap(left_index, right_index);

    let result = CodeExecutor::with_default_host()
        .run(&validate_procedures_program(&procedure_roots))
        .await;

    assert_execution_error!(result, ERR_ACCOUNT_PROCEDURES_MUST_BE_SORTED_AND_UNIQUE);

    Ok(())
}

/// The duplicated procedure is always the one preceding it, which must be at index 1 or greater so
/// the duplicate does not involve the auth procedure at index 0.
#[rstest::rstest]
#[case::first_procedure(2)]
#[case::middle_procedure(4)]
#[case::last_procedure(7)]
#[tokio::test]
async fn test_validate_procedures_rejects_duplicated_procedure(
    #[case] duplicated_index: usize,
) -> anyhow::Result<()> {
    let mut procedure_roots = sorted_procedure_roots(8);
    procedure_roots[duplicated_index] = procedure_roots[duplicated_index - 1];

    let result = CodeExecutor::with_default_host()
        .run(&validate_procedures_program(&procedure_roots))
        .await;

    assert_execution_error!(result, ERR_ACCOUNT_PROCEDURES_MUST_BE_SORTED_AND_UNIQUE);

    Ok(())
}

/// A duplicated auth procedure is not caught by the ordering check, since the auth procedure is
/// exempt from it, so it must be rejected by the explicit comparison against the root at index 0.
#[rstest::rstest]
#[case::minimum_number_of_procedures(2, 1)]
#[case::first_procedure(8, 1)]
#[case::middle_procedure(8, 4)]
#[case::last_procedure(8, 7)]
#[tokio::test]
async fn test_validate_procedures_rejects_duplicated_auth_procedure(
    #[case] num_procedures: usize,
    #[case] duplicated_index: usize,
) -> anyhow::Result<()> {
    let mut procedure_roots = sorted_procedure_roots(num_procedures);
    procedure_roots[0] = procedure_roots[duplicated_index];

    let result = CodeExecutor::with_default_host()
        .run(&validate_procedures_program(&procedure_roots))
        .await;

    assert_execution_error!(result, ERR_ACCOUNT_AUTH_PROCEDURE_MUST_NOT_BE_DUPLICATED);

    Ok(())
}

#[tokio::test]
async fn test_set_item() -> anyhow::Result<()> {
    let mock_tx = TestTransactionBuilder::with_existing_mock_account().build().unwrap();

    let slot_name = &*MOCK_VALUE_SLOT0;
    let new_value = Word::from([91, 92, 93, 94u32]);
    let old_value = mock_tx.account().storage().get_item(slot_name)?;

    let code = format!(
        r#"
        use miden::tx_kernel_core::account
        use miden::tx_kernel_core::prologue

        const MOCK_VALUE_SLOT0 = word("{slot_name}")

        begin
            exec.prologue::prepare_transaction

            # set the storage item
            push.{new_value}
            push.MOCK_VALUE_SLOT0[0..2]
            # => [slot_id_suffix, slot_id_prefix, NEW_VALUE]

            exec.account::set_item

            # assert old value was correctly returned
            push.{old_value}
            assert_eqw.err="old value did not match"

            # assert new value has been correctly set
            push.MOCK_VALUE_SLOT0[0..2]
            # => [slot_id_suffix, slot_id_prefix]

            exec.account::get_item
            push.{new_value}
            assert_eqw.err="new value did not match"
        end
        "#,
    );

    mock_tx.execute_code(&code).await?;

    Ok(())
}

#[tokio::test]
async fn test_set_map_item() -> anyhow::Result<()> {
    let (new_key, new_value) = (
        StorageMapKey::from_array([109, 110, 111, 112u32]),
        Word::from([9, 10, 11, 12u32]),
    );

    let slot = AccountStorage::mock_map_slot();
    let account = AccountBuilder::new(rand::random())
        .with_components(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_slots(vec![slot.clone()]))
        .build_existing()
        .unwrap();

    let mock_tx = TestTransactionBuilder::new(account).build().unwrap();

    let code = format!(
        r#"
        use miden::core::sys

        use miden::tx_kernel_core::prologue
        use mock::account as mock_account

        const SLOT_NAME=word("{slot_name}")

        begin
            exec.prologue::prepare_transaction

            # set the map item
            push.{new_value}
            push.{new_key}
            push.SLOT_NAME[0..2]
            call.mock_account::set_map_item

            # double check that the storage slot is indeed the new map
            push.SLOT_NAME[0..2]
            # => [slot_id_suffix, slot_id_prefix, OLD_VALUE]

            # pad the stack
            repeat.14 push.0 movdn.2 end
            # => [slot_id_suffix, slot_id_prefix, pad(14), OLD_VALUE]

            call.mock_account::get_item
            # => [MAP_ROOT, pad(12), OLD_VALUE]

            # truncate the stack
            repeat.3 swapw dropw end
            # => [MAP_ROOT, OLD_VALUE]

            exec.sys::truncate_stack
        end
        "#,
        slot_name = slot.name(),
        new_key = new_key,
        new_value = new_value,
    );

    let exec_output = &mock_tx.execute_code(&code).await?;

    let mut new_storage_map = AccountStorage::mock_map();
    new_storage_map.insert(new_key, new_value).unwrap();

    assert_eq!(
        new_storage_map.root(),
        exec_output.get_stack_word(0),
        "get_item should return the updated root",
    );

    let old_value_for_key = match slot.content() {
        StorageSlotContent::Map(original_map) => original_map.get(&new_key),
        _ => panic!("expected map"),
    };
    assert_eq!(
        old_value_for_key,
        exec_output.get_stack_word(4),
        "set_map_item must return the old value for the key (empty word for new key)",
    );

    Ok(())
}

/// Tests that we can successfully create regular and faucet accounts with empty storage.
#[tokio::test]
async fn create_account_with_empty_storage_slots() -> anyhow::Result<()> {
    let account = AccountBuilder::new([5; 32])
        .with_components(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .build()
        .context("failed to build account")?;

    TestTransactionBuilder::new(account).build()?.execute().await?;

    Ok(())
}

#[tokio::test]
async fn test_get_initial_storage_commitment() -> anyhow::Result<()> {
    let mock_tx = TestTransactionBuilder::with_existing_mock_account().build()?;

    let code = format!(
        r#"
        use mock::account as mock_account
        use miden::tx_kernel_core::prologue

        begin
            exec.prologue::prepare_transaction

            # get the initial storage commitment
            call.mock_account::get_initial_storage_commitment
            # => [INIT_STORAGE_COMMITMENT, pad(12)]
            swapdw dropw dropw swapw dropw
            # => [INIT_STORAGE_COMMITMENT]
            push.{expected_storage_commitment}
            assert_eqw.err="actual storage commitment is not equal to the expected one"
        end
        "#,
        expected_storage_commitment = mock_tx.account().storage().to_commitment(),
    );
    mock_tx.execute_code(&code).await?;

    Ok(())
}

// ACCOUNT UPGRADE TESTS
// ================================================================================================

/// Returns the existing mock account that the upgrade tests start from.
fn existing_mock_account() -> Account {
    Account::mock(ACCOUNT_ID_REGULAR_PUBLIC_ACCOUNT_UPDATABLE_CODE, [IncrNonceAuthComponent])
}

/// Returns the code of the mock account extended with the [`AddComponent`], which the upgrade tests
/// upgrade to.
fn upgraded_mock_account_code() -> anyhow::Result<AccountCode> {
    Ok(AccountCode::from_components(&[
        IncrNonceAuthComponent.into(),
        MockAccountComponent::with_slots(vec![]).into(),
        AddComponent.into(),
    ])?)
}

/// Returns a transaction script that initializes one account upgrade per provided pair of new code
/// and new storage commitments.
fn upgrade_tx_script(
    upgrades: impl IntoIterator<Item = (Word, Word)>,
) -> anyhow::Result<TransactionScript> {
    let upgrade_calls: String = upgrades
        .into_iter()
        .map(|(new_code_commitment, storage_upgrade_commitment)| {
            format!(
                "
                push.{storage_upgrade_commitment}
                push.{new_code_commitment}
                call.mock_account::upgrade
                dropw dropw
                "
            )
        })
        .collect();

    let tx_script = format!(
        r#"
        use mock::account as mock_account

        @transaction_script
        pub proc main
            {upgrade_calls}
        end
        "#
    );

    Ok(CodeBuilder::with_mock_packages().compile_tx_script(tx_script)?)
}

/// Returns a program that runs the prologue and then initializes an upgrade of the native account's
/// code to the code with `new_code_commitment`.
fn upgrade_program(new_code_commitment: Word) -> String {
    format!(
        r#"
        use mock::account as mock_account
        use miden::tx_kernel_core::prologue

        begin
            exec.prologue::prepare_transaction

            padw push.{new_code_commitment}
            # => [NEW_CODE_COMMITMENT, STORAGE_UPGRADE_COMMITMENT, pad(8)]

            call.mock_account::upgrade
            # => [pad(16)]
            dropw dropw dropw dropw
        end
        "#,
    )
}

/// Tests that `native_account::upgrade` stores the new code commitment in kernel memory, and the
/// empty word if the upgrade is a no-op.
#[rstest::rstest]
#[case::upgraded_code(upgraded_mock_account_code()?.commitment(), upgraded_mock_account_code()?.commitment())]
#[case::current_code(existing_mock_account().code().commitment(), Word::empty())]
#[case::empty_word(Word::empty(), Word::empty())]
#[tokio::test]
async fn test_account_upgrade_stores_code_commitment(
    #[case] new_code_commitment: Word,
    #[case] expected_code_upgrade_commitment: Word,
) -> anyhow::Result<()> {
    let mock_tx = TestTransactionBuilder::new(existing_mock_account())
        .account_code_upgrade(AccountCodeUpgrade::new(upgraded_mock_account_code()?))
        .build()?;

    let exec_output = &mock_tx.execute_code(&upgrade_program(new_code_commitment)).await?;

    assert_eq!(
        exec_output.get_kernel_mem_word(CODE_UPGRADE_COMMITMENT_PTR),
        expected_code_upgrade_commitment,
    );
    assert_eq!(exec_output.get_kernel_mem_word(STORAGE_UPGRADE_COMMITMENT_PTR), Word::empty());

    Ok(())
}

/// Tests that a transaction replaces the code of the native account in its final state and patch,
/// and that an upgrade to the current code leaves the code unchanged.
///
/// A pending upgrade must also count as a state change before the nonce is incremented.
#[rstest::rstest]
#[case::upgraded_code(true)]
#[case::current_code(false)]
#[tokio::test]
async fn test_account_upgrade_replaces_code(#[case] is_upgrade: bool) -> anyhow::Result<()> {
    let account = existing_mock_account();
    let upgraded_code = upgraded_mock_account_code()?;
    let expected_code = if is_upgrade {
        upgraded_code.clone()
    } else {
        account.code().clone()
    };

    let tx_script = format!(
        r#"
        use mock::account as mock_account

        @transaction_script
        pub proc main
            padw push.{new_code_commitment}
            # => [NEW_CODE_COMMITMENT, STORAGE_UPGRADE_COMMITMENT]

            call.mock_account::upgrade
            dropw dropw
            # => []

            call.mock_account::has_state_changed
            # => [has_state_changed]

            eq.{is_upgrade} assert.err="a pending code upgrade should count as a state change"
            dropw dropw dropw drop drop drop
            # => []
        end
        "#,
        new_code_commitment = expected_code.commitment(),
        is_upgrade = u8::from(is_upgrade),
    );
    let tx_script = CodeBuilder::with_mock_packages().compile_tx_script(tx_script)?;

    let executed_tx = TestTransactionBuilder::new(account.clone())
        .tx_script(tx_script)
        .account_code_upgrade(AccountCodeUpgrade::new(upgraded_code))
        .build()?
        .execute()
        .await?;

    assert_eq!(executed_tx.final_account().code_commitment(), expected_code.commitment());
    assert_eq!(
        executed_tx.account_patch().code().as_code(),
        is_upgrade.then_some(&expected_code)
    );

    let mut expected_account = account;
    expected_account.apply_patch(executed_tx.account_patch())?;
    assert_eq!(expected_account.to_commitment(), executed_tx.final_account().to_commitment());

    // Check account upgrades work under the prover's re-execution.
    LocalTransactionProver::default().prove(executed_tx)?;

    Ok(())
}

/// Tests that an auth component that signs the delta commitment signs the upgraded code, which
/// requires the delta commitments of the kernel and the host to agree on the code section.
#[tokio::test]
async fn test_account_upgrade_with_signature_auth() -> anyhow::Result<()> {
    let mut builder = MockChain::builder();
    let account = builder.add_existing_mock_account(Auth::BasicAuth {
        auth_scheme: AuthScheme::Falcon512Poseidon2,
    })?;
    let mock_chain = builder.build()?;

    let upgraded_code = upgraded_mock_account_code()?;
    let executed_tx = mock_chain
        .build_transaction(account.id())
        .tx_script(upgrade_tx_script([(upgraded_code.commitment(), Word::empty())])?)
        .account_code_upgrade(AccountCodeUpgrade::new(upgraded_code.clone()))
        .build()?
        .execute()
        .await?;

    assert_eq!(executed_tx.final_account().code_commitment(), upgraded_code.commitment());
    assert_eq!(executed_tx.account_patch().code().as_code(), Some(&upgraded_code));

    Ok(())
}

/// Tests that the kernel rejects upgrades that are invalid on their own.
#[rstest::rstest]
#[case::storage_upgrade(
    vec![(upgraded_mock_account_code()?.commitment(), Word::from([1, 2, 3, 4u32]))],
    ERR_ACCOUNT_UPGRADE_STORAGE_UPGRADES_UNSUPPORTED,
)]
#[case::second_upgrade(
    vec![(upgraded_mock_account_code()?.commitment(), Word::empty()); 2],
    ERR_ACCOUNT_UPGRADE_CODE_ALREADY_SET,
)]
#[tokio::test]
async fn test_account_upgrade_rejects_invalid_initialization(
    #[case] upgrades: Vec<(Word, Word)>,
    #[case] expected_error: MasmError,
) -> anyhow::Result<()> {
    let result = TestTransactionBuilder::new(existing_mock_account())
        .tx_script(upgrade_tx_script(upgrades)?)
        .account_code_upgrade(AccountCodeUpgrade::new(upgraded_mock_account_code()?))
        .build()?
        .execute()
        .await;

    assert_transaction_executor_error!(result, expected_error);

    Ok(())
}

/// Tests that a new account cannot be upgraded, since its code is part of its creation.
#[tokio::test]
async fn test_account_upgrade_rejects_new_account() -> anyhow::Result<()> {
    let mut builder = MockChain::builder();
    let account = builder.create_new_mock_account(Auth::IncrNonce)?;
    let mut mock_chain = builder.build()?;
    mock_chain.prove_next_block()?;

    let result = mock_chain
        .build_transaction(account)
        .tx_script(upgrade_tx_script([(
            upgraded_mock_account_code()?.commitment(),
            Word::empty(),
        )])?)
        .build()?
        .execute()
        .await;

    assert_transaction_executor_error!(result, ERR_ACCOUNT_UPGRADE_NOT_ALLOWED_FOR_NEW_ACCOUNT);

    Ok(())
}

/// Tests that the host rejects an upgrade to code that the advice map does not provide.
#[tokio::test]
async fn test_account_upgrade_rejects_missing_code() -> anyhow::Result<()> {
    let upgraded_code = upgraded_mock_account_code()?;

    let result = TestTransactionBuilder::new(existing_mock_account())
        .tx_script(upgrade_tx_script([(upgraded_code.commitment(), Word::empty())])?)
        .build()?
        .execute()
        .await;

    assert_transaction_executor_error!(
        result,
        matches ExecutionError::EventError { error: ref event_err, .. }
            if matches!(
                event_err.downcast_ref::<TransactionKernelError>(),
                Some(TransactionKernelError::AccountCodeUpgradeMissing(new_code_commitment))
                    if *new_code_commitment == upgraded_code.commitment()
            )
    );

    Ok(())
}

/// Tests that the host rejects an upgrade whose advice map entry does not encode valid code.
#[tokio::test]
async fn test_account_upgrade_rejects_invalid_code() -> anyhow::Result<()> {
    let upgraded_code = upgraded_mock_account_code()?;

    let result = TestTransactionBuilder::new(existing_mock_account())
        .tx_script(upgrade_tx_script([(upgraded_code.commitment(), Word::empty())])?)
        .add_advice_map_entry(
            AccountCodeUpgrade::advice_map_key(upgraded_code.commitment()),
            vec![Felt::ONE],
        )
        .build()?
        .execute()
        .await;

    assert_transaction_executor_error!(
        result,
        matches ExecutionError::EventError { error: ref event_err, .. }
            if matches!(
                event_err.downcast_ref::<TransactionKernelError>(),
                Some(TransactionKernelError::AccountCodeUpgradeInvalid { new_code_commitment, .. })
                    if *new_code_commitment == upgraded_code.commitment()
            )
    );

    Ok(())
}

/// Tests that the host rejects an upgrade whose advice map entry provides code with a different
/// commitment.
#[tokio::test]
async fn test_account_upgrade_rejects_code_not_matching_commitment() -> anyhow::Result<()> {
    let upgraded_code = upgraded_mock_account_code()?;
    let provided_code = AccountCode::mock();
    assert_ne!(upgraded_code.commitment(), provided_code.commitment());

    let (_, provided_code_data) =
        AccountCodeUpgrade::new(provided_code.clone()).to_advice_map_entry();
    let result = TestTransactionBuilder::new(existing_mock_account())
        .tx_script(upgrade_tx_script([(upgraded_code.commitment(), Word::empty())])?)
        .add_advice_map_entry(
            AccountCodeUpgrade::advice_map_key(upgraded_code.commitment()),
            provided_code_data,
        )
        .build()?
        .execute()
        .await;

    assert_transaction_executor_error!(
        result,
        matches ExecutionError::EventError { error: ref event_err, .. }
            if matches!(
                event_err.downcast_ref::<TransactionKernelError>(),
                Some(TransactionKernelError::AccountCodeUpgradeCommitmentMismatch {
                    expected,
                    actual,
                }) if *expected == upgraded_code.commitment()
                    && *actual == provided_code.commitment()
            )
    );

    Ok(())
}

/// Tests that the upgrade rejects procedures that do not match the new code commitment, so that a
/// malicious host cannot swap the code the transaction commits to.
#[tokio::test]
async fn test_account_upgrade_rejects_procedures_not_matching_commitment() -> anyhow::Result<()> {
    let upgraded_code = upgraded_mock_account_code()?;

    // Without lazy loading, the host does not provide the procedures of the new code, so the kernel
    // loads the mismatching procedures from the advice map.
    let mock_tx = TestTransactionBuilder::new(existing_mock_account())
        .add_advice_map_entry(upgraded_code.commitment(), AccountCode::mock().to_elements())
        .build()?;

    let result = mock_tx
        .execute_code_without_lazy_loading(&upgrade_program(upgraded_code.commitment()))
        .await;

    assert_execution_error!(result, ERR_ACCOUNT_CODE_COMMITMENT_MISMATCH);

    Ok(())
}

/// Tests that the upgrade rejects procedures that match the new code commitment but are not valid
/// account procedures, which only a malicious host could provide.
#[rstest::rstest]
#[case::not_enough_procedures(sorted_procedure_roots(1), ERR_ACCOUNT_NOT_ENOUGH_PROCEDURES)]
#[case::unsorted_procedures(
    {
        let mut procedure_roots = sorted_procedure_roots(4);
        procedure_roots.swap(1, 2);
        procedure_roots
    },
    ERR_ACCOUNT_PROCEDURES_MUST_BE_SORTED_AND_UNIQUE,
)]
#[case::duplicated_auth_procedure(
    {
        let mut procedure_roots = sorted_procedure_roots(4);
        procedure_roots[3] = procedure_roots[0];
        procedure_roots
    },
    ERR_ACCOUNT_AUTH_PROCEDURE_MUST_NOT_BE_DUPLICATED,
)]
#[tokio::test]
async fn test_account_upgrade_rejects_invalid_procedures(
    #[case] procedure_roots: Vec<AccountProcedureRoot>,
    #[case] expected_error: MasmError,
) -> anyhow::Result<()> {
    let procedure_elements: Vec<Felt> = procedure_roots
        .iter()
        .flat_map(AccountProcedureRoot::as_elements)
        .copied()
        .collect();
    let new_code_commitment = Hasher::hash_elements(&procedure_elements);

    // Without lazy loading, the host does not provide the procedures of the new code, so the kernel
    // loads the invalid procedures from the advice map.
    let mock_tx = TestTransactionBuilder::new(existing_mock_account())
        .add_advice_map_entry(new_code_commitment, procedure_elements)
        .build()?;

    let result = mock_tx
        .execute_code_without_lazy_loading(&upgrade_program(new_code_commitment))
        .await;

    assert_execution_error!(result, expected_error);

    Ok(())
}

/// Tests that a code upgrade without a nonce increment is rejected.
#[tokio::test]
async fn test_account_upgrade_requires_nonce_increment() -> anyhow::Result<()> {
    let upgraded_code = upgraded_mock_account_code()?;

    let result = TestTransactionBuilder::with_noop_auth_account()
        .tx_script(upgrade_tx_script([(upgraded_code.commitment(), Word::empty())])?)
        .account_code_upgrade(AccountCodeUpgrade::new(upgraded_code))
        .build()?
        .execute()
        .await;

    assert_transaction_executor_error!(
        result,
        ERR_ACCOUNT_PATCH_NONCE_MUST_BE_INCREMENTED_IF_STATE_CHANGED
    );

    Ok(())
}

/// Tests that `account_upgrade` is gated by the account context: invoking it from outside an
/// account procedure (so that `caller` is not a procedure of the account) must be rejected by the
/// authenticator. This models what an untrusted transaction script could attempt.
#[tokio::test]
async fn test_native_account_upgrade_from_tx_script_is_rejected() -> anyhow::Result<()> {
    let code_upgrade_commitment = Word::from([1, 2, 3, 4u32]);
    let storage_upgrade_commitment = Word::from([5, 6, 7, 8u32]);

    // A transaction script invokes `native_account::upgrade` directly. Its caller is the tx script,
    // not a procedure of the account, so authentication must reject the invocation.
    let tx_script_source = format!(
        r#"
        use miden::protocol::native_account

        @transaction_script
        pub proc main
            push.{storage_upgrade_commitment}
            push.{code_upgrade_commitment}
            # => [NEW_CODE_COMMITMENT, STORAGE_UPGRADE_COMMITMENT]

            exec.native_account::upgrade
        end
        "#,
        code_upgrade_commitment = code_upgrade_commitment,
        storage_upgrade_commitment = storage_upgrade_commitment,
    );
    let tx_script = CodeBuilder::with_mock_packages().compile_tx_script(tx_script_source)?;

    let mock_tx = TestTransactionBuilder::with_existing_mock_account()
        .tx_script(tx_script)
        .build()?;

    let execution_result = mock_tx.execute().await;

    // The tx-script root is not a procedure of the account, so `authenticate_account_origin` fails
    // while resolving the caller's procedure index.
    assert_transaction_executor_error!(
        execution_result,
        matches ExecutionError::EventError { error: ref event_err, .. }
            if matches!(
                event_err.downcast_ref::<TransactionKernelError>(),
                Some(TransactionKernelError::UnknownAccountProcedure(_))
            )
    );

    Ok(())
}

/// This test creates an account with mock storage slots and calls the
/// `compute_storage_commitment` procedure each time the storage is updated.
///
/// Namely, we invoke the `mock_account::compute_storage_commitment` procedure:
/// - Right after the account creation.
/// - After updating the 0th storage slot (value slot).
/// - Right after the previous call to make sure it returns the same commitment from the cached
///   data.
/// - After updating the 2nd storage slot (map slot).
#[tokio::test]
async fn test_compute_storage_commitment() -> anyhow::Result<()> {
    let mock_tx = TestTransactionBuilder::with_existing_mock_account().build().unwrap();
    let mut account_clone = mock_tx.account().clone();
    let account_storage = account_clone.storage_mut();

    let init_storage_commitment = account_storage.to_commitment();

    let mock_value_slot0 = &*MOCK_VALUE_SLOT0;
    let value_slot0 = Word::from([9, 10, 11, 12u32]);

    let mock_map_slot = &*MOCK_MAP_SLOT;
    let map_key = StorageMapKey::from_array([101, 102, 103, 104u32]);
    let map_value = Word::from([5, 6, 7, 8u32]);

    account_storage.set_item(mock_value_slot0, value_slot0)?;
    let storage_commitment_value = account_storage.to_commitment();

    account_storage.set_map_item(mock_map_slot, map_key, map_value)?;
    let storage_commitment_map = account_storage.to_commitment();

    let code = format!(
        r#"
        use miden::tx_kernel_core::prologue
        use mock::account as mock_account

        const MOCK_VALUE_SLOT0=word("{mock_value_slot0}")
        const MOCK_MAP_SLOT=word("{mock_map_slot}")

        begin
            exec.prologue::prepare_transaction

            # assert the correctness of the initial storage commitment
            call.mock_account::compute_storage_commitment
            push.{init_storage_commitment}
            assert_eqw.err="storage commitment at the beginning of the transaction is not equal to the expected one"

            # update the value storage slot
            push.{value_slot0}
            push.MOCK_VALUE_SLOT0[0..2]
            call.mock_account::set_item dropw drop
            # => []

            # assert the correctness of the storage commitment after the value slot was updated
            call.mock_account::compute_storage_commitment
            push.{storage_commitment_value}
            assert_eqw.err="storage commitment after the value slot was updated is not equal to the expected one"

            # get the storage commitment once more to get the cached data and assert that this data
            # didn't change
            call.mock_account::compute_storage_commitment
            push.{storage_commitment_value}
            assert_eqw.err="storage commitment should remain the same"

            # update the map storage slot
            push.{map_value}
            push.{map_key}
            push.MOCK_MAP_SLOT[0..2]
            # => [slot_id_suffix, slot_id_prefix, KEY, VALUE]

            call.mock_account::set_map_item dropw dropw
            # => []

            # assert the correctness of the storage commitment after the map slot was updated
            call.mock_account::compute_storage_commitment
            push.{storage_commitment_map}
            assert_eqw.err="storage commitment after the map slot was updated is not equal to the expected one"
        end
        "#,
    );

    mock_tx.execute_code(&code).await?;

    Ok(())
}

/// Tests that an account with a non-empty map can be created.
///
/// In particular, this tests the account delta logic for (non-empty) storage slots for _new_
/// accounts.
#[tokio::test]
async fn prove_account_creation_with_non_empty_storage() -> anyhow::Result<()> {
    let slot_name0 = StorageSlotName::mock(0);
    let slot_name1 = StorageSlotName::mock(1);
    let slot_name2 = StorageSlotName::mock(2);

    let slot0 = StorageSlot::with_value(slot_name0.clone(), Word::from([1, 2, 3, 4u32]));
    let slot1 = StorageSlot::with_value(slot_name1.clone(), Word::from([10, 20, 30, 40u32]));
    let mut map_entries = Vec::new();
    for _ in 0..10 {
        map_entries.push((StorageMapKey::from_raw(random::<Word>()), random::<Word>()));
    }
    let map_slot =
        StorageSlot::with_map(slot_name2.clone(), StorageMap::with_entries(map_entries.clone())?);

    let account = AccountBuilder::new([6; 32])
        .account_type(AccountType::Public)
        .with_components(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_slots(vec![
            slot0.clone(),
            slot1.clone(),
            map_slot,
        ]))
        .build()?;

    let tx = TestTransactionBuilder::new(account)
        .build()?
        .execute()
        .await
        .context("failed to execute account-creating transaction")?;

    assert_eq!(
        tx.account_patch().final_nonce(),
        Some(Felt::ONE),
        "new account should have nonce 1"
    );

    assert_matches!(
        tx.account_patch().storage().get(&slot_name0).unwrap(),
        StorageSlotPatch::Value(StorageValuePatch::Create { value }) => {
            assert_eq!(*value, slot0.value())
        }
    );
    assert_matches!(
        tx.account_patch().storage().get(&slot_name1).unwrap(),
        StorageSlotPatch::Value(StorageValuePatch::Create { value }) => {
            assert_eq!(*value, slot1.value())
        }
    );
    assert_matches!(
        tx.account_patch().storage().get(&slot_name2).unwrap(),
        StorageSlotPatch::Map(StorageMapPatch::Create { entries }) => {
            let expected = &BTreeMap::from_iter(map_entries);
            assert_eq!(expected, entries.as_map())
        }
    );

    assert!(tx.account_patch().vault().is_empty());
    assert_eq!(tx.final_account().nonce(), Felt::ONE);

    let proven_tx = LocalTransactionProver::default().prove(tx.clone())?;

    // The patch should be present on the proven tx.
    let patch = proven_tx.account_update().details().unwrap_public();
    assert_eq!(patch, tx.account_patch());

    Ok(())
}

// ACCOUNT VAULT TESTS
// ================================================================================================

#[tokio::test]
async fn test_get_vault_root() -> anyhow::Result<()> {
    let mock_tx = TestTransactionBuilder::with_existing_mock_account().build()?;

    let mut account = mock_tx.account().clone();

    let fungible_asset = Asset::from(
        FungibleAsset::new(
            AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).context("id should be valid")?,
            5,
        )
        .context("fungible_asset_0 is invalid")?,
    );

    // get the initial vault root
    let code = format!(
        r#"
        use mock::account as mock_account
        use miden::tx_kernel_core::prologue

        begin
            exec.prologue::prepare_transaction

            # get the initial vault root
            call.mock_account::get_initial_vault_root
            # => [INIT_VAULT_ROOT, pad(12)]
            swapdw dropw dropw swapw dropw
            # => [INIT_VAULT_ROOT]
            push.{expected_vault_root}
            assert_eqw.err="initial vault root mismatch"
        end
        "#,
        expected_vault_root = account.vault().root(),
    );
    mock_tx.execute_code(&code).await?;

    // get the current vault root
    account.vault_mut().add_asset(fungible_asset)?;

    let code = format!(
        r#"
        use miden::protocol::active_account
        use miden::tx_kernel_core::prologue
        use mock::account as mock_account

        begin
            exec.prologue::prepare_transaction

            # add an asset to the account
            push.{FUNGIBLE_ASSET_VALUE}
            push.{FUNGIBLE_ASSET_ID}
            call.mock_account::add_asset
            dropw dropw
            # => []

            # get the current vault root
            call.mock_account::get_vault_root
            # => [VAULT_ROOT, pad(12)]
            swapdw dropw dropw swapw dropw
            # => [VAULT_ROOT]
            push.{expected_vault_root}
            assert_eqw.err="vault root mismatch"
        end
        "#,
        FUNGIBLE_ASSET_VALUE = fungible_asset.to_value_word(),
        FUNGIBLE_ASSET_ID = fungible_asset.to_id_word(),
        expected_vault_root = account.vault().root(),
    );
    mock_tx.execute_code(&code).await?;

    Ok(())
}

/// This test checks the correctness of the
/// `miden::standards::assets::fungible_asset::get_initial_native_account_balance` procedure in two
/// cases:
/// - when a note adds the asset which already exists in the account vault.
/// - when a note adds the asset which doesn't exist in the account vault.
///
/// As part of the test pipeline it also checks the correctness of the
/// `miden::standards::assets::fungible_asset::get_active_account_balance` procedure.
#[tokio::test]
async fn test_get_init_balance_addition() -> anyhow::Result<()> {
    // prepare the testing data
    // ------------------------------------------
    let mut builder = MockChain::builder();

    let faucet_existing_asset =
        AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).context("id should be valid")?;
    let faucet_new_asset =
        AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET_1).context("id should be valid")?;

    let fungible_asset_for_account = Asset::from(
        FungibleAsset::new(faucet_existing_asset, 10).context("fungible_asset_0 is invalid")?,
    );
    let account = builder.add_existing_mock_account_with_assets(
        crate::Auth::BasicAuth {
            auth_scheme: AuthScheme::Falcon512Poseidon2,
        },
        [fungible_asset_for_account],
    )?;

    let fungible_asset_for_note_existing = Asset::from(
        FungibleAsset::new(faucet_existing_asset, 7).context("fungible_asset_0 is invalid")?,
    );

    let fungible_asset_for_note_new = Asset::from(
        FungibleAsset::new(faucet_new_asset, 20).context("fungible_asset_1 is invalid")?,
    );

    let p2id_note_existing_asset = builder.add_p2id_note(
        ACCOUNT_ID_SENDER.try_into().unwrap(),
        account.id(),
        &[fungible_asset_for_note_existing],
        NoteType::Public,
    )?;
    let p2id_note_new_asset = builder.add_p2id_note(
        ACCOUNT_ID_SENDER.try_into().unwrap(),
        account.id(),
        &[fungible_asset_for_note_new],
        NoteType::Public,
    )?;

    let mut mock_chain = builder.build()?;
    mock_chain.prove_next_block()?;

    // case 1: existing asset was added to the account
    // ------------------------------------------

    let asset_id = AssetId::new_fungible(faucet_existing_asset);
    let initial_balance = account.vault().get_balance(asset_id)?.as_u64();

    let add_existing_source = format!(
        r#"
        use miden::core::sys
        use mock::account as mock_account

        @transaction_script
        pub proc main
            # get the current asset balance
            push.{ASSET_ID}
            call.mock_account::get_active_account_balance
            # => [final_balance, pad(15)]

            # assert final balance is correct
            push.{final_balance}
            assert_eq.err="final balance is incorrect"
            # => []

            # get the initial asset balance
            push.{ASSET_ID}
            call.mock_account::get_initial_native_account_balance
            # => [init_balance, pad(15)]

            # assert initial balance is correct
            push.{initial_balance}
            assert_eq.err="initial balance is incorrect"

            # truncate the stack
            exec.sys::truncate_stack
        end
    "#,
        ASSET_ID = asset_id.to_word(),
        final_balance =
            initial_balance + fungible_asset_for_note_existing.unwrap_fungible().amount().as_u64(),
    );

    let tx_script = CodeBuilder::with_mock_packages().compile_tx_script(add_existing_source)?;

    let mock_tx = mock_chain
        .build_transaction(account.id())
        .unauthenticated_input_note(p2id_note_existing_asset)
        .tx_script(tx_script)
        .build()?;

    mock_tx.execute().await?;

    // case 2: new asset was added to the account
    // ------------------------------------------

    let asset_id = AssetId::new_fungible(faucet_new_asset);
    let initial_balance = account.vault().get_balance(asset_id)?.as_u64();

    let add_new_source = format!(
        r#"
        use miden::core::sys
        use mock::account as mock_account

        @transaction_script
        pub proc main
            # get the current asset balance
            push.{ASSET_ID}
            call.mock_account::get_active_account_balance
            # => [final_balance, pad(15)]

            # assert final balance is correct
            push.{final_balance}
            assert_eq.err="final balance is incorrect"
            # => []

            # get the initial asset balance
            push.{ASSET_ID}
            call.mock_account::get_initial_native_account_balance
            # => [init_balance, pad(15)]

            # assert initial balance is correct
            push.{initial_balance}
            assert_eq.err="initial balance is incorrect"

            # truncate the stack
            exec.sys::truncate_stack
        end
    "#,
        ASSET_ID = asset_id.to_word(),
        final_balance =
            initial_balance + fungible_asset_for_note_new.unwrap_fungible().amount().as_u64(),
    );

    let tx_script = CodeBuilder::with_mock_packages().compile_tx_script(add_new_source)?;

    let mock_tx = mock_chain
        .build_transaction(account.id())
        .unauthenticated_input_note(p2id_note_new_asset)
        .tx_script(tx_script)
        .build()?;

    mock_tx.execute().await?;

    Ok(())
}

/// This test checks the correctness of the
/// `miden::standards::assets::fungible_asset::get_initial_native_account_balance` procedure when an
/// asset is moved from the vault to a note.
///
/// As part of the test pipeline it also checks the correctness of the
/// `miden::standards::assets::fungible_asset::get_active_account_balance` procedure.
#[tokio::test]
async fn test_get_init_balance_subtraction() -> anyhow::Result<()> {
    let mut builder = MockChain::builder();

    let faucet_existing_asset =
        AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).context("id should be valid")?;

    let fungible_asset_for_account = Asset::from(
        FungibleAsset::new(faucet_existing_asset, 10).context("fungible_asset_0 is invalid")?,
    );
    let account = builder.add_existing_mock_account_with_assets(
        crate::Auth::BasicAuth {
            auth_scheme: AuthScheme::Falcon512Poseidon2,
        },
        [fungible_asset_for_account],
    )?;

    let fungible_asset_for_note_existing = Asset::from(
        FungibleAsset::new(faucet_existing_asset, 7).context("fungible_asset_0 is invalid")?,
    );

    let mut mock_chain = builder.build()?;
    mock_chain.prove_next_block()?;

    let asset_id = AssetId::new_fungible(faucet_existing_asset);
    let initial_balance = account.vault().get_balance(asset_id)?.as_u64();

    let expected_output_note =
        create_public_p2any_note(ACCOUNT_ID_SENDER.try_into()?, [fungible_asset_for_note_existing]);

    let remove_existing_source = format!(
        r#"
        use miden::core::sys
        use mock::account as mock_account
        use mock::util

        @transaction_script
        pub proc main
            # create random note and move the asset into it
            exec.util::create_default_note
            # => [note_idx]

            push.{REMOVED_ASSET_VALUE}
            push.{REMOVED_ASSET_ID}
            exec.util::move_asset_to_note
            # => []

            # get the current asset balance
            push.{ASSET_ID}
            call.mock_account::get_active_account_balance
            # => [final_balance, pad(15)]

            # assert final balance is correct
            push.{final_balance}
            assert_eq.err="final balance is incorrect"
            # => []

            # get the initial asset balance
            push.{ASSET_ID}
            call.mock_account::get_initial_native_account_balance
            # => [init_balance, pad(15)]

            # assert initial balance is correct
            push.{initial_balance}
            assert_eq.err="initial balance is incorrect"

            # truncate the stack
            exec.sys::truncate_stack
        end
    "#,
        REMOVED_ASSET_ID = fungible_asset_for_note_existing.to_id_word(),
        REMOVED_ASSET_VALUE = fungible_asset_for_note_existing.to_value_word(),
        ASSET_ID = asset_id.to_word(),
        final_balance =
            initial_balance - fungible_asset_for_note_existing.unwrap_fungible().amount().as_u64(),
    );

    let tx_script = CodeBuilder::with_mock_packages().compile_tx_script(remove_existing_source)?;

    let mock_tx = mock_chain
        .build_transaction(account.id())
        .tx_script(tx_script)
        .expected_output_note(RawOutputNote::Full(expected_output_note))
        .build()?;

    mock_tx.execute().await?;

    Ok(())
}

/// This test checks the correctness of the `miden::protocol::native_account::get_initial_asset`
/// procedure creating a note which removes an asset from the account vault.
///
/// As part of the test pipeline it also checks the correctness of the
/// `miden::protocol::active_account::get_asset` procedure.
#[tokio::test]
async fn test_get_init_asset() -> anyhow::Result<()> {
    let mut builder = MockChain::builder();

    let faucet_existing_asset =
        AccountId::try_from(ACCOUNT_ID_PUBLIC_FUNGIBLE_FAUCET).context("id should be valid")?;

    let fungible_asset_for_account = Asset::from(
        FungibleAsset::new(faucet_existing_asset, 10).context("fungible_asset_0 is invalid")?,
    );
    let account = builder.add_existing_mock_account_with_assets(
        crate::Auth::BasicAuth {
            auth_scheme: AuthScheme::Falcon512Poseidon2,
        },
        [fungible_asset_for_account],
    )?;

    let fungible_asset_for_note_existing = Asset::from(
        FungibleAsset::new(faucet_existing_asset, 7).context("fungible_asset_0 is invalid")?,
    );

    let mut mock_chain = builder.build()?;
    mock_chain.prove_next_block()?;

    let final_asset = fungible_asset_for_account
        .unwrap_fungible()
        .sub(fungible_asset_for_note_existing.unwrap_fungible())?;

    let expected_output_note =
        create_public_p2any_note(ACCOUNT_ID_SENDER.try_into()?, [fungible_asset_for_note_existing]);

    let remove_existing_source = format!(
        r#"
        use miden::core::sys
        use miden::protocol::active_account
        use miden::protocol::native_account
        use mock::account as mock_account
        use mock::util

        @transaction_script
        pub proc main
            # create default note and move the asset into it
            exec.util::create_default_note
            # => [note_idx]

            push.{REMOVED_ASSET_VALUE}
            push.{ASSET_ID}
            exec.util::move_asset_to_note
            # => []

            # get the current asset
            push.{ASSET_ID} call.mock_account::get_asset
            # => [ASSET_VALUE, pad(12)]

            push.{FINAL_ASSET}
            assert_eqw.err="final asset is incorrect"
            # => [pad(12)]

            # get the initial asset
            push.{ASSET_ID} call.mock_account::get_initial_asset
            # => [INITIAL_ASSET, pad(12)]

            push.{INITIAL_ASSET_VALUE}
            assert_eqw.err="initial asset is incorrect"

            # truncate the stack
            exec.sys::truncate_stack
        end
    "#,
        ASSET_ID = fungible_asset_for_note_existing.to_id_word(),
        REMOVED_ASSET_VALUE = fungible_asset_for_note_existing.to_value_word(),
        INITIAL_ASSET_VALUE = fungible_asset_for_account.to_value_word(),
        FINAL_ASSET = final_asset.to_value_word(),
    );

    let tx_script = CodeBuilder::with_mock_packages().compile_tx_script(remove_existing_source)?;

    mock_chain
        .build_transaction(account.id())
        .tx_script(tx_script)
        .expected_output_note(RawOutputNote::Full(expected_output_note))
        .build()?
        .execute()
        .await?;

    Ok(())
}

// PROCEDURE AUTHENTICATION TESTS
// ================================================================================================

#[tokio::test]
async fn test_authenticate_procedure() -> anyhow::Result<()> {
    let mock_component = MockAccountComponent::with_empty_slots();

    let components: Vec<AccountComponent> =
        Auth::IncrNonce.into_iter().chain([mock_component.into()]).collect();
    let account_code = AccountCode::from_components(&components).unwrap();

    let tc_0 = *account_code.procedures()[1].mast_root();
    let tc_1 = *account_code.procedures()[2].mast_root();
    let tc_2 = *account_code.procedures()[3].mast_root();

    let test_cases =
        vec![(tc_0, true), (tc_1, true), (tc_2, true), (Word::from([1, 0, 1, 0u32]), false)];

    for (root, valid) in test_cases.into_iter() {
        let mock_tx = TestTransactionBuilder::with_existing_mock_account().build().unwrap();

        let code = format!(
            "
            use miden::tx_kernel_core::account
            use miden::tx_kernel_core::prologue

            begin
                exec.prologue::prepare_transaction

                # authenticate procedure
                push.{root}
                exec.account::authenticate_procedure

                # truncate the stack
                dropw
            end
            ",
            root = root,
        );

        // Execution of this code will return an EventError(UnknownAccountProcedure) for procs
        // that are not in the advice provider.
        let exec_output = mock_tx.execute_code(&code).await;

        match valid {
            true => {
                assert!(exec_output.is_ok(), "A valid procedure must successfully authenticate")
            },
            false => {
                assert!(exec_output.is_err(), "An invalid procedure should fail to authenticate")
            },
        }
    }

    Ok(())
}

// PROCEDURE INTROSPECTION TESTS
// ================================================================================================

#[tokio::test]
async fn test_was_procedure_called() -> anyhow::Result<()> {
    // Create a standard account using the mock component
    let mock_component = MockAccountComponent::with_slots(AccountStorage::mock_storage_slots());
    let account = AccountBuilder::new(rand::random())
        .with_components(Auth::IncrNonce)
        .with_component(mock_component)
        .build_existing()
        .unwrap();
    let mock_value_slot1 = &*MOCK_VALUE_SLOT1;

    // Verifies the call-tracking of an account procedure: `get_item` is tracked as called once it
    // has been invoked. `was_procedure_called` is itself account-context-gated, so it is invoked
    // through the account.
    let tx_script_code = format!(
        r#"
        use miden::core::sys
        use mock::account as mock_account

        const MOCK_VALUE_SLOT1 = word("{mock_value_slot1}")

        @transaction_script
        pub proc main
            # First check that get_item procedure hasn't been called yet
            procref.mock_account::get_item
            call.mock_account::was_procedure_called
            assertz.err="procedure should not have been called"

            # Call the procedure first time
            push.MOCK_VALUE_SLOT1[0..2]
            call.mock_account::get_item dropw

            procref.mock_account::get_item
            call.mock_account::was_procedure_called
            assert.err="procedure should have been called"

            # Call the procedure second time
            push.MOCK_VALUE_SLOT1[0..2]
            call.mock_account::get_item dropw

            procref.mock_account::get_item
            call.mock_account::was_procedure_called
            assert.err="2nd call should not change the was_called flag"

            exec.sys::truncate_stack
        end
        "#
    );

    // Compile the transaction script using the testing assembler with mock account
    let tx_script = CodeBuilder::with_mock_packages().compile_tx_script(tx_script_code)?;

    // Create mock transaction and execute
    let mock_tx = TestTransactionBuilder::new(account).tx_script(tx_script).build().unwrap();

    mock_tx.execute().await?;

    Ok(())
}

/// Tests that an account can call code in a custom package when loading that package into the
/// executor.
///
/// The call chain and dependency graph in this test is:
/// `tx script -> account code -> external package`
#[tokio::test]
async fn transaction_executor_account_code_using_custom_package() -> anyhow::Result<()> {
    let slot_value = Word::from([2, 3, 4, 5u32]);
    let external_package_code = format!(
        r#"
      use miden::protocol::native_account

      const MOCK_VALUE_SLOT0 = word("{mock_value_slot0}")

      pub proc external_setter
        push.{slot_value}
        push.MOCK_VALUE_SLOT0[0..2]
        exec.native_account::set_item
        dropw dropw
      end"#,
        mock_value_slot0 = *MOCK_VALUE_SLOT0,
    );

    const ACCOUNT_COMPONENT_CODE: &str = "
      use external_package::external_module

      @account_procedure
      pub proc custom_setter
        exec.external_module::external_setter
      end";

    let source_manager = Arc::new(DefaultSourceManager::default());
    let mut parser = ModuleParser::new(Some(ModuleKind::Library));
    let external_package_root = parser
        .parse_str(
            Some(Path::new("external_package::external_module")),
            &external_package_code,
            source_manager.clone(),
        )
        .map_err(|err| {
            anyhow::anyhow!("failed to parse package: {}", PrintDiagnostic::new(&err))
        })?;
    let external_package = TransactionKernel::assembler_with_source_manager(source_manager.clone())
        .assemble_library("external-library", external_package_root, None::<&str>)
        .map_err(|err| {
            anyhow::anyhow!("failed to assemble package: {}", PrintDiagnostic::new(&err))
        })?;

    let assembler: miden_protocol::assembly::Assembler =
        CodeBuilder::with_mock_packages_with_source_manager(source_manager.clone()).into();
    let assembler =
        assembler
            .with_package(Arc::from(external_package), Linkage::Static)
            .map_err(|err| {
                anyhow::anyhow!("failed to link static package: {}", PrintDiagnostic::new(&err))
            })?;

    let account_component_root = parser
        .parse_str(
            Some(Path::new("account_component::account_module")),
            ACCOUNT_COMPONENT_CODE,
            source_manager,
        )
        .map_err(|err| {
            anyhow::anyhow!("failed to parse account component: {}", PrintDiagnostic::new(&err))
        })?;
    let account_component_lib = *assembler
        .clone()
        .assemble_library("account-component", account_component_root, None::<&str>)
        .unwrap();

    let tx_script_src = "\
          use account_component::account_module

          @transaction_script
          pub proc main
            call.account_module::custom_setter
          end";

    let account_component = AccountComponent::new(
        account_component_lib.clone(),
        AccountStorage::mock_storage_slots(),
        AccountComponentMetadata::mock("account_module"),
    )?;

    // Build an existing account with nonce 1.
    let native_account = AccountBuilder::new(rand::random())
        .with_components(Auth::IncrNonce)
        .with_component(account_component)
        .build_existing()?;

    let tx_script = CodeBuilder::default()
        .with_dynamically_linked_package(&account_component_lib)?
        .compile_tx_script(tx_script_src)?;

    let mock_tx = TestTransactionBuilder::new(native_account.clone())
        .tx_script(tx_script)
        .build()
        .unwrap();

    let executed_tx = mock_tx.execute().await?;

    // Account's initial nonce of 1 should have been incremented by 1.
    assert_eq!(
        executed_tx.account_patch().final_nonce(),
        Some(native_account.nonce() + Felt::ONE)
    );

    // Make sure that account storage has been updated as per the tx script call.
    assert_eq!(executed_tx.account_patch().storage().values().count(), 1);
    assert_eq!(
        executed_tx.account_patch().storage().get(&MOCK_VALUE_SLOT0).unwrap(),
        &StorageSlotPatch::Value(StorageValuePatch::Update { value: slot_value }),
    );
    Ok(())
}

/// Tests that incrementing the account nonce twice fails.
#[tokio::test]
async fn incrementing_nonce_twice_fails() -> anyhow::Result<()> {
    let source_code = "
        use miden::protocol::native_account

        @auth_script
        pub proc auth_incr_nonce_twice
            exec.native_account::incr_nonce drop
            exec.native_account::incr_nonce drop
        end
    ";

    let faulty_auth_code =
        CodeBuilder::default().compile_component_code("test::faulty_auth", source_code)?;
    let faulty_auth_component = AccountComponent::new(
        faulty_auth_code,
        vec![],
        AccountComponentMetadata::mock("test::faulty_auth"),
    )?;
    let account = AccountBuilder::new([5; 32])
        .with_component(faulty_auth_component)
        .with_component(MockAccountComponent::with_empty_slots())
        .build()
        .context("failed to build account")?;

    let result = TestTransactionBuilder::new(account).build()?.execute().await;

    assert_transaction_executor_error!(result, ERR_ACCOUNT_NONCE_CAN_ONLY_BE_INCREMENTED_ONCE);

    Ok(())
}

#[tokio::test]
async fn test_has_procedure() -> anyhow::Result<()> {
    // Create a standard account using the mock component
    let mock_component = MockAccountComponent::with_slots(AccountStorage::mock_storage_slots());
    let account = AccountBuilder::new(rand::random())
        .with_components(Auth::IncrNonce)
        .with_component(mock_component)
        .build_existing()
        .unwrap();

    let tx_script_code = r#"
        use miden::core::sys
        use mock::account as mock_account

        @transaction_script
        pub proc main
            # check that get_item procedure is available on the mock account
            procref.mock_account::get_item
            # => [GET_ITEM_ROOT]

            call.mock_account::has_procedure
            # => [is_procedure_available, pad(15)]

            # assert that the get_item is exposed
            assert.err="get_item procedure should be exposed by the mock account"

            # get some random word and assert that it is not exposed
            push.5.3.15.686

            call.mock_account::has_procedure
            # => [is_procedure_available, pad(15)]

            # assert that the procedure with some random root is not exposed
            assertz.err="procedure with some random root should not be exposed by the mock account"

            exec.sys::truncate_stack
        end
        "#;

    // Compile the transaction script using the testing assembler with mock account
    let tx_script = CodeBuilder::with_mock_packages()
        .compile_tx_script(tx_script_code)
        .map_err(|err| anyhow::anyhow!("{err}"))?;

    // Create mock transaction and execute
    let mock_tx = TestTransactionBuilder::new(account).tx_script(tx_script).build().unwrap();

    mock_tx.execute().await?;

    Ok(())
}

#[tokio::test]
async fn test_has_storage_slot() -> anyhow::Result<()> {
    let existing_slot_name = format!("{}", AccountStorage::mock_value_slot0().name());

    // (slot name, whether a slot with that name is expected to exist on the account)
    let test_cases = [(existing_slot_name.as_str(), true), ("unknown::slot::name", false)];

    for (slot_name, expected_to_exist) in test_cases {
        let mock_tx = TestTransactionBuilder::with_existing_mock_account().build().unwrap();

        let assertion = if expected_to_exist {
            r#"assert.err="installed storage slot should be reported as present""#
        } else {
            r#"assertz.err="unknown storage slot should be reported as absent""#
        };

        let code = format!(
            r#"
            use miden::core::sys

            use miden::tx_kernel_core::prologue
            use mock::account as mock_account

            const SLOT_NAME = word("{slot_name}")

            begin
                exec.prologue::prepare_transaction

                # pad the stack for the call
                push.SLOT_NAME[0..2]
                repeat.14 push.0 movdn.2 end
                # => [slot_id_suffix, slot_id_prefix, pad(14)]

                call.mock_account::has_storage_slot
                # => [has_slot, pad(15)]

                {assertion}

                exec.sys::truncate_stack
            end
            "#,
        );

        mock_tx.execute_code(&code).await?;
    }

    Ok(())
}

// ACCOUNT INITIAL STORAGE TESTS
// ================================================================================================

#[tokio::test]
async fn test_get_initial_item() -> anyhow::Result<()> {
    let mock_tx = TestTransactionBuilder::with_existing_mock_account().build().unwrap();

    // Test that get_initial_item returns the initial value before any changes
    let code = format!(
        r#"
        use miden::tx_kernel_core::account
        use miden::tx_kernel_core::prologue
        use mock::account as mock_account

        const MOCK_VALUE_SLOT0 = word("{mock_value_slot0}")

        begin
            exec.prologue::prepare_transaction

            # get initial value of the storage slot
            push.MOCK_VALUE_SLOT0[0..2]
            exec.account::get_initial_item

            push.{expected_initial_value}
            assert_eqw.err="initial value should match expected"

            # modify the storage slot
            push.9.10.11.12
            push.MOCK_VALUE_SLOT0[0..2]
            call.mock_account::set_item dropw drop drop

            # get_item should return the new value
            push.MOCK_VALUE_SLOT0[0..2]
            exec.account::get_item
            push.9.10.11.12
            assert_eqw.err="current value should be updated"

            # get_initial_item should still return the initial value
            push.MOCK_VALUE_SLOT0[0..2]
            exec.account::get_initial_item
            push.{expected_initial_value}
            assert_eqw.err="initial value should remain unchanged"
        end
        "#,
        mock_value_slot0 = *MOCK_VALUE_SLOT0,
        expected_initial_value = AccountStorage::mock_value_slot0().content().value(),
    );

    mock_tx.execute_code(&code).await?;

    Ok(())
}

#[tokio::test]
async fn test_get_initial_map_item() -> anyhow::Result<()> {
    let map_slot = AccountStorage::mock_map_slot();
    let account = AccountBuilder::new(rand::random())
        .with_components(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_slots(vec![map_slot.clone()]))
        .build_existing()
        .unwrap();

    let mock_tx = TestTransactionBuilder::new(account).build().unwrap();

    // Use the first key-value pair from the mock storage
    let StorageSlotContent::Map(map) = map_slot.content() else {
        panic!("expected map");
    };

    let (initial_key, initial_value) = map.entries().next().unwrap();
    let new_key = Word::from([201, 202, 203, 204u32]);
    let new_value = Word::from([301, 302, 303, 304u32]);
    let mock_map_slot = map_slot.name();

    let code = format!(
        r#"
        use miden::tx_kernel_core::prologue
        use mock::account as mock_account

        const MOCK_MAP_SLOT = word("{mock_map_slot}")

        begin
            exec.prologue::prepare_transaction

            # get initial value from map
            push.{initial_key}
            push.MOCK_MAP_SLOT[0..2]
            call.mock_account::get_initial_map_item
            push.{initial_value}
            assert_eqw.err="initial map value should match expected"

            # add a new key-value pair to the map
            push.{new_value}
            push.{new_key}
            push.MOCK_MAP_SLOT[0..2]
            call.mock_account::set_map_item dropw dropw

            # get_map_item should return the new value
            push.{new_key}
            push.MOCK_MAP_SLOT[0..2]
            call.mock_account::get_map_item
            push.{new_value}
            assert_eqw.err="current map value should be updated"

            # get_initial_map_item should still return the initial value for the initial key
            push.{initial_key}
            push.MOCK_MAP_SLOT[0..2]
            call.mock_account::get_initial_map_item
            push.{initial_value}
            assert_eqw.err="initial map value should remain unchanged"

            # get_initial_map_item for the new key should return empty word (default)
            push.{new_key}
            push.MOCK_MAP_SLOT[0..2]
            call.mock_account::get_initial_map_item
            padw
            assert_eqw.err="new key should have empty initial value"

            dropw dropw dropw
        end
        "#,
        initial_key = initial_key,
        initial_value = initial_value,
        new_key = new_key,
        new_value = new_value,
    );

    mock_tx.execute_code(&code).await.unwrap();

    Ok(())
}

/// Tests that `get_initial_item` returns the original slot values and `get_item` returns updated
/// values after modification, for all possible storage slot indices.
#[tokio::test]
async fn test_get_item_and_get_initial_item_for_all_slots() -> anyhow::Result<()> {
    // Build storage slots for all valid indices.
    let slots: Vec<StorageSlot> = (0..AccountStorage::MAX_NUM_STORAGE_SLOTS as u32)
        .map(|index| {
            StorageSlot::with_value(
                StorageSlotName::mock(index as usize),
                Word::from([0, 0, 0, index]),
            )
        })
        .collect();

    let account = AccountBuilder::new(rand::random())
        .with_components(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_slots(slots.clone()))
        .build_existing()
        .unwrap();

    let mock_tx = TestTransactionBuilder::new(account).build().unwrap();

    // Build MASM code that, for each slot:
    // 1. Sets a new value [index, 0, 0, 0]
    // 2. Asserts get_initial_item returns the original value [0, 0, 0, index]
    // 3. Asserts get_item returns the new value [index, 0, 0, 0]
    let mut slot_constants = String::new();
    let mut slot_operations = String::new();

    for (index, slot) in slots.iter().enumerate() {
        let slot_name = slot.name();
        let initial_value = slot.value();
        // Use a different format than the initial value (index at word position 0).
        let new_value = Word::from([index as u32, 0, 0, 0]);
        let const_name = format!("SLOT_{index}");

        slot_constants.push_str(&format!("const {const_name} = word(\"{slot_name}\")\n"));

        slot_operations.push_str(&format!(
            r#"
                # slot {index}: set new value
                push.{new_value}
                push.{const_name}[0..2]
                call.mock_account::set_item dropw drop drop

                # slot {index}: assert get_initial_item returns original value
                push.{const_name}[0..2]
                exec.account::get_initial_item
                push.{initial_value}
                assert_eqw.err="slot {index}: initial value mismatch"

                # slot {index}: assert get_item returns the new value
                push.{const_name}[0..2]
                exec.account::get_item
                push.{new_value}
                assert_eqw.err="slot {index}: current value mismatch"
            "#,
        ));
    }

    let code = format!(
        r#"
        use miden::tx_kernel_core::account
        use miden::tx_kernel_core::prologue
        use mock::account as mock_account

        {slot_constants}

        begin
            exec.prologue::prepare_transaction
            {slot_operations}
        end
        "#,
    );

    mock_tx.execute_code(&code).await?;

    Ok(())
}

/// Tests that incrementing the account nonce fails if it would overflow the field.
#[tokio::test]
async fn incrementing_nonce_overflow_fails() -> anyhow::Result<()> {
    let mut account = AccountBuilder::new([42; 32])
        .with_components(Auth::IncrNonce)
        .with_component(MockAccountComponent::with_empty_slots())
        .build_existing()
        .context("failed to build account")?;
    // Increment the nonce to the maximum felt value. The nonce is already 1, so we increment by
    // modulus - 2.
    account.increment_nonce(Felt::new_unchecked(Felt::ORDER_U64 - 2))?;

    let result = TestTransactionBuilder::new(account).build()?.execute().await;

    assert_transaction_executor_error!(result, ERR_ACCOUNT_NONCE_AT_MAX);

    Ok(())
}

/// Tests that merging two components that have a procedure with the same mast root
/// (`get_slot_content`) works.
///
/// Asserts that the procedure is callable via both names.
#[tokio::test]
async fn merging_components_with_same_mast_root_succeeds() -> anyhow::Result<()> {
    static TEST_SLOT_NAME: LazyLock<StorageSlotName> = LazyLock::new(|| {
        StorageSlotName::new("miden::slot::test").expect("storage slot name should be valid")
    });

    static COMPONENT_1_PACKAGE: LazyLock<Package> = LazyLock::new(|| {
        let code = format!(
            r#"
              use miden::protocol::active_account

              const TEST_SLOT_NAME = word("{test_slot_name}")

              @account_procedure
              pub proc get_slot_content
                  push.TEST_SLOT_NAME[0..2]
                  exec.active_account::get_item
                  swapw dropw
              end
            "#,
            test_slot_name = *TEST_SLOT_NAME
        );

        let source_manager = Arc::new(DefaultSourceManager::default());
        let root = ModuleParser::new(Some(ModuleKind::Library))
            .parse_str(Some(Path::new("component1::interface")), &code, source_manager.clone())
            .expect("mock account code should parse");
        *TransactionKernel::assembler_with_source_manager(source_manager)
            .assemble_library("component1", root, None::<&str>)
            .expect("mock account code should be valid")
    });

    static COMPONENT_2_PACKAGE: LazyLock<Package> = LazyLock::new(|| {
        let code = format!(
            r#"
              use miden::protocol::active_account
              use miden::protocol::native_account

              const TEST_SLOT_NAME = word("{test_slot_name}")

              @account_procedure
              pub proc get_slot_content
                  push.TEST_SLOT_NAME[0..2]
                  exec.active_account::get_item
                  swapw dropw
              end

              @account_procedure
              pub proc set_slot_content
                  push.[5,6,7,8]
                  push.TEST_SLOT_NAME[0..2]
                  exec.native_account::set_item
                  swapw dropw
              end
            "#,
            test_slot_name = *TEST_SLOT_NAME
        );

        let source_manager = Arc::new(DefaultSourceManager::default());
        let root = ModuleParser::new(Some(ModuleKind::Library))
            .parse_str(Some(Path::new("component2::interface")), &code, source_manager.clone())
            .expect("mock account code should parse");
        *TransactionKernel::assembler_with_source_manager(source_manager)
            .assemble_library("component2", root, None::<&str>)
            .expect("mock account code should be valid")
    });

    struct CustomComponent1 {
        slot: StorageSlot,
    }

    impl From<CustomComponent1> for AccountComponent {
        fn from(component: CustomComponent1) -> AccountComponent {
            AccountComponent::new(
                COMPONENT_1_PACKAGE.clone(),
                vec![component.slot],
                AccountComponentMetadata::mock("component1::interface"),
            )
            .expect("should be valid")
        }
    }

    struct CustomComponent2;

    impl From<CustomComponent2> for AccountComponent {
        fn from(_component: CustomComponent2) -> AccountComponent {
            AccountComponent::new(
                COMPONENT_2_PACKAGE.clone(),
                vec![],
                AccountComponentMetadata::mock("component2::interface"),
            )
            .expect("should be valid")
        }
    }

    let slot_content1 = Word::from([1, 2, 3, 4u32]);
    let slot = StorageSlot::with_value(TEST_SLOT_NAME.clone(), slot_content1);

    let account = AccountBuilder::new([42; 32])
        .with_components(Auth::IncrNonce)
        .with_component(CustomComponent1 { slot: slot.clone() })
        .with_component(CustomComponent2)
        .build()
        .context("failed to build account")?;

    let tx_script = format!(
        r#"
      use component1::interface as comp1_interface
      use component2::interface as comp2_interface

      @transaction_script
      pub proc main
          call.comp1_interface::get_slot_content
          push.{slot_content1}
          assert_eqw.err="failed to get slot content1"

          call.comp2_interface::set_slot_content

          call.comp2_interface::get_slot_content
          push.[5,6,7,8]
          assert_eqw.err="failed to get slot content2"
      end
    "#
    );

    let tx_script = CodeBuilder::default()
        .with_dynamically_linked_package(COMPONENT_1_PACKAGE.clone())?
        .with_dynamically_linked_package(COMPONENT_2_PACKAGE.clone())?
        .compile_tx_script(tx_script)?;

    TestTransactionBuilder::new(account)
        .tx_script(tx_script)
        .build()?
        .execute()
        .await?;

    Ok(())
}