solana-runtime 4.2.0-beta.0

Solana runtime
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
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
use {
    super::{
        Bank, CachedVoteAccounts, CalculateValidatorRewardsResult, EpochRewardCalculateParamInfo,
        InflationReward, PartitionedRewardsCalculation, PartitionedStakeReward,
        PartitionedStakeRewards, REWARD_CALCULATION_NUM_BLOCKS, RewardCommission,
        RewardCommissionAccounts, RewardCommissionAccountsStorable, RewardCommissionLamportAmounts,
        RewardCommissions, StakeRewardCalculation,
        epoch_rewards_hasher::hash_rewards_into_partitions,
    },
    crate::{
        alpenglow_epoch_type::{AlpenglowEpochType, RewardEpochDelegatedStakes},
        bank::{
            RewardCalcTracer, RewardCalculationEvent, RewardsMetrics,
            fee_distribution::ExternalCollectorType, null_tracer,
        },
        inflation_rewards::{
            delegation_may_need_adjustment,
            points::{
                CalculationEnvironment, DelegatedVoteState, PointValue, calculate_points_for_tower,
            },
            redeem_rewards,
        },
        reward_info::RewardInfo,
        stake_account::StakeAccount,
        stakes::Stakes,
    },
    log::{debug, info},
    rayon::{
        ThreadPool,
        iter::{IndexedParallelIterator, IntoParallelRefIterator, ParallelIterator},
    },
    solana_account::{ReadableAccount, WritableAccount},
    solana_clock::{Epoch, Slot},
    solana_measure::{measure::Measure, measure_us},
    solana_pubkey::Pubkey,
    solana_reward_info::RewardType,
    solana_stake_interface::{stake_history::StakeHistory, state::Delegation},
    solana_sysvar::epoch_rewards::EpochRewards,
    std::sync::{
        Arc,
        atomic::{AtomicU64, Ordering::Relaxed},
    },
};

#[derive(Debug)]
struct InflationRewardWithCommission {
    inflation: InflationReward,
    commission_pubkey: Pubkey,
    reward_commission: RewardCommission,
}

#[derive(Default)]
struct RewardsAccumulator {
    reward_commissions: RewardCommissions,
    num_stake_rewards: usize,
    total_stake_rewards_lamports: u64,
}

/// Merge the lamport and `is_vote_account` fields of two `RewardCommission`s
///
/// This pays special attention to the case where `is_vote_account` does not
/// match, which can happen in the following situation:
///
/// * a vote account A sets the inflation collector to valid system account B
/// * at some point in the future, that system account B gets allocated and
///   initialized as a vote account B
/// * vote account B sets itself as the inflation reward collector
///
/// In that situation, the rewards for vote account A will get burned, but the
/// rewards for vote account B will not. According to the rules of SIMD-0232,
/// a collector account must either be the vote account itself or a system
/// account that fulfills certain criteria. In the case of vote account A, we
/// are already sure that the collector account is invalid.
///
/// NOTE: if vote account B sets a system account as its inflation collector,
/// then the commission lamports for vote account A will NOT get burned here,
/// but will get burned during `load_and_reward_commission_accounts`
fn accumulate_lamports(src: &RewardCommission, dst: &mut RewardCommission) {
    match (src.is_vote_account, dst.is_vote_account) {
        (false, true) => {
            // Don't accumulate, burn everything in the source
            // reward commission entry.
            //
            // NOTE: There shouldn't be any burned lamports in the
            // source entry, but we're defensive
            dst.burned_lamports = dst
                .burned_lamports
                .saturating_add(src.commission_lamports)
                .saturating_add(src.burned_lamports);
        }
        (true, false) => {
            // The commission lamports on the source are the only
            // ones that get distributed, all others get burned.
            //
            // NOTE: There shouldn't be any burned lamports in the
            // destination entry, but we're defensive
            dst.is_vote_account = true;
            dst.burned_lamports = dst
                .burned_lamports
                .saturating_add(dst.commission_lamports)
                .saturating_add(src.burned_lamports);
            dst.commission_lamports = src.commission_lamports;
        }
        _ => {
            // Normal case, just accumulate both
            dst.commission_lamports = dst
                .commission_lamports
                .saturating_add(src.commission_lamports);
            dst.burned_lamports = dst.burned_lamports.saturating_add(src.burned_lamports);
        }
    }
}

impl RewardsAccumulator {
    fn add_reward(
        &mut self,
        commission_pubkey: Pubkey,
        reward_commission: RewardCommission,
        stakers_reward: u64,
    ) {
        self.reward_commissions
            .entry(commission_pubkey)
            .and_modify(|dst_reward_commission| {
                accumulate_lamports(&reward_commission, dst_reward_commission);
            })
            .or_insert(reward_commission);
        self.num_stake_rewards = self.num_stake_rewards.saturating_add(1);
        self.total_stake_rewards_lamports = self
            .total_stake_rewards_lamports
            .saturating_add(stakers_reward);
    }

    /// Merges two instances by combining their reward commissions and stake rewards.
    ///
    /// To minimize reallocations, the instance with more reward commissions is used
    /// as the base and the smaller instance is merged into it.
    fn accumulate_into_larger(self, rhs: Self) -> Self {
        // Check which instance has more reward commissions. Treat the bigger one
        // as a destination, which is going to be extended. This way we make
        // the reallocation as small as possible.
        let (mut dst, src) = if self.reward_commissions.len() >= rhs.reward_commissions.len() {
            (self, rhs)
        } else {
            (rhs, self)
        };
        for (commission_pubkey, reward_commission) in src.reward_commissions {
            dst.reward_commissions
                .entry(commission_pubkey)
                .and_modify(|dst_reward_commission: &mut RewardCommission| {
                    accumulate_lamports(&reward_commission, dst_reward_commission);
                })
                .or_insert(reward_commission);
        }
        dst.num_stake_rewards = dst.num_stake_rewards.saturating_add(src.num_stake_rewards);
        dst.total_stake_rewards_lamports = dst
            .total_stake_rewards_lamports
            .saturating_add(src.total_stake_rewards_lamports);
        dst
    }
}

impl Bank {
    /// Begin the process of calculating and distributing rewards.
    /// This process can take multiple slots.
    ///
    /// Returns the total rewards that will be distributed in this epoch (to both validators and
    /// stakers) minus rewards sent to the incinerator.  This is the total amount the capitalization
    /// will increase by after all the rewards have been paid.
    pub(in crate::bank) fn begin_partitioned_rewards(
        &mut self,
        parent_epoch: Epoch,
        parent_slot: Slot,
        parent_block_height: u64,
        rewards_calculation: &PartitionedRewardsCalculation,
        rewards_metrics: &mut RewardsMetrics,
        thread_pool: &ThreadPool,
    ) -> u64 {
        let RewardCommissionLamportAmounts {
            distributed_lamports,
            distributed_to_incinerator_lamports,
            burned_lamports,
        } = self.distribute_reward_commissions(
            parent_epoch,
            rewards_calculation,
            rewards_metrics,
            thread_pool,
        );

        let slot = self.slot();
        let distribution_starting_block_height =
            self.block_height() + REWARD_CALCULATION_NUM_BLOCKS;

        let PartitionedRewardsCalculation {
            stake_rewards,
            point_value,
            ..
        } = rewards_calculation;

        let stake_rewards = Arc::clone(&stake_rewards.stake_rewards);

        let num_partitions = self.get_reward_distribution_num_blocks(&stake_rewards);
        self.set_epoch_reward_status_calculation(distribution_starting_block_height, stake_rewards);

        self.create_epoch_rewards_sysvar(
            distributed_lamports + distributed_to_incinerator_lamports + burned_lamports,
            distribution_starting_block_height,
            num_partitions,
            point_value,
            0, // block_rewards
        );

        datapoint_info!(
            "epoch-rewards-status-update",
            ("start_slot", slot, i64),
            ("calculation_block_height", self.block_height(), i64),
            ("active", 1, i64),
            ("parent_slot", parent_slot, i64),
            ("parent_block_height", parent_block_height, i64),
        );
        distributed_lamports
            + rewards_calculation
                .stake_rewards
                .total_stake_rewards_lamports
    }

    // Calculate rewards from previous epoch and distribute reward commissions
    pub(in crate::bank) fn calculate_rewards(
        &self,
        stake_history: &StakeHistory,
        stake_delegations: Vec<(&Pubkey, &StakeAccount<Delegation>)>,
        cached_vote_accounts: CachedVoteAccounts<'_>,
        rewarded_epoch: Epoch,
        reward_epoch_delegated_stakes: RewardEpochDelegatedStakes,
        reward_calc_tracer: Option<impl Fn(&RewardCalculationEvent) + Send + Sync>,
        thread_pool: &ThreadPool,
        metrics: &mut RewardsMetrics,
    ) -> Arc<PartitionedRewardsCalculation> {
        // We hold the lock here for the epoch rewards calculation cache to prevent
        // rewards computation across multiple forks simultaneously. This aligns with
        // how banks are currently created- all banks are created sequentially.
        // As such, this lock does not actually introduce contention because bank
        // creation (and therefore reward calculation) is always done sequentially.
        //
        // However, if we plan to support creating banks in parallel in the future, this logic
        // would need to change to allow rewards computation on multiple forks concurrently.
        // That said, there's still a compelling reason to keep this lock even in a parallel
        // bank creation model: we want to avoid calculating rewards multiple times for the same
        // parent bank hash. This lock ensures that.
        //
        // Creating bank for multiple forks in parallel would also introduce contention for compute resources,
        // potentially slowing down the performance of both forks. This, in turn, could delay
        // vote propagation and consensus for the leading fork—the one most likely to become rooted.
        //
        // Therefore, it seems beneficial to continue processing forks sequentially at epoch
        // boundaries: acquire the lock for the first fork, compute rewards, and let other forks
        // wait until the computation is complete.
        let mut epoch_rewards_calculation_cache =
            self.epoch_rewards_calculation_cache.lock().unwrap();
        let rewards_calculation = epoch_rewards_calculation_cache
            .entry(self.parent_hash)
            .or_insert_with(|| {
                Arc::new(self.calculate_rewards_for_partitioning(
                    stake_history,
                    stake_delegations,
                    cached_vote_accounts,
                    rewarded_epoch,
                    reward_epoch_delegated_stakes,
                    reward_calc_tracer,
                    thread_pool,
                    metrics,
                ))
            })
            .clone();
        drop(epoch_rewards_calculation_cache);

        rewards_calculation
    }

    /// Returns a tuple containing the total amount of commission lamports
    /// distributed and the total amount of lamports burned.
    pub(in crate::bank) fn distribute_reward_commissions(
        &mut self,
        prev_epoch: Epoch,
        rewards_calculation: &PartitionedRewardsCalculation,
        rewards_metrics: &mut RewardsMetrics,
        thread_pool: &ThreadPool,
    ) -> RewardCommissionLamportAmounts {
        let PartitionedRewardsCalculation {
            reward_commissions,
            stake_rewards,
            capitalization,
            point_value,
            num_filtered_vote_accounts,
            ..
        } = rewards_calculation;

        // Load the commission accounts and apply their rewards.
        // This is intentionally deferred from calculation time so that any
        // intervening account mutations (e.g. VAT burns in
        // `update_epoch_stakes`) are reflected.
        let (reward_commission_accounts, load_and_reward_commission_accounts_us) =
            measure_us!(self.load_and_reward_commission_accounts(reward_commissions, thread_pool));
        rewards_metrics.load_and_reward_commission_accounts_us =
            load_and_reward_commission_accounts_us;
        info!(
            "load_and_reward_commission_accounts: input_count={} output_count={} elapsed_us={}",
            reward_commissions.len(),
            reward_commission_accounts.accounts_with_rewards.len(),
            load_and_reward_commission_accounts_us,
        );

        let RewardCommissionLamportAmounts {
            distributed_lamports,
            distributed_to_incinerator_lamports,
            burned_lamports,
        } = reward_commission_accounts.amounts;
        self.store_commission_accounts_partitioned(&reward_commission_accounts, rewards_metrics);
        self.update_reward_commissions(&reward_commission_accounts);

        let StakeRewardCalculation {
            total_stake_rewards_lamports,
            ..
        } = stake_rewards;

        // verify that we didn't pay any more than we expected to
        assert!(
            point_value.rewards
                >= distributed_lamports
                    + distributed_to_incinerator_lamports
                    + burned_lamports
                    + total_stake_rewards_lamports,
            "point_value={point_value:?}, distributed_lamports={distributed_lamports}, \
             distributed_to_incinerator_lamports={distributed_to_incinerator_lamports} \
             burned_lamports={burned_lamports}, \
             total_stake_rewards_lamports={total_stake_rewards_lamports}"
        );
        info!(
            "distributed reward commissions: {} out of {}, remaining {}",
            distributed_lamports + distributed_to_incinerator_lamports + burned_lamports,
            point_value.rewards,
            total_stake_rewards_lamports
        );

        let num_stake_accounts = self.stakes_cache.stakes().stake_delegations().len();
        let num_vote_accounts = *num_filtered_vote_accounts;
        self.capitalization.fetch_add(
            distributed_lamports + distributed_to_incinerator_lamports,
            Relaxed,
        );

        let active_stake = if let Some(stake_history_entry) =
            self.stakes_cache.stakes().history().get(prev_epoch)
        {
            stake_history_entry.effective
        } else {
            0
        };

        datapoint_info!(
            "epoch_rewards",
            ("slot", self.slot, i64),
            ("epoch", prev_epoch, i64),
            ("validator_rewards", distributed_lamports, i64),
            (
                "validator_rewards_to_incinerator",
                distributed_to_incinerator_lamports,
                i64
            ),
            ("validator_rewards_burned", burned_lamports, i64),
            ("active_stake", active_stake, i64),
            ("pre_capitalization", *capitalization, i64),
            ("post_capitalization", self.capitalization(), i64),
            ("num_stake_accounts", num_stake_accounts, i64),
            ("num_vote_accounts", num_vote_accounts, i64),
        );

        reward_commission_accounts.amounts
    }

    fn store_commission_accounts_partitioned(
        &self,
        reward_commission_accounts: &RewardCommissionAccounts,
        metrics: &RewardsMetrics,
    ) {
        let (_, measure_us) = measure_us!({
            let storable = RewardCommissionAccountsStorable {
                slot: self.slot(),
                reward_commission_accounts,
            };
            self.store_accounts(storable);
        });

        metrics
            .store_commission_accounts_us
            .fetch_add(measure_us, Relaxed);
    }

    /// Calculate rewards from previous epoch to prepare for partitioned distribution.
    pub(super) fn calculate_rewards_for_partitioning<'a>(
        &self,
        stake_history: &StakeHistory,
        stake_delegations: Vec<(&'a Pubkey, &'a StakeAccount<Delegation>)>,
        cached_vote_accounts: CachedVoteAccounts<'_>,
        rewarded_epoch: Epoch,
        reward_epoch_delegated_stakes: RewardEpochDelegatedStakes,
        reward_calc_tracer: Option<impl Fn(&RewardCalculationEvent) + Send + Sync>,
        thread_pool: &ThreadPool,
        metrics: &mut RewardsMetrics,
    ) -> PartitionedRewardsCalculation {
        let capitalization = self.capitalization();
        let epoch_inflation_rewards =
            self.calculate_epoch_inflation_rewards(capitalization, rewarded_epoch);
        // `distribution_epoch_vote_accounts` is the post-VAT-filter snapshot
        // produced upstream of this call (or unfiltered when VAT is off),
        // so its length is the right value for the `epoch_rewards` metric.
        let num_filtered_vote_accounts =
            cached_vote_accounts.distribution_epoch_vote_accounts.len();

        let CalculateValidatorRewardsResult {
            reward_commissions,
            stake_reward_calculation: stake_rewards,
            point_value,
        } = self
            .calculate_validator_rewards(
                stake_history,
                stake_delegations,
                cached_vote_accounts,
                rewarded_epoch,
                epoch_inflation_rewards,
                reward_epoch_delegated_stakes,
                reward_calc_tracer,
                thread_pool,
                metrics,
            )
            .unwrap_or_default();

        info!(
            "calculated rewards for epoch: {}, parent_slot: {}, parent_hash: {}",
            self.epoch, self.parent_slot, self.parent_hash
        );

        PartitionedRewardsCalculation {
            reward_commissions,
            stake_rewards,
            capitalization,
            point_value,
            num_filtered_vote_accounts,
        }
    }

    /// Calculate epoch reward and return stake rewards and commissions.
    #[allow(clippy::too_many_arguments)]
    fn calculate_validator_rewards<'a>(
        &self,
        stake_history: &StakeHistory,
        stake_delegations: Vec<(&'a Pubkey, &'a StakeAccount<Delegation>)>,
        cached_vote_accounts: CachedVoteAccounts<'_>,
        rewarded_epoch: Epoch,
        epoch_inflation_rewards: u64,
        reward_epoch_delegated_stakes: RewardEpochDelegatedStakes,
        reward_calc_tracer: Option<impl RewardCalcTracer>,
        thread_pool: &ThreadPool,
        metrics: &mut RewardsMetrics,
    ) -> Option<CalculateValidatorRewardsResult> {
        let ag_epoch_type =
            AlpenglowEpochType::get(self, rewarded_epoch, || Some(reward_epoch_delegated_stakes));
        self.calculate_reward_points_partitioned(
            stake_history,
            &stake_delegations,
            &cached_vote_accounts,
            epoch_inflation_rewards,
            &ag_epoch_type,
            thread_pool,
            metrics,
        )
        .map(|point_value| {
            let (reward_commissions, stake_reward_calculation) = self
                .calculate_stake_rewards_and_commissions(
                    stake_history,
                    stake_delegations,
                    cached_vote_accounts,
                    rewarded_epoch,
                    point_value.clone(),
                    &ag_epoch_type,
                    thread_pool,
                    reward_calc_tracer,
                    metrics,
                );
            CalculateValidatorRewardsResult {
                reward_commissions,
                stake_reward_calculation,
                point_value,
            }
        })
    }

    /// Retrieves stake history and delegations for stake reward recalculation
    /// after snapshot restore.
    fn get_epoch_params_for_recalculation<'a>(
        &'a self,
        rewarded_epoch: Epoch,
        stakes: &'a Stakes<StakeAccount<Delegation>>,
    ) -> EpochRewardCalculateParamInfo<'a> {
        // Use `stakes` for stake-related info
        let stake_history = stakes.history().clone();
        let stake_delegations = stakes.stake_delegations_vec();

        // Use the vote-account snapshot from epoch_stakes, which is VAT-filtered
        // when admission filtering is enabled. Recalculation should match the
        // vote-account admission policy used for distribution.
        let leader_schedule_epoch = self.epoch_schedule().get_leader_schedule_epoch(self.slot());
        let distribution_epoch_vote_accounts = self
            .epoch_stakes(leader_schedule_epoch)
            .expect("calculation should always run after Bank::update_epoch_stakes()")
            .stakes()
            .vote_accounts();
        let cached_vote_accounts =
            self.get_cached_vote_accounts(rewarded_epoch, distribution_epoch_vote_accounts);

        EpochRewardCalculateParamInfo {
            stake_history,
            stake_delegations,
            cached_vote_accounts,
        }
    }

    #[expect(clippy::too_many_arguments)]
    fn redeem_delegation_rewards(
        &self,
        rewarded_epoch: Epoch,
        stake_pubkey: &Pubkey,
        stake_account: &StakeAccount<Delegation>,
        point_value: &PointValue,
        stake_history: &StakeHistory,
        cached_vote_accounts: &CachedVoteAccounts<'_>,
        reward_calc_tracer: Option<impl RewardCalcTracer>,
        new_rate_activation_epoch: Option<Epoch>,
        delay_commission_updates: bool,
        commission_rate_in_basis_points: bool,
        adjust_delegations_for_rent: bool,
        ag_epoch_type: &AlpenglowEpochType,
        custom_commission_collector: bool,
        use_fixed_point_stake_math: bool,
    ) -> Option<InflationRewardWithCommission> {
        // curry closure to add the contextual stake_pubkey
        let reward_calc_tracer = reward_calc_tracer.as_ref().map(|outer| {
            // inner
            move |inner_event: &_| {
                outer(&RewardCalculationEvent::Staking(stake_pubkey, inner_event))
            }
        });

        let CachedVoteAccounts {
            snapshot_epoch_vote_accounts,
            rewarded_epoch_vote_accounts,
            distribution_epoch_vote_accounts,
        } = cached_vote_accounts;

        let vote_pubkey = stake_account.delegation().voter_pubkey;

        let current_lamports = stake_account.lamports();
        let minimum_lamports = self
            .rent_collector
            .rent
            .minimum_balance(stake_account.data_len());
        let stake = *stake_account.stake();

        let Some(vote_account) = distribution_epoch_vote_accounts.get(&vote_pubkey) else {
            debug!("could not find vote account {vote_pubkey} in cache");
            // Even if the vote account doesn't exist, there might still be a
            // need to adjust the stake delegation
            if adjust_delegations_for_rent {
                if delegation_may_need_adjustment(
                    stake.delegation.stake,
                    stake.delegation.stake,
                    current_lamports,
                    minimum_lamports,
                ) {
                    debug!(
                        "delegation for stake {stake_pubkey} may be adjusted at distribution, \
                         unless lamports are transferred before distribution block"
                    );
                    let inflation = InflationReward {
                        stake,
                        stake_reward: 0,
                        commission_bps: (!custom_commission_collector).then_some(0),
                    };
                    // Set `is_vote_account` to `false` in order to deliberately
                    // fail during commission collector checks. This avoids
                    // creating a reward entry during payout.
                    let reward_commission = RewardCommission {
                        commission_bps: (!custom_commission_collector).then_some(0),
                        commission_lamports: 0,
                        burned_lamports: 0,
                        is_vote_account: false,
                    };
                    return Some(InflationRewardWithCommission {
                        inflation,
                        commission_pubkey: vote_pubkey,
                        reward_commission,
                    });
                } else {
                    debug!("delegation for stake {stake_pubkey} will not be adjusted");
                    return None;
                }
            } else {
                return None;
            }
        };
        let vote_state = vote_account.vote_state_view();

        // Fetch the voter commission from past epochs to attempt to
        // delay the effect of commission updates by at least one
        // full epoch.
        // When `commission_rate_in_basis_points` is true, use the new field
        // `inflation_rewards_commission_bps`; otherwise use the legacy
        // percentage field and convert to basis points by multiplying by 100.
        let commission_bps = if delay_commission_updates {
            let vote_state_for_commission = snapshot_epoch_vote_accounts
                .and_then(|eva| eva.get(&vote_pubkey))
                .or_else(|| rewarded_epoch_vote_accounts.and_then(|eva| eva.get(&vote_pubkey)))
                .map(|vote_account| vote_account.vote_state_view())
                .unwrap_or(vote_state);
            if commission_rate_in_basis_points {
                vote_state_for_commission.inflation_rewards_commission()
            } else {
                vote_state_for_commission.commission() as u16 * 100
            }
        } else if commission_rate_in_basis_points {
            vote_state.inflation_rewards_commission()
        } else {
            vote_state.commission() as u16 * 100
        };

        match redeem_rewards(
            stake,
            commission_bps,
            DelegatedVoteState::from(vote_state),
            CalculationEnvironment {
                rewarded_epoch,
                point_value,
                stake_history,
                new_rate_activation_epoch,
                commission_rate_in_basis_points,
                adjust_delegations_for_rent,
                use_fixed_point_stake_math,
            },
            reward_calc_tracer,
            ag_epoch_type,
            current_lamports,
            minimum_lamports,
        ) {
            Ok((stake_reward, commission_lamports, stake)) => {
                let inflation = InflationReward {
                    stake,
                    stake_reward,
                    commission_bps: (!custom_commission_collector).then_some(commission_bps),
                };
                let (commission_pubkey, is_vote_account) = if custom_commission_collector {
                    let commission_pubkey = *vote_state
                        .inflation_rewards_collector()
                        .unwrap_or(&vote_pubkey);
                    (commission_pubkey, commission_pubkey == vote_pubkey)
                } else {
                    (vote_pubkey, true)
                };
                let reward_commission = RewardCommission {
                    commission_bps: (!custom_commission_collector).then_some(commission_bps),
                    commission_lamports,
                    burned_lamports: 0,
                    is_vote_account,
                };
                Some(InflationRewardWithCommission {
                    inflation,
                    commission_pubkey,
                    reward_commission,
                })
            }
            Err(e) => {
                debug!("redeem_rewards() failed for {stake_pubkey}: {e:?}");
                None
            }
        }
    }

    /// Calculates epoch rewards for stake/commission accounts
    /// Returns commission accounts, stake rewards, and the sum of all stake rewards in lamports
    #[allow(clippy::too_many_arguments)]
    fn calculate_stake_rewards_and_commissions<'a>(
        &self,
        stake_history: &StakeHistory,
        stake_delegations: Vec<(&'a Pubkey, &'a StakeAccount<Delegation>)>,
        cached_vote_accounts: CachedVoteAccounts<'_>,
        rewarded_epoch: Epoch,
        point_value: PointValue,
        ag_epoch_type: &AlpenglowEpochType,
        thread_pool: &ThreadPool,
        reward_calc_tracer: Option<impl RewardCalcTracer>,
        metrics: &mut RewardsMetrics,
    ) -> (RewardCommissions, StakeRewardCalculation) {
        let new_warmup_cooldown_rate_epoch = self.new_warmup_cooldown_rate_epoch();
        let feature_snapshot = self.feature_set.snapshot();
        let use_fixed_point_stake_math = feature_snapshot.upgrade_bpf_stake_program_to_v5_1;
        let delay_commission_updates = feature_snapshot.delay_commission_updates;
        let commission_rate_in_basis_points = feature_snapshot.commission_rate_in_basis_points;
        // Name intentionally doesn't match -- "adjust delegations for rent" is
        // part of relaxing post-exec min balance checks.
        let adjust_delegations_for_rent = feature_snapshot.relax_post_exec_min_balance_check;
        let custom_commission_collector = feature_snapshot.custom_commission_collector;

        let mut measure_redeem_rewards = Measure::start("redeem-rewards");
        // For N stake delegations, where N is >1,000,000, we produce:
        // * N stake rewards,
        // * M reward commission accounts, where M is a number of stake nodes.
        //   Currently, way smaller number than 1,000,000. And we can expect it
        //   to always be significantly smaller than number of delegations.
        //
        // Producing the stake reward with rayon triggers a lot of
        // (re)allocations. To avoid that, we allocate it at the start and
        // pass `stake_rewards.spare_capacity_mut()` as one of iterators.
        let mut stake_rewards = PartitionedStakeRewards::with_capacity(stake_delegations.len());
        let rewards_accumulator: RewardsAccumulator = thread_pool.install(|| {
            stake_delegations
                .par_iter()
                .zip_eq(stake_rewards.spare_capacity_mut())
                .with_min_len(500)
                .filter_map(|((stake_pubkey, stake_account), stake_reward_ref)| {
                    let maybe_reward_record = self.redeem_delegation_rewards(
                        rewarded_epoch,
                        stake_pubkey,
                        stake_account,
                        &point_value,
                        stake_history,
                        &cached_vote_accounts,
                        reward_calc_tracer.as_ref(),
                        new_warmup_cooldown_rate_epoch,
                        delay_commission_updates,
                        commission_rate_in_basis_points,
                        adjust_delegations_for_rent,
                        ag_epoch_type,
                        custom_commission_collector,
                        use_fixed_point_stake_math,
                    );

                    let (stake_reward, maybe_reward_record) = match maybe_reward_record {
                        Some(res) => {
                            let InflationRewardWithCommission {
                                inflation,
                                commission_pubkey,
                                reward_commission,
                            } = res;
                            let stakers_reward = inflation.stake_reward;
                            (
                                Some(PartitionedStakeReward {
                                    stake_pubkey: **stake_pubkey,
                                    inflation,
                                }),
                                Some((stakers_reward, commission_pubkey, reward_commission)),
                            )
                        }
                        None => (None, None),
                    };
                    // It's important that for every stake delegation, we write
                    // a value to the cell of the stake rewards vector,
                    // regardless of whether it's `Some` or `None` variant.
                    // This allows us to pre-allocate the vector with the known
                    // size and avoid re-allocations, which were the bottleneck
                    // in this path.
                    stake_reward_ref.write(stake_reward);
                    maybe_reward_record
                })
                .fold(
                    RewardsAccumulator::default,
                    |mut rewards_accumulator,
                     (stakers_reward, commission_pubkey, reward_commission)| {
                        rewards_accumulator.add_reward(
                            commission_pubkey,
                            reward_commission,
                            stakers_reward,
                        );
                        rewards_accumulator
                    },
                )
                .reduce(
                    RewardsAccumulator::default,
                    |rewards_accumulator_a, rewards_accumulator_b| {
                        rewards_accumulator_a.accumulate_into_larger(rewards_accumulator_b)
                    },
                )
        });
        let RewardsAccumulator {
            reward_commissions,
            num_stake_rewards,
            total_stake_rewards_lamports,
        } = rewards_accumulator;
        // SAFETY: We initialized all the `stake_rewards` elements up to the capacity.
        unsafe {
            stake_rewards.assume_init(num_stake_rewards);
        }
        measure_redeem_rewards.stop();
        metrics.redeem_rewards_us = measure_redeem_rewards.as_us();

        (
            reward_commissions,
            StakeRewardCalculation {
                stake_rewards: Arc::new(stake_rewards),
                total_stake_rewards_lamports,
            },
        )
    }

    /// Calculates epoch reward points from stake/vote accounts.
    /// Returns reward lamports and points for the epoch or none if points == 0.
    fn calculate_reward_points_partitioned<'a>(
        &self,
        stake_history: &StakeHistory,
        stake_delegations: &Vec<(&'a Pubkey, &'a StakeAccount<Delegation>)>,
        cached_vote_accounts: &CachedVoteAccounts<'_>,
        epoch_inflation_rewards: u64,
        ag_epoch_type: &AlpenglowEpochType,
        thread_pool: &ThreadPool,
        metrics: &RewardsMetrics,
    ) -> Option<PointValue> {
        let CachedVoteAccounts {
            distribution_epoch_vote_accounts,
            ..
        } = cached_vote_accounts;

        let solana_vote_program: Pubkey = solana_vote_program::id();
        let new_warmup_cooldown_rate_epoch = self.new_warmup_cooldown_rate_epoch();
        match ag_epoch_type {
            AlpenglowEpochType::Alpenglow { .. } => {
                // In alpenglow, we do not need to compute `PointValue::points` as the final
                // rewards are simply the total credits stored in the vote account.  We just need
                // to return a `Some` value with valid rewards.
                return Some(PointValue {
                    rewards: epoch_inflation_rewards,
                    points: 0,
                });
            }
            AlpenglowEpochType::Tower => {
                // For tower we need to compute the valid `PointValue::points`.
            }
            AlpenglowEpochType::MigrationEpoch { .. } => {
                // For the migrating epoch, we need to compute the tower portion of `PointValue::points`.
            }
        }

        let use_fixed_point_stake_math = self.use_fixed_point_stake_math();
        let (points, measure_us) = measure_us!(thread_pool.install(|| {
            stake_delegations
                .par_iter()
                .map(|(_stake_pubkey, stake_account)| {
                    let vote_pubkey = stake_account.delegation().voter_pubkey;

                    let Some(vote_account) = distribution_epoch_vote_accounts.get(&vote_pubkey)
                    else {
                        return 0;
                    };
                    if vote_account.owner() != &solana_vote_program {
                        return 0;
                    }

                    calculate_points_for_tower(
                        stake_account.stake_state(),
                        DelegatedVoteState::from(vote_account.vote_state_view()),
                        stake_history,
                        new_warmup_cooldown_rate_epoch,
                        use_fixed_point_stake_math,
                    )
                    .unwrap_or(0)
                })
                .sum::<u128>()
        }));
        metrics.calculate_points_us.fetch_add(measure_us, Relaxed);

        (points > 0).then_some(PointValue {
            rewards: epoch_inflation_rewards,
            points,
        })
    }

    /// If rewards are still active, recalculates partitioned stake rewards and
    /// updates Bank::epoch_reward_status. This method assumes that reward
    /// commissions have already been calculated and delivered, and *only*
    /// recalculates stake rewards
    pub(in crate::bank) fn recalculate_partitioned_rewards_if_active<F, TP>(
        &mut self,
        thread_pool_builder: F,
    ) where
        F: FnOnce() -> TP,
        TP: std::borrow::Borrow<ThreadPool>,
    {
        let epoch_rewards_sysvar = self.get_epoch_rewards_sysvar();
        if epoch_rewards_sysvar.active {
            let thread_pool = thread_pool_builder();
            let (stake_rewards, partition_indices) =
                self.recalculate_stake_rewards(&epoch_rewards_sysvar, thread_pool.borrow());
            self.set_epoch_reward_status_distribution(
                epoch_rewards_sysvar.distribution_starting_block_height,
                stake_rewards,
                partition_indices,
            );
        }
    }

    /// Returns a vector of partitioned stake rewards. StakeRewards are
    /// recalculated from an active EpochRewards sysvar, vote accounts from
    /// EpochStakes, and stake accounts from StakesCache.
    fn recalculate_stake_rewards(
        &self,
        epoch_rewards_sysvar: &EpochRewards,
        thread_pool: &ThreadPool,
    ) -> (Arc<PartitionedStakeRewards>, Vec<Vec<usize>>) {
        assert!(epoch_rewards_sysvar.active);
        // If rewards are active, the rewarded epoch is always the immediately
        // preceding epoch.
        let rewarded_epoch = self.epoch().saturating_sub(1);

        let point_value = PointValue {
            rewards: epoch_rewards_sysvar.total_rewards,
            points: epoch_rewards_sysvar.total_points,
        };

        let stakes = self.stakes_cache.stakes();
        let EpochRewardCalculateParamInfo {
            stake_history,
            stake_delegations,
            cached_vote_accounts,
        } = self.get_epoch_params_for_recalculation(rewarded_epoch, &stakes);
        let ag_epoch_type = AlpenglowEpochType::get(self, rewarded_epoch, || {
            RewardEpochDelegatedStakes::get(self)
        });

        // On recalculation, only the `StakeRewardCalculation::stake_rewards`
        // field is relevant. It is assumed that reward commission accounts have
        // already been calculated and delivered, while
        // `StakeRewardCalculation::total_rewards` only reflects rewards that
        // have not yet been distributed.
        //
        // NOTE: the `RewardCommissionAccounts` will NOT have a correct
        // post_lamport amount if the commission account is NOT the vote account,
        // because the commission account is loaded from the current bank, and
        // not the start of the epoch. We don't have a snapshot of all commission
        // accounts from the start of the epoch. For this reason, the
        // `RewardCommissionAccounts` calculated in this function call should
        // NOT be used ever.
        let (_, StakeRewardCalculation { stake_rewards, .. }) = self
            .calculate_stake_rewards_and_commissions(
                &stake_history,
                stake_delegations,
                cached_vote_accounts,
                rewarded_epoch,
                point_value,
                &ag_epoch_type,
                thread_pool,
                null_tracer(),
                &mut RewardsMetrics::default(), // This is required, but not reporting anything at the moment
            );
        drop(stakes);
        let partition_indices = hash_rewards_into_partitions(
            &stake_rewards,
            &epoch_rewards_sysvar.parent_blockhash,
            epoch_rewards_sysvar.num_partitions as usize,
        );
        (stake_rewards, partition_indices)
    }

    /// Load each planned commission account from the store and apply its
    /// reward. This is the single point where commission account data is
    /// fetched, ensuring we always see the latest balances — including any
    /// intervening account mutations (e.g. VAT burns in `update_epoch_stakes`)
    /// that happen between calculation and distribution.
    fn load_and_reward_commission_accounts(
        &self,
        reward_commissions: &RewardCommissions,
        thread_pool: &ThreadPool,
    ) -> RewardCommissionAccounts {
        let reserved_account_keys = &self.reserved_account_keys;
        let rent = &self.rent_collector().rent;
        let feature_snapshot = self.feature_set.snapshot();
        let relax_post_exec_min_balance_check = feature_snapshot.relax_post_exec_min_balance_check;
        let custom_commission_collector = feature_snapshot.custom_commission_collector;
        let total_non_incinerator_burned_lamports = AtomicU64::new(0);
        let total_incinerator_lamports = AtomicU64::new(0);

        let accounts_with_rewards: Vec<_> = thread_pool.install(|| {
            reward_commissions
                .par_iter()
                .filter_map(
                    |(
                        commission_pubkey,
                        RewardCommission {
                            commission_bps,
                            commission_lamports,
                            burned_lamports,
                            is_vote_account,
                        },
                    )| {
                        let maybe_commission_account =
                            self.get_account_with_fixed_root_no_cache(commission_pubkey);
                        let mut commission_account = if custom_commission_collector {
                            // If the account doesn't exist, the vote commission
                            // may be enough lamports to cover rent-exemption
                            // and properly create the commission account.
                            maybe_commission_account.unwrap_or_default()
                        } else {
                            // Before SIMD-0232, commission accounts were always
                            // vote accounts, which cannot be closed unless the
                            // account hasn't voted for at least a full epoch.
                            // This means that `maybe_commission_account` should
                            // always exist.
                            let Some(commission_account) = maybe_commission_account else {
                                debug!(
                                    "commission account {commission_pubkey} missing at \
                                     distribution time"
                                );
                                return None;
                            };
                            commission_account
                        };
                        if *burned_lamports != 0 {
                            total_non_incinerator_burned_lamports
                                .fetch_add(*burned_lamports, Relaxed);
                        }
                        let pre_lamports = commission_account.lamports();
                        if let Err(err) =
                            commission_account.checked_add_lamports(*commission_lamports)
                        {
                            debug!("reward redemption failed for {commission_pubkey}: {err:?}");
                            total_non_incinerator_burned_lamports
                                .fetch_add(*commission_lamports, Relaxed);
                            return None;
                        }
                        if !is_vote_account {
                            match Self::collector_type_checked(
                                commission_pubkey,
                                pre_lamports,
                                &commission_account,
                                reserved_account_keys,
                                rent,
                                relax_post_exec_min_balance_check,
                            ) {
                                Ok(ExternalCollectorType::SystemAccount) => {}
                                Ok(ExternalCollectorType::Incinerator) => {
                                    total_incinerator_lamports
                                        .fetch_add(*commission_lamports, Relaxed);
                                }
                                Err(err) => {
                                    debug!(
                                        "reward redemption failed for {commission_pubkey} due to \
                                         commission account error: {err:?}"
                                    );
                                    total_non_incinerator_burned_lamports
                                        .fetch_add(*commission_lamports, Relaxed);
                                    return None;
                                }
                            }
                        }
                        Some((
                            *commission_pubkey,
                            RewardInfo {
                                reward_type: RewardType::Voting,
                                lamports: *commission_lamports as i64,
                                post_balance: commission_account.lamports(),
                                commission_bps: *commission_bps,
                            },
                            commission_account,
                        ))
                    },
                )
                .collect()
        });

        let distributed_to_incinerator_lamports = total_incinerator_lamports.into_inner();
        let distributed_lamports = accounts_with_rewards
            .iter()
            .map(|(_, info, _)| info.lamports as u64)
            .sum::<u64>()
            .checked_sub(distributed_to_incinerator_lamports)
            .expect("incinerator lamports must be a subset of all distributed lamports");
        RewardCommissionAccounts {
            accounts_with_rewards,
            amounts: RewardCommissionLamportAmounts {
                distributed_lamports,
                distributed_to_incinerator_lamports,
                burned_lamports: total_non_incinerator_burned_lamports.into_inner(),
            },
        }
    }

    fn update_reward_commissions(&self, reward_commission_accounts: &RewardCommissionAccounts) {
        let mut rewards = self.rewards.write().unwrap();
        rewards.reserve(reward_commission_accounts.accounts_with_rewards.len());
        reward_commission_accounts
            .accounts_with_rewards
            .iter()
            .for_each(|(commission_pubkey, reward_commission, _)| {
                rewards.push((*commission_pubkey, *reward_commission));
            });
    }
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::{
            bank::{
                RewardInfo, SlotLeader, null_tracer,
                partitioned_epoch_rewards::{
                    EpochRewardPhase, EpochRewardStatus, PartitionedStakeRewards,
                    StartBlockHeightAndPartitionedRewards,
                    tests::{
                        RewardBank, SLOTS_PER_EPOCH, build_partitioned_stake_rewards,
                        create_default_reward_bank, create_reward_bank,
                        create_reward_bank_with_specific_stakes, populate_vote_accounts_with_votes,
                    },
                },
                tests::create_genesis_config,
            },
            bank_forks::BankForks,
            genesis_utils::{self, GenesisConfigInfo, deactivate_features},
            runtime_config::RuntimeConfig,
            stake_account::StakeAccount,
            stake_utils,
            stakes::{Stakes, tests::create_staked_node_accounts},
        },
        agave_feature_set::{FeatureSet, delay_commission_updates},
        agave_votor_messages::consensus_message::BLS_KEYPAIR_DERIVE_SEED,
        rand::Rng,
        rayon::ThreadPoolBuilder,
        solana_account::{
            AccountSharedData, ReadableAccount, accounts_equal, state_traits::StateMut,
        },
        solana_accounts_db::{
            accounts_db::{ACCOUNTS_DB_CONFIG_FOR_TESTING, AccountsDbConfig},
            partitioned_rewards::PartitionedEpochRewardsConfig,
        },
        solana_bls_signatures::keypair::Keypair as BLSKeypair,
        solana_clock::Clock,
        solana_epoch_schedule::EpochSchedule,
        solana_keypair::Keypair,
        solana_native_token::LAMPORTS_PER_SOL,
        solana_rent::Rent,
        solana_sdk_ids::incinerator,
        solana_signer::Signer,
        solana_stake_interface::{
            stake_flags::StakeFlags,
            state::{Authorized, Delegation, Meta, Stake, StakeStateV2},
        },
        solana_vote_interface::state::{
            BLS_PUBLIC_KEY_COMPRESSED_SIZE, VoteInitV2, VoteStateV4, VoteStateVersions,
        },
        solana_vote_program::vote_state::{self, create_bls_proof_of_possession},
        std::{
            collections::{HashMap, HashSet},
            sync::{Arc, RwLock, RwLockReadGuard},
        },
        test_case::{test_case, test_matrix},
    };

    fn reward_epoch_delegated_stakes_for_tests(epoch: Epoch) -> RewardEpochDelegatedStakes {
        RewardEpochDelegatedStakes {
            epoch,
            delegated_stakes: HashMap::default(),
        }
    }

    #[test]
    fn test_store_commission_accounts_partitioned() {
        let (genesis_config, _mint_keypair) = create_genesis_config(1_000_000 * LAMPORTS_PER_SOL);
        let bank = Bank::new_for_tests(&genesis_config);

        let num_reward_commissions = 100;
        let mut rng = rand::rng();
        let entries: Vec<(Pubkey, RewardInfo, AccountSharedData)> = (0..num_reward_commissions)
            .map(|_| {
                let commission_balance = rng.random_range(1..200);
                let commission_bps: u16 = rng.random_range(100..2_000);
                let commission_lamports: u64 = rng.random_range(1..200);
                let mut commission_account = AccountSharedData::default();
                commission_account.set_lamports(commission_balance);
                let info = RewardInfo {
                    reward_type: RewardType::Voting,
                    lamports: commission_lamports as i64,
                    post_balance: commission_lamports,
                    commission_bps: Some(commission_bps),
                };
                (Pubkey::new_unique(), info, commission_account)
            })
            .collect();

        let mut reward_commission_accounts = RewardCommissionAccounts::default();
        for (commission_pubkey, info, commission_account) in &entries {
            reward_commission_accounts.accounts_with_rewards.push((
                *commission_pubkey,
                *info,
                commission_account.clone(),
            ));
            reward_commission_accounts.amounts.distributed_lamports += info.lamports as u64;
        }

        let metrics = RewardsMetrics::default();

        let total_reward_commissions = reward_commission_accounts.amounts.distributed_lamports;
        bank.store_commission_accounts_partitioned(&reward_commission_accounts, &metrics);
        assert_eq!(
            num_reward_commissions,
            reward_commission_accounts.accounts_with_rewards.len()
        );
        assert_eq!(
            entries
                .iter()
                .map(|(_, info, _)| info.lamports as u64)
                .sum::<u64>(),
            total_reward_commissions
        );

        // load accounts to make sure they were stored correctly
        for (commission_pubkey, _, commission_account) in &entries {
            let loaded_account = bank
                .load_slow_with_fixed_root(&bank.ancestors, commission_pubkey)
                .unwrap();
            assert!(accounts_equal(&loaded_account.0, commission_account));
        }
    }

    #[test]
    fn test_store_commission_accounts_partitioned_empty() {
        let (genesis_config, _mint_keypair) = create_genesis_config(1_000_000 * LAMPORTS_PER_SOL);
        let bank = Bank::new_for_tests(&genesis_config);

        let expected = 0;
        let reward_commission_accounts = RewardCommissionAccounts::default();
        let metrics = RewardsMetrics::default();
        let total_reward_commissions = reward_commission_accounts.amounts.distributed_lamports;

        bank.store_commission_accounts_partitioned(&reward_commission_accounts, &metrics);
        assert_eq!(
            expected,
            reward_commission_accounts.accounts_with_rewards.len()
        );
        assert_eq!(0, total_reward_commissions);
    }

    #[test]
    /// Test rewards computation and partitioned rewards distribution at the epoch boundary
    fn test_rewards_computation() {
        agave_logger::setup();

        // Delegations to get rewards (2 SOL).
        let delegations = 100;
        let stakes = (0..delegations).map(|_| 2_000_000_000).collect::<Vec<_>>();
        let bank = create_reward_bank_with_specific_stakes(
            stakes,
            PartitionedEpochRewardsConfig::default().stake_account_stores_per_block,
            SLOTS_PER_EPOCH,
        )
        .0
        .bank;

        // Calculate rewards
        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let mut rewards_metrics = RewardsMetrics::default();
        let expected_rewards = 100_000_000_000;

        let stakes = bank.stakes_cache.stakes();
        let rewarded_epoch = 0;
        let EpochRewardCalculateParamInfo {
            stake_history,
            stake_delegations,
            cached_vote_accounts,
        } = bank.get_epoch_params_for_recalculation(rewarded_epoch, &stakes);
        let calculated_rewards = bank.calculate_validator_rewards(
            &stake_history,
            stake_delegations,
            cached_vote_accounts,
            rewarded_epoch,
            expected_rewards,
            reward_epoch_delegated_stakes_for_tests(rewarded_epoch),
            null_tracer(),
            &thread_pool,
            &mut rewards_metrics,
        );

        let reward_commissions = &calculated_rewards.as_ref().unwrap().reward_commissions;
        let stake_rewards = &calculated_rewards
            .as_ref()
            .unwrap()
            .stake_reward_calculation;

        let total_reward_commissions: u64 = reward_commissions
            .values()
            .map(|rc| rc.commission_lamports)
            .sum();

        // assert that total rewards matches the sum of reward commissions and stake rewards
        assert_eq!(
            stake_rewards.total_stake_rewards_lamports + total_reward_commissions,
            expected_rewards
        );

        // assert that number of stake rewards matches
        assert_eq!(stake_rewards.stake_rewards.num_rewards(), delegations);
    }

    #[test]
    fn test_rewards_point_calculation() {
        agave_logger::setup();

        let expected_num_delegations = 100;
        let RewardBank { bank, .. } =
            create_default_reward_bank(expected_num_delegations, SLOTS_PER_EPOCH).0;

        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let rewards_metrics = RewardsMetrics::default();
        let expected_rewards = 100_000_000_000;

        let stakes: RwLockReadGuard<Stakes<StakeAccount<Delegation>>> = bank.stakes_cache.stakes();
        let rewarded_epoch = bank.epoch().saturating_sub(1);
        let EpochRewardCalculateParamInfo {
            stake_history,
            stake_delegations,
            cached_vote_accounts,
        } = bank.get_epoch_params_for_recalculation(rewarded_epoch, &stakes);

        let point_value = bank.calculate_reward_points_partitioned(
            &stake_history,
            &stake_delegations,
            &cached_vote_accounts,
            expected_rewards,
            &AlpenglowEpochType::Tower,
            &thread_pool,
            &rewards_metrics,
        );

        assert!(point_value.is_some());
        assert_eq!(point_value.as_ref().unwrap().rewards, expected_rewards);
        assert_eq!(point_value.as_ref().unwrap().points, 8400000000000);
    }

    #[test]
    fn test_rewards_point_calculation_empty() {
        agave_logger::setup();

        // bank with no rewards to distribute
        let (genesis_config, _mint_keypair) = create_genesis_config(LAMPORTS_PER_SOL);
        let bank = Bank::new_for_tests(&genesis_config);

        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let rewards_metrics: RewardsMetrics = RewardsMetrics::default();
        let expected_rewards = 100_000_000_000;
        let stakes: RwLockReadGuard<Stakes<StakeAccount<Delegation>>> = bank.stakes_cache.stakes();
        let rewarded_epoch = bank.epoch().saturating_sub(1);
        let EpochRewardCalculateParamInfo {
            stake_history,
            stake_delegations,
            cached_vote_accounts,
        } = bank.get_epoch_params_for_recalculation(rewarded_epoch, &stakes);

        let point_value = bank.calculate_reward_points_partitioned(
            &stake_history,
            &stake_delegations,
            &cached_vote_accounts,
            expected_rewards,
            &AlpenglowEpochType::Tower,
            &thread_pool,
            &rewards_metrics,
        );

        assert!(point_value.is_none());
    }

    #[test]
    fn test_begin_partitioned_rewards_returns_total_capitalization_increase() {
        let (genesis_config, _mint_keypair) = create_genesis_config(1_000 * LAMPORTS_PER_SOL);
        let mut bank = Bank::new_for_tests(&genesis_config);
        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();

        let commission_pubkey = Pubkey::new_unique();
        {
            let mut commission_account = AccountSharedData::default();
            commission_account.set_lamports(1);
            bank.store_account_and_update_capitalization(&commission_pubkey, &commission_account);
        }

        let commission_lamports = 123;
        let stake_reward_lamports = 456;
        let mut reward_commissions = RewardCommissions::default();
        reward_commissions.insert(
            commission_pubkey,
            RewardCommission {
                commission_bps: Some(0),
                commission_lamports,
                burned_lamports: 0,
                is_vote_account: true,
            },
        );
        let stake_rewards = [Some(PartitionedStakeReward {
            stake_pubkey: Pubkey::new_unique(),
            inflation: InflationReward {
                stake: Stake {
                    delegation: Delegation::default(),
                    credits_observed: 0,
                },
                stake_reward: stake_reward_lamports,
                commission_bps: Some(0),
            },
        })]
        .into_iter()
        .collect::<PartitionedStakeRewards>();
        let rewards_calculation = PartitionedRewardsCalculation {
            reward_commissions,
            stake_rewards: StakeRewardCalculation {
                stake_rewards: Arc::new(stake_rewards),
                total_stake_rewards_lamports: stake_reward_lamports,
            },
            capitalization: bank.capitalization(),
            point_value: PointValue {
                rewards: commission_lamports + stake_reward_lamports,
                points: 1,
            },
            num_filtered_vote_accounts: 1,
        };
        let mut rewards_metrics = RewardsMetrics::default();

        let rewards = bank.begin_partitioned_rewards(
            bank.epoch().saturating_sub(1),
            bank.parent_slot(),
            bank.block_height(),
            &rewards_calculation,
            &mut rewards_metrics,
            &thread_pool,
        );

        assert_eq!(rewards, commission_lamports + stake_reward_lamports);
        let epoch_rewards = bank.get_epoch_rewards_sysvar();
        assert_eq!(epoch_rewards.distributed_rewards, commission_lamports);
        assert_eq!(epoch_rewards.total_rewards, rewards);
    }

    struct EpochOperations {
        epoch: Epoch,
        vote_operations: Vec<(Pubkey, VoteOperations)>,
    }

    #[derive(Default)]
    struct VoteOperations {
        expect_reward: bool,
        // Additional lamport amount to ignore in collector account, used for
        // VAT burns in Alpenglow when the incinerator is an inflation collector
        extra_reward_lamport_amount: Option<u64>,
        // ops to perform before epoch ends
        create_with_balance: Option<u64>,
        delegate_stake_amount: Option<u64>,
        new_commission: Option<u8>,
        earned_credits: Option<u64>,
        new_inflation_rewards_collector: Option<Pubkey>,
    }

    fn recalculate_reward_commissions_for_tests(bank: &Bank) -> RewardCommissions {
        let epoch_rewards_sysvar = bank.get_epoch_rewards_sysvar();
        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        assert!(epoch_rewards_sysvar.active);
        let rewarded_epoch = bank.epoch().saturating_sub(1);

        let point_value = PointValue {
            rewards: epoch_rewards_sysvar.total_rewards,
            points: epoch_rewards_sysvar.total_points,
        };

        let stakes = bank.stakes_cache.stakes();
        let EpochRewardCalculateParamInfo {
            stake_history,
            stake_delegations,
            cached_vote_accounts,
        } = bank.get_epoch_params_for_recalculation(rewarded_epoch, &stakes);

        let (reward_commissions, ..) = bank.calculate_stake_rewards_and_commissions(
            &stake_history,
            stake_delegations,
            cached_vote_accounts,
            rewarded_epoch,
            point_value,
            &AlpenglowEpochType::Tower,
            &thread_pool,
            null_tracer(),
            &mut RewardsMetrics::default(), // This is required, but not reporting anything at the moment
        );
        reward_commissions
    }

    fn recalculate_reward_commission_for_tests(
        bank: &Bank,
        commission_pubkey: &Pubkey,
    ) -> Option<RewardInfo> {
        let reward_commissions = recalculate_reward_commissions_for_tests(bank);
        reward_commissions.get(commission_pubkey).and_then(|rc| {
            let commission_account = bank.get_account(commission_pubkey).unwrap_or_default();
            // In the recalculation path, commissions have already been
            // distributed — so the current account balance already includes
            // them. We report that balance as the post_balance.
            let post_balance = commission_account.lamports();

            // This is artificial, but mimics the actual distribution logic a
            // bit better
            if *commission_account.owner() != solana_vote_program::id()
                && Bank::collector_type_checked(
                    commission_pubkey,
                    post_balance.saturating_sub(rc.commission_lamports),
                    &commission_account,
                    &bank.reserved_account_keys,
                    &bank.rent_collector().rent,
                    true,
                )
                .is_err()
            {
                None
            } else {
                Some(RewardInfo {
                    reward_type: RewardType::Voting,
                    lamports: rc.commission_lamports as i64,
                    post_balance,
                    commission_bps: rc.commission_bps,
                })
            }
        })
    }

    fn create_stake_account(
        lamports: u64,
        delegation: u64,
        vote_address: &Pubkey,
        activation_epoch: Epoch,
    ) -> AccountSharedData {
        let mut stake_account = AccountSharedData::new(
            lamports,
            StakeStateV2::size_of(),
            &solana_sdk_ids::stake::id(),
        );
        let rent_exempt_reserve = lamports.saturating_sub(delegation);

        let meta = Meta {
            authorized: Authorized::auto(&Pubkey::new_unique()),
            #[expect(deprecated)]
            rent_exempt_reserve,
            ..Meta::default()
        };

        let stake = Stake {
            delegation: Delegation::new(vote_address, delegation, activation_epoch),
            credits_observed: 0,
        };

        stake_account
            .set_state(&StakeStateV2::Stake(meta, stake, StakeFlags::empty()))
            .expect("set_state");
        stake_account
    }

    fn apply_epoch_operations(
        bank: Arc<Bank>,
        bank_forks: &RwLock<BankForks>,
        op: EpochOperations,
    ) -> Arc<Bank> {
        assert_eq!(bank.epoch(), op.epoch);
        for (vote_address, vote_op) in &op.vote_operations {
            if let Some(balance) = &vote_op.create_with_balance {
                // Create a BLS pubkey so the vote account passes VAT filtering
                let identity = Keypair::new();
                let bls_keypair =
                    BLSKeypair::derive_from_signer(&identity, BLS_KEYPAIR_DERIVE_SEED).unwrap();
                let (bls_pubkey, bls_pop) =
                    create_bls_proof_of_possession(vote_address, &bls_keypair);
                let vote_init = VoteInitV2 {
                    node_pubkey: identity.pubkey(),
                    authorized_voter: identity.pubkey(),
                    authorized_voter_bls_pubkey: bls_pubkey,
                    authorized_voter_bls_proof_of_possession: bls_pop,
                    ..VoteInitV2::default()
                };
                let vote_state = VoteStateV4::new(
                    &vote_init,
                    vote_address,
                    &identity.pubkey(),
                    &Clock::default(),
                );
                let mut account = solana_account::AccountSharedData::new(
                    *balance,
                    VoteStateV4::size_of(),
                    &solana_vote_program::id(),
                );
                account
                    .serialize_data(&VoteStateVersions::new_v4(vote_state))
                    .unwrap();
                bank.store_account(vote_address, &account);
            }

            if let Some(stake_amount) = &vote_op.delegate_stake_amount {
                let size = StakeStateV2::size_of();
                let rent_exempt_reserve = bank.rent_collector().rent.minimum_balance(size);
                let lamports = rent_exempt_reserve + stake_amount;
                let stake_account =
                    create_stake_account(lamports, *stake_amount, vote_address, bank.epoch());
                bank.store_account(&Pubkey::new_unique(), &stake_account);
            }

            let modify_vote_state = |modify_fn: &dyn Fn(&mut VoteStateV4)| {
                let mut vote_account = bank.get_account(vote_address).unwrap();
                let vote_state_versions = vote_account
                    .deserialize_data::<VoteStateVersions>()
                    .unwrap();
                let VoteStateVersions::V4(mut vote_state) = vote_state_versions else {
                    panic!("unexpected version");
                };

                modify_fn(&mut vote_state);

                vote_account
                    .serialize_data(&VoteStateVersions::V4(vote_state))
                    .unwrap();
                bank.store_account(vote_address, &vote_account);
            };

            if let Some(commission) = vote_op.new_commission {
                modify_vote_state(&|vote_state: &mut VoteStateV4| {
                    vote_state.inflation_rewards_commission_bps = commission as u16 * 100;
                });
            }

            if let Some(inflation_rewards_collector) = vote_op.new_inflation_rewards_collector {
                modify_vote_state(&|vote_state: &mut VoteStateV4| {
                    vote_state.inflation_rewards_collector = inflation_rewards_collector;
                });
            }

            if let Some(earned_credits) = vote_op.earned_credits {
                modify_vote_state(&|vote_state: &mut VoteStateV4| {
                    let last_credits = vote_state
                        .epoch_credits
                        .last()
                        .map(|(_epoch, credits, _)| *credits)
                        .unwrap_or(0);
                    vote_state.epoch_credits.push((
                        bank.epoch,
                        last_credits + earned_credits,
                        last_credits,
                    ));
                });
            }
        }

        // Advance bank to next epoch
        let slot = bank.slot() + SLOTS_PER_EPOCH;
        let prev_bank = bank.clone();
        let bank =
            Bank::new_from_parent_with_bank_forks(bank_forks, bank, SlotLeader::new_unique(), slot);

        for (vote_address, vote_op) in &op.vote_operations {
            // some tests delegate before the vote account exists
            let collector_address = bank
                .get_account(vote_address)
                .map(|vote_account| {
                    VoteStateV4::deserialize(vote_account.data(), vote_address)
                        .unwrap()
                        .inflation_rewards_collector
                })
                .unwrap_or(*vote_address);
            let recalculated_vote_reward =
                recalculate_reward_commission_for_tests(&bank, &collector_address);
            let vote_reward = bank
                .rewards
                .read()
                .unwrap()
                .iter()
                .find(|(address, _reward)| *address == collector_address)
                .map(|(_address, reward)| *reward);

            let prev_collector_balance = prev_bank
                .get_account(&collector_address)
                .unwrap_or_default()
                .lamports();
            let collector_balance = bank.get_balance(&collector_address);

            if vote_op.expect_reward {
                let reward_lamports = collector_balance
                    - prev_collector_balance
                    - vote_op.extra_reward_lamport_amount.unwrap_or(0);
                let expected_vote_reward = RewardInfo {
                    reward_type: RewardType::Voting,
                    lamports: reward_lamports as i64,
                    post_balance: collector_balance,
                    commission_bps: None,
                };

                assert_eq!(
                    vote_reward,
                    Some(expected_vote_reward),
                    "epoch {}: unexpected reward info",
                    op.epoch
                );

                assert_eq!(
                    recalculated_vote_reward,
                    Some(expected_vote_reward),
                    "epoch {}: unexpected recalculated reward info",
                    op.epoch
                );
            } else {
                assert!(
                    vote_reward.map(|reward| reward.lamports).unwrap_or(0) == 0,
                    "epoch {}: expected no reward",
                    op.epoch
                );
                assert!(
                    recalculated_vote_reward
                        .map(|reward| reward.lamports)
                        .unwrap_or(0)
                        == 0,
                    "epoch {}: expected no recalculated reward",
                    op.epoch
                );
            }
        }

        bank
    }

    #[test_case(true; "delay_commission_updates")]
    #[test_case(false; "instant_commission_updates")]
    fn test_calculate_stake_vote_rewards_new_vote_account(delay_commission_updates: bool) {
        let GenesisConfigInfo {
            mut genesis_config, ..
        } = genesis_utils::create_genesis_config_with_leader(
            1_000_000 * LAMPORTS_PER_SOL,
            &Pubkey::new_unique(),
            42 * LAMPORTS_PER_SOL,
        );

        genesis_config.epoch_schedule = EpochSchedule::new(SLOTS_PER_EPOCH);
        if !delay_commission_updates {
            deactivate_features(&mut genesis_config, &vec![delay_commission_updates::id()]);
        }

        let (bank, bank_forks) =
            Bank::new_for_tests(&genesis_config).wrap_with_bank_forks_for_tests();
        let vote_address = Pubkey::new_unique();

        // No reward should be given in the epoch that a vote account is
        // delegated to for the first time
        let mut bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 0,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        create_with_balance: Some(LAMPORTS_PER_SOL),
                        new_commission: Some(1),
                        earned_credits: Some(1000),
                        delegate_stake_amount: Some(LAMPORTS_PER_SOL),
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        // Check that if a vote account didn't exist two epochs ago (normal for
        // new vote accounts), that the reward commission falls back to the
        // commission from the end of the rewarded epoch.
        bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 1,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        new_commission: Some(2),
                        earned_credits: Some(1000),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 2,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        new_commission: Some(3),
                        earned_credits: Some(1000),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );
    }

    #[test]
    fn test_calculate_stake_vote_rewards_prestaked_vote_account() {
        let GenesisConfigInfo {
            mut genesis_config, ..
        } = genesis_utils::create_genesis_config_with_leader(
            1_000_000 * LAMPORTS_PER_SOL,
            &Pubkey::new_unique(),
            42 * LAMPORTS_PER_SOL,
        );

        genesis_config.epoch_schedule = EpochSchedule::new(SLOTS_PER_EPOCH);
        let (bank, bank_forks) =
            Bank::new_for_tests(&genesis_config).wrap_with_bank_forks_for_tests();
        assert!(bank.feature_set.snapshot().delay_commission_updates);

        let vote_address = Pubkey::new_unique();
        let mut bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 0,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        delegate_stake_amount: Some(LAMPORTS_PER_SOL),
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        // Check that if a new vote account is somehow already staked and
        // earning rewards in the epoch in which it was created, the reward
        // commission falls back to the latest commission rate for that epoch
        bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 1,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        create_with_balance: Some(LAMPORTS_PER_SOL),
                        new_commission: Some(1),
                        earned_credits: Some(1000),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        // And similarly, check that if a vote account didn't exist two epochs
        // ago, the reward commission falls back to the commission from the
        // previous epoch
        bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 2,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        new_commission: Some(2),
                        earned_credits: Some(1000),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 3,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        new_commission: Some(3),
                        earned_credits: Some(1000),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );
    }

    #[test]
    fn test_adjust_delegation_for_prestaked_vote_account() {
        let GenesisConfigInfo {
            mut genesis_config,
            voting_keypair,
            ..
        } = genesis_utils::create_genesis_config_with_leader(
            1_000_000 * LAMPORTS_PER_SOL,
            &Pubkey::new_unique(),
            42 * LAMPORTS_PER_SOL,
        );
        let genesis_vote_address = voting_keypair.pubkey();

        genesis_config.epoch_schedule = EpochSchedule::new(SLOTS_PER_EPOCH);
        genesis_config.rent = Rent::default();

        let (bank, bank_forks) =
            Bank::new_for_tests(&genesis_config).wrap_with_bank_forks_for_tests();

        let old_delegation = LAMPORTS_PER_SOL;
        let rent_exempt_amount = genesis_config.rent.minimum_balance(StakeStateV2::size_of());

        let vote_address = Pubkey::new_unique();

        // No rent exemption at all
        let stake_address_to_adjust = Pubkey::new_unique();
        let stake_account =
            create_stake_account(old_delegation, old_delegation, &vote_address, bank.epoch());
        bank.store_account(&stake_address_to_adjust, &stake_account);

        // Will be deactivated, below rent exemption
        let stake_address_to_deactivate = Pubkey::new_unique();
        let stake_account = create_stake_account(
            rent_exempt_amount - 1,
            rent_exempt_amount - 1,
            &vote_address,
            bank.epoch(),
        );
        bank.store_account(&stake_address_to_deactivate, &stake_account);

        // Make a vote account earn points, otherwise stakes don't get updated
        // at all
        let bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 0,
                vote_operations: vec![(
                    genesis_vote_address,
                    VoteOperations {
                        earned_credits: Some(1000),
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        // Advance bank to next slot for distribution, see adjustment
        let slot = bank.slot();
        let bank = Bank::new_from_parent_with_bank_forks(
            bank_forks.as_ref(),
            bank,
            SlotLeader::new_unique(),
            slot + 1,
        );

        let stake_account = bank.get_account(&stake_address_to_adjust).unwrap();
        let stake_state: StakeStateV2 = stake_account.state().unwrap();
        let new_delegation = stake_state.stake().unwrap().delegation.stake;
        assert_ne!(old_delegation, new_delegation);
        assert_eq!(old_delegation, new_delegation + rent_exempt_amount);

        let stake_account = bank.get_account(&stake_address_to_deactivate).unwrap();
        let stake_state: StakeStateV2 = stake_account.state().unwrap();
        let new_delegation = stake_state.stake().unwrap().delegation;
        assert_eq!(new_delegation.stake, 0);
        assert_eq!(new_delegation.deactivation_epoch, 0);
    }

    #[test]
    fn test_calculate_stake_vote_rewards_genesis_vote_account() {
        let GenesisConfigInfo {
            mut genesis_config,
            voting_keypair,
            ..
        } = genesis_utils::create_genesis_config_with_leader(
            1_000_000 * LAMPORTS_PER_SOL,
            &Pubkey::new_unique(),
            42 * LAMPORTS_PER_SOL,
        );

        genesis_config.epoch_schedule = EpochSchedule::new(SLOTS_PER_EPOCH);
        let (bank, bank_forks) =
            Bank::new_for_tests(&genesis_config).wrap_with_bank_forks_for_tests();
        assert!(bank.feature_set.snapshot().delay_commission_updates);

        let genesis_vote_address = voting_keypair.pubkey();

        // Check that staked genesis vote accounts use the initial commission
        // rate for the first reward epoch
        let mut bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 0,
                vote_operations: vec![(
                    genesis_vote_address,
                    VoteOperations {
                        new_commission: Some(1),
                        earned_credits: Some(1000),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        // Check that staked genesis vote accounts use the initial commission
        // rate for the second reward epoch too.
        bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 1,
                vote_operations: vec![(
                    genesis_vote_address,
                    VoteOperations {
                        new_commission: Some(2),
                        earned_credits: Some(1000),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 2,
                vote_operations: vec![(
                    genesis_vote_address,
                    VoteOperations {
                        earned_credits: Some(1000),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 3,
                vote_operations: vec![(
                    genesis_vote_address,
                    VoteOperations {
                        earned_credits: Some(1000),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 4,
                vote_operations: vec![(
                    genesis_vote_address,
                    VoteOperations {
                        earned_credits: Some(1000),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );
    }

    #[test]
    fn test_calculate_stake_vote_rewards() {
        agave_logger::setup();

        let expected_num_delegations = 1;
        let RewardBank {
            bank,
            voters,
            stakers,
        } = create_default_reward_bank(expected_num_delegations, SLOTS_PER_EPOCH).0;

        let vote_pubkey = voters.first().unwrap();
        let stake_pubkey = *stakers.first().unwrap();
        let stake_account = bank
            .load_slow_with_fixed_root(&bank.ancestors, &stake_pubkey)
            .unwrap()
            .0;

        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let mut rewards_metrics = RewardsMetrics::default();

        let point_value = PointValue {
            rewards: 100000, // lamports to split
            points: 1000,    // over these points
        };
        let tracer = |_event: &RewardCalculationEvent| {};
        let reward_calc_tracer = Some(tracer);
        let rewarded_epoch = bank.epoch();
        let stakes: RwLockReadGuard<Stakes<StakeAccount<Delegation>>> = bank.stakes_cache.stakes();
        let EpochRewardCalculateParamInfo {
            stake_history,
            stake_delegations,
            cached_vote_accounts,
        } = bank.get_epoch_params_for_recalculation(rewarded_epoch, &stakes);
        let (vote_rewards_accounts, stake_reward_calculation) = bank
            .calculate_stake_rewards_and_commissions(
                &stake_history,
                stake_delegations,
                cached_vote_accounts,
                rewarded_epoch,
                point_value,
                &AlpenglowEpochType::Tower,
                &thread_pool,
                reward_calc_tracer,
                &mut rewards_metrics,
            );
        drop(stakes);

        let vote_account = bank
            .load_slow_with_fixed_root(&bank.ancestors, vote_pubkey)
            .unwrap()
            .0;
        let vote_state = VoteStateV4::deserialize(vote_account.data(), vote_pubkey).unwrap();

        assert_eq!(vote_rewards_accounts.len(), 1);
        let reward_commission = vote_rewards_accounts.get(vote_pubkey).unwrap();
        let vote_rewards = 0;
        assert_eq!(reward_commission.commission_lamports, vote_rewards);
        assert_eq!(reward_commission.commission_bps, None);

        assert_eq!(stake_reward_calculation.stake_rewards.num_rewards(), 1);
        let expected_reward = {
            let stake_reward = 8_400_000_000_000;
            let stake_state: StakeStateV2 = stake_account.state().unwrap();
            let mut stake = stake_state.stake().unwrap();
            stake.credits_observed = vote_state.credits();
            stake.delegation.stake += stake_reward;
            PartitionedStakeReward {
                stake_pubkey,
                inflation: InflationReward {
                    stake,
                    stake_reward,
                    commission_bps: None,
                },
            }
        };
        assert_eq!(
            stake_reward_calculation
                .stake_rewards
                .get(0)
                .unwrap()
                .as_ref()
                .unwrap(),
            &expected_reward
        );
    }

    fn compare_stake_rewards(
        expected_stake_rewards: &[PartitionedStakeRewards],
        received_stake_rewards: &[PartitionedStakeRewards],
    ) {
        for (i, partition) in received_stake_rewards.iter().enumerate() {
            let expected_partition = &expected_stake_rewards[i];
            assert_eq!(partition, expected_partition);
        }
    }

    #[test]
    fn test_recalculate_stake_rewards() {
        let expected_num_delegations = 4;
        let num_rewards_per_block = 2;
        // Distribute 4 rewards over 2 blocks
        let (RewardBank { bank, .. }, bank_forks) = create_reward_bank(
            expected_num_delegations,
            num_rewards_per_block,
            SLOTS_PER_EPOCH,
        );
        let rewarded_epoch = bank.epoch() - 1;

        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let mut rewards_metrics = RewardsMetrics::default();
        let stakes = bank.stakes_cache.stakes();
        let EpochRewardCalculateParamInfo {
            stake_history,
            stake_delegations,
            cached_vote_accounts,
        } = bank.get_epoch_params_for_recalculation(rewarded_epoch, &stakes);
        let PartitionedRewardsCalculation {
            stake_rewards:
                StakeRewardCalculation {
                    stake_rewards: expected_stake_rewards,
                    ..
                },
            ..
        } = bank.calculate_rewards_for_partitioning(
            &stake_history,
            stake_delegations,
            cached_vote_accounts,
            rewarded_epoch,
            reward_epoch_delegated_stakes_for_tests(rewarded_epoch),
            null_tracer(),
            &thread_pool,
            &mut rewards_metrics,
        );
        drop(stakes);

        let epoch_rewards_sysvar = bank.get_epoch_rewards_sysvar();
        let (recalculated_rewards, recalculated_partition_indices) =
            bank.recalculate_stake_rewards(&epoch_rewards_sysvar, &thread_pool);

        let recalculated_rewards =
            build_partitioned_stake_rewards(&recalculated_rewards, &recalculated_partition_indices);

        let expected_partition_indices = hash_rewards_into_partitions(
            &expected_stake_rewards,
            &epoch_rewards_sysvar.parent_blockhash,
            epoch_rewards_sysvar.num_partitions as usize,
        );

        let expected_stake_rewards_partitioned =
            build_partitioned_stake_rewards(&expected_stake_rewards, &expected_partition_indices);

        assert_eq!(
            expected_stake_rewards_partitioned.len(),
            recalculated_rewards.len()
        );
        compare_stake_rewards(&expected_stake_rewards_partitioned, &recalculated_rewards);

        // Advance to first distribution block, ie. child block of the epoch
        // boundary; slot is advanced 2 to demonstrate that distribution works
        // on block-height, not slot
        let new_slot = bank.slot() + 2;
        let bank = Bank::new_from_parent_with_bank_forks(
            bank_forks.as_ref(),
            bank,
            SlotLeader::default(),
            new_slot,
        );

        let epoch_rewards_sysvar = bank.get_epoch_rewards_sysvar();
        let (recalculated_rewards, recalculated_partition_indices) =
            bank.recalculate_stake_rewards(&epoch_rewards_sysvar, &thread_pool);

        // Note that recalculated rewards are **NOT** the same as expected
        // rewards, which were calculated before any distribution. This is
        // because "Recalculated rewards" doesn't include already distributed
        // stake rewards. Therefore, the partition_indices are different too.
        // However, the actual rewards for the remaining partitions should be
        // the same. The following code use the test helper function to build
        // the partitioned stake rewards for the remaining partitions and verify
        // that they are the same.
        let recalculated_rewards =
            build_partitioned_stake_rewards(&recalculated_rewards, &recalculated_partition_indices);
        assert_eq!(
            expected_stake_rewards_partitioned.len(),
            recalculated_rewards.len()
        );
        // First partition has already been distributed, so recalculation
        // returns 0 rewards
        assert_eq!(recalculated_rewards[0].num_rewards(), 0);
        let starting_index = (bank.block_height() + 1
            - epoch_rewards_sysvar.distribution_starting_block_height)
            as usize;
        compare_stake_rewards(
            &expected_stake_rewards_partitioned[starting_index..],
            &recalculated_rewards[starting_index..],
        );

        // Advance until reward distribution has completed.
        let mut bank = bank;
        for _ in 1..bank.get_epoch_rewards_sysvar().num_partitions {
            assert!(bank.get_epoch_rewards_sysvar().active);
            let new_slot = bank.slot() + 1;
            bank = Arc::new(Bank::new_from_parent(bank, SlotLeader::default(), new_slot));
        }

        assert!(!bank.get_epoch_rewards_sysvar().active);
    }

    #[test]
    fn test_recalculate_partitioned_rewards() {
        let expected_num_delegations = 4;
        let num_rewards_per_block = 2;
        // Distribute 4 rewards over 2 blocks
        let mut stakes = vec![2_000_000_000; expected_num_delegations - 1];
        // Add stake large enough to be affected by total-rewards discrepancy
        stakes.push(40_000_000_000);
        let (RewardBank { bank, .. }, _bank_forks) = create_reward_bank_with_specific_stakes(
            stakes,
            num_rewards_per_block,
            SLOTS_PER_EPOCH - 1,
        );
        let rewarded_epoch = bank.epoch();

        // Advance to next epoch boundary to update EpochStakes Kludgy because
        // mutable Bank methods require the bank not be Arc-wrapped.
        let new_slot = bank.slot() + 1;
        let mut bank = Bank::new_from_parent(bank, SlotLeader::default(), new_slot);
        let expected_starting_block_height = bank.block_height() + 1;

        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let mut rewards_metrics = RewardsMetrics::default();
        let stakes = bank.stakes_cache.stakes();
        let EpochRewardCalculateParamInfo {
            stake_history,
            stake_delegations,
            cached_vote_accounts,
        } = bank.get_epoch_params_for_recalculation(rewarded_epoch, &stakes);
        let PartitionedRewardsCalculation {
            stake_rewards:
                StakeRewardCalculation {
                    stake_rewards: expected_stake_rewards,
                    ..
                },
            point_value,
            ..
        } = bank.calculate_rewards_for_partitioning(
            &stake_history,
            stake_delegations,
            cached_vote_accounts,
            rewarded_epoch,
            reward_epoch_delegated_stakes_for_tests(rewarded_epoch),
            null_tracer(),
            &thread_pool,
            &mut rewards_metrics,
        );
        drop(stakes);

        bank.recalculate_partitioned_rewards_if_active(|| &thread_pool);
        let EpochRewardStatus::Active(EpochRewardPhase::Distribution(
            StartBlockHeightAndPartitionedRewards {
                distribution_starting_block_height,
                all_stake_rewards: ref recalculated_rewards,
                ref partition_indices,
            },
        )) = bank.epoch_reward_status
        else {
            panic!("{:?} not active", bank.epoch_reward_status);
        };
        assert_eq!(
            expected_starting_block_height,
            distribution_starting_block_height
        );

        let recalculated_rewards =
            build_partitioned_stake_rewards(recalculated_rewards, partition_indices);

        let epoch_rewards_sysvar = bank.get_epoch_rewards_sysvar();
        let expected_partition_indices = hash_rewards_into_partitions(
            &expected_stake_rewards,
            &epoch_rewards_sysvar.parent_blockhash,
            epoch_rewards_sysvar.num_partitions as usize,
        );
        let expected_stake_rewards =
            build_partitioned_stake_rewards(&expected_stake_rewards, &expected_partition_indices);

        assert_eq!(expected_stake_rewards.len(), recalculated_rewards.len());
        compare_stake_rewards(&expected_stake_rewards, &recalculated_rewards);

        let sysvar = bank.get_epoch_rewards_sysvar();
        assert_eq!(point_value.rewards, sysvar.total_rewards);

        // Advance to first distribution slot (bank_forks kept in scope so parent has fork_graph)
        let mut bank =
            Bank::new_from_parent(Arc::new(bank), SlotLeader::default(), SLOTS_PER_EPOCH + 1);

        bank.recalculate_partitioned_rewards_if_active(|| &thread_pool);
        let EpochRewardStatus::Active(EpochRewardPhase::Distribution(
            StartBlockHeightAndPartitionedRewards {
                distribution_starting_block_height,
                all_stake_rewards: ref recalculated_rewards,
                ref partition_indices,
            },
        )) = bank.epoch_reward_status
        else {
            panic!("{:?} not active", bank.epoch_reward_status);
        };

        // Note that recalculated rewards are **NOT** the same as expected
        // rewards, which were calculated before any distribution. This is
        // because "Recalculated rewards" doesn't include already distributed
        // stake rewards. Therefore, the partition_indices are different too.
        // However, the actual rewards for the remaining partitions should be
        // the same. The following code use the test helper function to build
        // the partitioned stake rewards for the remaining partitions and verify
        // that they are the same.
        let recalculated_rewards =
            build_partitioned_stake_rewards(recalculated_rewards, partition_indices);
        assert_eq!(
            expected_starting_block_height,
            distribution_starting_block_height
        );
        assert_eq!(expected_stake_rewards.len(), recalculated_rewards.len());
        // First partition has already been distributed, so recalculation
        // returns 0 rewards
        assert_eq!(recalculated_rewards[0].num_rewards(), 0);
        let epoch_rewards_sysvar = bank.get_epoch_rewards_sysvar();
        let starting_index = (bank.block_height() + 1
            - epoch_rewards_sysvar.distribution_starting_block_height)
            as usize;
        compare_stake_rewards(
            &expected_stake_rewards[starting_index..],
            &recalculated_rewards[starting_index..],
        );

        // Advance until reward distribution has completed.
        let mut bank = bank;
        for _ in 1..bank.get_epoch_rewards_sysvar().num_partitions {
            assert!(bank.get_epoch_rewards_sysvar().active);
            let next_slot = bank.slot() + 1;
            bank = Bank::new_from_parent(Arc::new(bank), SlotLeader::default(), next_slot);
            bank.recalculate_partitioned_rewards_if_active(|| &thread_pool);
        }

        assert_eq!(bank.epoch_reward_status, EpochRewardStatus::Inactive);
    }

    #[test]
    fn test_recalculate_alpenglow_rewards_after_partial_distribution_uses_original_denominator() {
        let stake_lamports = 2_000_000_000;
        let validator_keypairs = vec![genesis_utils::ValidatorVoteKeypairs::new_rand()];
        let GenesisConfigInfo {
            mut genesis_config, ..
        } = genesis_utils::create_genesis_config_with_alpenglow_vote_accounts(
            1_000_000_000 * LAMPORTS_PER_SOL,
            &validator_keypairs,
            vec![stake_lamports],
        );
        genesis_config.epoch_schedule = EpochSchedule::new(SLOTS_PER_EPOCH);
        let features_to_deactivate = crate::slot_params::slot_time_feature_ids().to_vec();
        deactivate_features(&mut genesis_config, &features_to_deactivate);

        let mut accounts_db_config: AccountsDbConfig = ACCOUNTS_DB_CONFIG_FOR_TESTING;
        accounts_db_config.partitioned_epoch_rewards_config =
            PartitionedEpochRewardsConfig::new_for_test(1);
        let bank = Bank::new_from_genesis(
            &genesis_config,
            Arc::new(RuntimeConfig::default()),
            Vec::new(),
            None,
            accounts_db_config,
            None,
            None,
            Arc::default(),
            None,
            None,
        );

        let vote_pubkey = validator_keypairs[0].vote_keypair.pubkey();
        let vote_account = bank.get_account(&vote_pubkey).unwrap();
        let extra_stake_pubkey = Pubkey::new_unique();
        let extra_stake_account = stake_utils::create_stake_account(
            &extra_stake_pubkey,
            &vote_pubkey,
            &vote_account,
            &bank.rent_collector.rent,
            stake_lamports,
        );
        bank.store_account_and_update_capitalization(&extra_stake_pubkey, &extra_stake_account);

        let (bank, bank_forks) = bank.wrap_with_bank_forks_for_tests();
        let bank = Bank::new_from_parent_with_bank_forks(
            bank_forks.as_ref(),
            bank,
            SlotLeader::default(),
            SLOTS_PER_EPOCH,
        );
        assert_eq!(bank.epoch(), 1);

        let mut vote_account = bank.get_account(&vote_pubkey).unwrap();
        let VoteStateVersions::V4(mut vote_state) = vote_account
            .deserialize_data::<VoteStateVersions>()
            .unwrap()
        else {
            panic!("unexpected vote state version");
        };
        let last_credits = vote_state
            .epoch_credits
            .last()
            .map(|(_epoch, final_credits, _initial_credits)| *final_credits)
            .unwrap_or_default();
        vote_state
            .epoch_credits
            .push((bank.epoch(), last_credits + 1_000_000, last_credits));
        vote_account
            .serialize_data(&VoteStateVersions::V4(vote_state))
            .unwrap();
        bank.store_account(&vote_pubkey, &vote_account);

        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let mut bank = Bank::new_from_parent(
            bank,
            SlotLeader::default(),
            SLOTS_PER_EPOCH.saturating_mul(2),
        );
        assert_eq!(bank.epoch(), 2);

        let EpochRewardStatus::Active(EpochRewardPhase::Calculation(calculation_status)) =
            bank.epoch_reward_status.clone()
        else {
            panic!("{:?} not active calculation", bank.epoch_reward_status);
        };
        let original_stake_rewards = calculation_status.all_stake_rewards;
        let original_rewards = original_stake_rewards
            .enumerated_rewards_iter()
            .collect::<Vec<_>>();
        assert_eq!(original_rewards.len(), 2);
        let (paid_index, paid_reward) = original_rewards[0];
        let (unpaid_index, unpaid_reward) = original_rewards[1];
        assert!(paid_reward.inflation.stake_reward > 0);
        assert!(unpaid_reward.inflation.stake_reward > 0);

        // Force exactly one stake reward to be distributed before simulating
        // snapshot restore. That write updates StakesCache with a larger
        // delegation for the same vote account.
        bank.set_epoch_reward_status_distribution(
            bank.block_height(),
            Arc::clone(&original_stake_rewards),
            vec![vec![paid_index], vec![unpaid_index]],
        );
        bank.distribute_partitioned_epoch_rewards();

        let epoch_rewards_sysvar = bank.get_epoch_rewards_sysvar();
        assert!(epoch_rewards_sysvar.active);
        let (recalculated_stake_rewards, _partition_indices) =
            bank.recalculate_stake_rewards(&epoch_rewards_sysvar, &thread_pool);
        let recalculated_unpaid_reward = recalculated_stake_rewards
            .enumerated_rewards_iter()
            .find_map(|(_index, reward)| {
                (reward.stake_pubkey == unpaid_reward.stake_pubkey).then_some(reward)
            })
            .expect("unpaid stake reward must still be pending after recalculation");

        assert_eq!(
            unpaid_reward.inflation.stake_reward, recalculated_unpaid_reward.inflation.stake_reward,
            "recalculation after partial distribution must use the same AG delegated stake \
             denominator as the original epoch-boundary calculation"
        );
    }

    #[test]
    fn test_alpenglow_reward_epoch_delegated_stakes_account_is_bounded() {
        let num_validators = crate::bank::MAX_ALPENGLOW_VOTE_ACCOUNTS + 1;
        let validator_keypairs = (0..num_validators)
            .map(|_| genesis_utils::ValidatorVoteKeypairs::new_rand())
            .collect::<Vec<_>>();
        // Unique stakes make VAT filtering exclude only the lowest-staked vote
        // account instead of dropping a tie group at the boundary.
        let stakes = (0..num_validators)
            .map(|index| 2_000_000_000 + (num_validators - index) as u64)
            .collect::<Vec<_>>();
        let filtered_vote_pubkey = validator_keypairs
            .last()
            .expect("validator keypairs must not be empty")
            .vote_keypair
            .pubkey();
        let GenesisConfigInfo {
            mut genesis_config, ..
        } = genesis_utils::create_genesis_config_with_alpenglow_vote_accounts(
            1_000_000_000 * LAMPORTS_PER_SOL,
            &validator_keypairs,
            stakes,
        );
        genesis_config.epoch_schedule = EpochSchedule::new(SLOTS_PER_EPOCH);
        let features_to_deactivate = crate::slot_params::slot_time_feature_ids().to_vec();
        deactivate_features(&mut genesis_config, &features_to_deactivate);

        let (bank, bank_forks) =
            Bank::new_for_tests(&genesis_config).wrap_with_bank_forks_for_tests();
        let bank = Bank::new_from_parent_with_bank_forks(
            bank_forks.as_ref(),
            bank,
            SlotLeader::default(),
            SLOTS_PER_EPOCH,
        );

        let reward_epoch_delegated_stakes = RewardEpochDelegatedStakes::get(&bank)
            .expect("AG reward epoch delegated stakes must be persisted");
        assert_eq!(reward_epoch_delegated_stakes.epoch, bank.epoch() - 1);
        assert_eq!(
            reward_epoch_delegated_stakes.delegated_stakes.len(),
            crate::bank::MAX_ALPENGLOW_VOTE_ACCOUNTS
        );
        assert!(
            !reward_epoch_delegated_stakes
                .delegated_stakes
                .contains_key(&filtered_vote_pubkey)
        );
    }

    #[test]
    fn test_initialize_after_snapshot_restore() {
        let expected_num_stake_rewards = 4;
        let num_rewards_per_block = 2;
        // Distribute 4 rewards over 2 blocks
        let stakes = vec![
            100_000_000,   // valid delegation
            2_000_000_000, // valid delegation
            3_000_000_000, // valid delegation
            4_000_000_000, // valid delegation
        ];
        let (RewardBank { bank, .. }, bank_forks) = create_reward_bank_with_specific_stakes(
            stakes,
            num_rewards_per_block,
            SLOTS_PER_EPOCH - 1,
        );

        // Advance to next epoch boundary (bank_forks kept in scope so parent has fork_graph)
        let new_slot = bank.slot() + 1;
        let mut bank = Bank::new_from_parent(bank, SlotLeader::default(), new_slot);

        let EpochRewardStatus::Active(EpochRewardPhase::Calculation(calculation_status)) =
            bank.epoch_reward_status.clone()
        else {
            panic!("{:?} not active calculation", bank.epoch_reward_status);
        };

        // Reset feature set to default, to simulate snapshot restore
        bank.feature_set = Arc::new(FeatureSet::default());

        // Run post snapshot restore initialization which should first apply
        // active features and then recalculate rewards
        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        bank.initialize_after_snapshot_restore(|| &thread_pool);

        let EpochRewardStatus::Active(EpochRewardPhase::Distribution(distribution_status)) =
            bank.epoch_reward_status.clone()
        else {
            panic!("{:?} not active distribution", bank.epoch_reward_status);
        };

        assert_eq!(
            calculation_status.all_stake_rewards,
            distribution_status.all_stake_rewards
        );
        assert_eq!(
            calculation_status.distribution_starting_block_height,
            distribution_status.distribution_starting_block_height
        );
        assert_eq!(
            calculation_status.all_stake_rewards.num_rewards(),
            expected_num_stake_rewards
        );
        let _ = &bank_forks; // Keep in scope so parent banks retain fork_graph
    }

    #[test]
    fn test_initialize_after_snapshot_restore_preserves_vat_filtered_rewards() {
        let num_validators = crate::bank::MAX_ALPENGLOW_VOTE_ACCOUNTS + 1;
        let num_rewards_per_block = 64;
        // Use unique stakes so VAT filtering deterministically excludes exactly
        // the lowest-staked validator instead of dropping an entire tie group.
        let stakes = (0..num_validators)
            .map(|index| 2_000_000_000 + (num_validators - index) as u64)
            .collect::<Vec<_>>();
        let (
            RewardBank {
                bank,
                voters,
                stakers,
            },
            bank_forks,
        ) = create_reward_bank_with_specific_stakes(
            stakes,
            num_rewards_per_block,
            SLOTS_PER_EPOCH - 1,
        );

        let filtered_vote_pubkey = *voters.last().unwrap();
        let filtered_stake_pubkey = *stakers.last().unwrap();

        // Advance to the epoch boundary, which computes the original in-memory
        // reward list and updates EpochStakes for the new epoch.
        let new_slot = bank.slot() + 1;
        let mut bank = Bank::new_from_parent(bank, SlotLeader::default(), new_slot);

        let leader_schedule_epoch = bank.epoch_schedule().get_leader_schedule_epoch(bank.slot());
        let filtered_epoch_vote_accounts = bank
            .epoch_stakes(leader_schedule_epoch)
            .unwrap()
            .stakes()
            .vote_accounts();
        assert_eq!(
            bank.stakes_cache.stakes().vote_accounts().len(),
            num_validators
        );
        assert_eq!(
            filtered_epoch_vote_accounts.len(),
            crate::bank::MAX_ALPENGLOW_VOTE_ACCOUNTS
        );
        assert!(
            filtered_epoch_vote_accounts
                .get(&filtered_vote_pubkey)
                .is_none()
        );

        let EpochRewardStatus::Active(EpochRewardPhase::Calculation(calculation_status)) =
            bank.epoch_reward_status.clone()
        else {
            panic!("{:?} not active calculation", bank.epoch_reward_status);
        };
        assert_eq!(
            calculation_status.all_stake_rewards.num_rewards(),
            crate::bank::MAX_ALPENGLOW_VOTE_ACCOUNTS
        );
        assert!(
            calculation_status
                .all_stake_rewards
                .enumerated_rewards_iter()
                .all(|(_, reward)| reward.stake_pubkey != filtered_stake_pubkey)
        );
        // Simulate snapshot restore: re-apply features from accounts and
        // rebuild epoch_reward_status from snapshot-stable state.
        bank.feature_set = Arc::new(FeatureSet::default());
        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        bank.initialize_after_snapshot_restore(|| &thread_pool);

        let EpochRewardStatus::Active(EpochRewardPhase::Distribution(distribution_status)) =
            bank.epoch_reward_status.clone()
        else {
            panic!("{:?} not active distribution", bank.epoch_reward_status);
        };
        assert_eq!(
            distribution_status.all_stake_rewards.num_rewards(),
            crate::bank::MAX_ALPENGLOW_VOTE_ACCOUNTS
        );
        assert!(
            distribution_status
                .all_stake_rewards
                .enumerated_rewards_iter()
                .all(|(_, reward)| reward.stake_pubkey != filtered_stake_pubkey)
        );

        assert_eq!(
            calculation_status.distribution_starting_block_height,
            distribution_status.distribution_starting_block_height
        );
        assert_eq!(
            calculation_status.all_stake_rewards,
            distribution_status.all_stake_rewards
        );
        let _ = &bank_forks; // Keep in scope so parent banks retain fork_graph
    }

    #[test]
    fn test_reward_accumulator() {
        let mut accumulator1 = RewardsAccumulator::default();
        let mut accumulator2 = RewardsAccumulator::default();

        let commission_pubkey_a = Pubkey::new_unique();
        let commission_pubkey_b = Pubkey::new_unique();
        let commission_pubkey_c = Pubkey::new_unique();

        accumulator1.add_reward(
            commission_pubkey_a,
            RewardCommission {
                commission_bps: Some(1_000),
                commission_lamports: 50,
                burned_lamports: 0,
                is_vote_account: true,
            },
            50,
        );
        accumulator1.add_reward(
            commission_pubkey_b,
            RewardCommission {
                commission_bps: Some(1_000),
                commission_lamports: 50,
                burned_lamports: 0,
                is_vote_account: true,
            },
            50,
        );
        accumulator2.add_reward(
            commission_pubkey_b,
            RewardCommission {
                commission_bps: Some(1_000),
                commission_lamports: 30,
                burned_lamports: 0,
                is_vote_account: true,
            },
            30,
        );
        accumulator2.add_reward(
            commission_pubkey_c,
            RewardCommission {
                commission_bps: Some(1_000),
                commission_lamports: 50,
                burned_lamports: 0,
                is_vote_account: true,
            },
            50,
        );

        assert_eq!(accumulator1.num_stake_rewards, 2);
        assert_eq!(accumulator1.total_stake_rewards_lamports, 100);
        let reward_commission_a_1 = accumulator1
            .reward_commissions
            .get(&commission_pubkey_a)
            .unwrap();
        assert_eq!(reward_commission_a_1.commission_bps, Some(1_000));
        assert_eq!(reward_commission_a_1.commission_lamports, 50);

        let reward_commission_b_1 = accumulator1
            .reward_commissions
            .get(&commission_pubkey_b)
            .unwrap();
        assert_eq!(reward_commission_b_1.commission_bps, Some(1_000));
        assert_eq!(reward_commission_b_1.commission_lamports, 50);

        let reward_commission_b_2 = accumulator2
            .reward_commissions
            .get(&commission_pubkey_b)
            .unwrap();
        assert_eq!(reward_commission_b_2.commission_bps, Some(1_000));
        assert_eq!(reward_commission_b_2.commission_lamports, 30);

        let reward_commission_c_2 = accumulator2
            .reward_commissions
            .get(&commission_pubkey_c)
            .unwrap();
        assert_eq!(reward_commission_c_2.commission_bps, Some(1_000));
        assert_eq!(reward_commission_c_2.commission_lamports, 50);

        let accumulator = accumulator1.accumulate_into_larger(accumulator2);

        assert_eq!(accumulator.num_stake_rewards, 4);
        assert_eq!(accumulator.total_stake_rewards_lamports, 180);
        let reward_commission_a = accumulator
            .reward_commissions
            .get(&commission_pubkey_a)
            .unwrap();
        assert_eq!(reward_commission_a.commission_bps, Some(1_000));
        assert_eq!(reward_commission_a.commission_lamports, 50);

        let reward_commission_b = accumulator
            .reward_commissions
            .get(&commission_pubkey_b)
            .unwrap();
        assert_eq!(reward_commission_b.commission_bps, Some(1_000));
        // sum of the reward commissions from both accumulators
        assert_eq!(reward_commission_b.commission_lamports, 80);

        let reward_commission_c = accumulator
            .reward_commissions
            .get(&commission_pubkey_c)
            .unwrap();
        assert_eq!(reward_commission_c.commission_bps, Some(1_000));
        assert_eq!(reward_commission_c.commission_lamports, 50);
    }

    fn check_accumulator(
        accumulator: &RewardsAccumulator,
        commission_pubkey: &Pubkey,
        left_reward: &RewardCommission,
        right_reward: &RewardCommission,
    ) {
        let reward_commission = accumulator
            .reward_commissions
            .get(commission_pubkey)
            .unwrap();

        assert_eq!(
            left_reward.is_vote_account || right_reward.is_vote_account,
            reward_commission.is_vote_account
        );
        match (left_reward.is_vote_account, right_reward.is_vote_account) {
            (false, true) => {
                assert_eq!(
                    reward_commission.commission_lamports,
                    right_reward.commission_lamports
                );
                assert_eq!(
                    reward_commission.burned_lamports,
                    left_reward.burned_lamports
                        + right_reward.burned_lamports
                        + left_reward.commission_lamports
                );
            }
            (true, false) => {
                assert_eq!(
                    reward_commission.commission_lamports,
                    left_reward.commission_lamports
                );
                assert_eq!(
                    reward_commission.burned_lamports,
                    left_reward.burned_lamports
                        + right_reward.burned_lamports
                        + right_reward.commission_lamports
                );
            }
            _ => {
                assert_eq!(
                    reward_commission.commission_lamports,
                    left_reward.commission_lamports + right_reward.commission_lamports
                );
                assert_eq!(
                    reward_commission.burned_lamports,
                    left_reward.burned_lamports + right_reward.burned_lamports
                );
            }
        }
    }

    #[test_matrix(
        [false, true],
        [false, true]
    )]
    fn test_reward_accumulator_add_rewards(
        left_is_vote_account: bool,
        right_is_vote_account: bool,
    ) {
        let mut accumulator = RewardsAccumulator::default();
        let commission_pubkey = Pubkey::new_unique();
        let commission_bps = Some(1_000);

        let left_reward = RewardCommission {
            commission_bps,
            commission_lamports: 1,
            burned_lamports: 10,
            is_vote_account: left_is_vote_account,
        };

        let right_reward = RewardCommission {
            commission_bps,
            commission_lamports: 100,
            burned_lamports: 1_000,
            is_vote_account: right_is_vote_account,
        };
        accumulator.add_reward(commission_pubkey, left_reward.clone(), 50);
        accumulator.add_reward(commission_pubkey, right_reward.clone(), 50);

        check_accumulator(
            &accumulator,
            &commission_pubkey,
            &left_reward,
            &right_reward,
        );
    }

    #[test_matrix(
        [false, true],
        [false, true],
        [false, true]
    )]
    fn test_reward_accumulator_accumulate_into_larger(
        left_is_vote_account: bool,
        right_is_vote_account: bool,
        right_is_larger: bool,
    ) {
        let mut accumulator1 = RewardsAccumulator::default();
        let mut accumulator2 = RewardsAccumulator::default();
        let commission_pubkey = Pubkey::new_unique();
        let commission_bps = Some(1_000);

        let left_reward = RewardCommission {
            commission_bps,
            commission_lamports: 1,
            burned_lamports: 10,
            is_vote_account: left_is_vote_account,
        };

        let right_reward = RewardCommission {
            commission_bps,
            commission_lamports: 100,
            burned_lamports: 1_000,
            is_vote_account: right_is_vote_account,
        };

        accumulator1.add_reward(commission_pubkey, left_reward.clone(), 50);
        accumulator2.add_reward(commission_pubkey, right_reward.clone(), 50);

        let additional_commission_pubkey = Pubkey::new_unique();
        let additional_reward_commission = RewardCommission {
            commission_bps,
            commission_lamports: 1,
            burned_lamports: 2,
            is_vote_account: true,
        };
        if right_is_larger {
            accumulator2.add_reward(
                additional_commission_pubkey,
                additional_reward_commission,
                50,
            );
        } else {
            accumulator1.add_reward(
                additional_commission_pubkey,
                additional_reward_commission,
                50,
            );
        };

        let accumulator = accumulator1.accumulate_into_larger(accumulator2);
        check_accumulator(
            &accumulator,
            &commission_pubkey,
            &left_reward,
            &right_reward,
        );
    }

    #[test]
    fn test_epoch_rewards_cache_multiple_forks() {
        let (mut genesis_config, _mint_keypair) =
            create_genesis_config(1_000_000 * LAMPORTS_PER_SOL);

        const NUM_STAKES: usize = 1000;

        for _i in 0..NUM_STAKES {
            let vote_pubkey = Pubkey::new_unique();
            let stake_pubkey = Pubkey::new_unique();

            genesis_config.accounts.insert(
                vote_pubkey,
                vote_state::create_v4_account_with_authorized(
                    &vote_pubkey,
                    &vote_pubkey,
                    [0u8; BLS_PUBLIC_KEY_COMPRESSED_SIZE],
                    &vote_pubkey,
                    0,
                    &vote_pubkey,
                    0,
                    &vote_pubkey,
                    100_000_000_000,
                )
                .into(),
            );

            let stake_lamports = 1_000_000_000_000;
            let stake_account = stake_utils::create_stake_account(
                &stake_pubkey,
                &vote_pubkey,
                &vote_state::create_v4_account_with_authorized(
                    &vote_pubkey,
                    &vote_pubkey,
                    [0u8; BLS_PUBLIC_KEY_COMPRESSED_SIZE],
                    &vote_pubkey,
                    0,
                    &vote_pubkey,
                    0,
                    &vote_pubkey,
                    100_000_000_000,
                ),
                &genesis_config.rent,
                stake_lamports,
            );
            genesis_config
                .accounts
                .insert(stake_pubkey, stake_account.into());
        }

        let (bank, bank_forks) =
            Bank::new_for_tests(&genesis_config).wrap_with_bank_forks_for_tests();
        let next_epoch_slot = bank.get_slots_in_epoch(bank.epoch());
        {
            let cache = bank.epoch_rewards_calculation_cache.lock().unwrap();
            assert!(
                !cache.contains_key(&bank.parent_hash()),
                "cache should be empty"
            );
        }

        let bank_fork1 = Bank::new_from_parent_with_bank_forks(
            bank_forks.as_ref(),
            bank.clone(),
            SlotLeader::default(),
            next_epoch_slot,
        );
        {
            let cache = bank_fork1.epoch_rewards_calculation_cache.lock().unwrap();
            assert!(
                cache.contains_key(&bank_fork1.parent_hash()),
                "cache should be populated"
            );
        }

        // Use new_from_parent (not _with_bank_forks) - we can't insert two banks at same slot
        let bank_fork2 = Arc::new(Bank::new_from_parent(
            bank.clone(),
            SlotLeader::default(),
            next_epoch_slot,
        ));
        {
            let cache = bank_fork2.epoch_rewards_calculation_cache.lock().unwrap();
            assert!(
                cache.contains_key(&bank_fork2.parent_hash()),
                "cache should be populated"
            );
        }
    }

    fn add_voters_and_populate(
        bank: &Arc<Bank>,
        voters: &mut HashSet<Pubkey>,
        stakers: &mut HashSet<Pubkey>,
        count: usize,
        stake_lamports: u64,
        commission: u8,
    ) {
        for _ in 0..count {
            let ((vote_pubkey, vote_account), (stake_pubkey, stake_account)) =
                create_staked_node_accounts(stake_lamports, &bank.rent_collector.rent);
            bank.store_account_and_update_capitalization(&vote_pubkey, &vote_account);
            bank.store_account_and_update_capitalization(&stake_pubkey, &stake_account);
            voters.insert(vote_pubkey);
            stakers.insert(stake_pubkey);
        }
        populate_vote_accounts_with_votes(bank, voters.iter().copied(), commission);
    }

    #[allow(clippy::too_many_arguments)]
    fn assert_cached_rewards(
        bank: &Arc<Bank>,
        expected_cache_len: usize,
        expected_voters: &HashSet<Pubkey>,
        expected_stakers: &HashSet<Pubkey>,
        expected_reward_commissions: u64,
        expected_stake_rewards: u64,
        expected_rewards: u64,
        expected_points: u128,
        parent_capitalization: Option<u64>,
    ) {
        let cache = bank.epoch_rewards_calculation_cache.lock().unwrap();
        assert_eq!(cache.len(), expected_cache_len);
        let partitioned = cache.get(&bank.parent_hash()).unwrap().as_ref();
        let reward_commissions = &partitioned.reward_commissions;
        let StakeRewardCalculation {
            stake_rewards,
            total_stake_rewards_lamports,
            ..
        } = &partitioned.stake_rewards;
        let point_value = &partitioned.point_value;
        let voters: HashSet<_> = reward_commissions.keys().copied().collect();
        let stakers: HashSet<_> = stake_rewards
            .rewards
            .iter()
            .filter_map(|reward| reward.as_ref())
            .map(|reward| reward.stake_pubkey)
            .collect();
        assert_eq!(expected_voters, &voters);
        assert_eq!(expected_stakers, &stakers);
        let total_reward_commission_lamports: u64 = reward_commissions
            .values()
            .map(|rc| rc.commission_lamports)
            .sum();
        assert_eq!(
            total_reward_commission_lamports,
            expected_reward_commissions
        );
        assert_eq!(*total_stake_rewards_lamports, expected_stake_rewards);
        assert_eq!(point_value.rewards, expected_rewards);
        assert_eq!(point_value.points, expected_points);
        if let Some(parent_cap) = parent_capitalization {
            assert_eq!(
                bank.capitalization(),
                parent_cap + expected_reward_commissions
            );
        }
    }

    #[test]
    fn test_epoch_boundary() {
        let delegations = 100;
        let stake_lamports = 2_000_000_000;
        let stakes: Vec<_> = (0..delegations).map(|_| stake_lamports).collect();
        let (
            RewardBank {
                bank: bank1,
                voters,
                stakers,
                ..
            },
            _bank_forks,
        ) = create_reward_bank_with_specific_stakes(
            stakes,
            PartitionedEpochRewardsConfig::default().stake_account_stores_per_block,
            SLOTS_PER_EPOCH,
        );
        let mut voters: HashSet<_> = voters.into_iter().collect();
        let mut stakers: HashSet<_> = stakers.into_iter().collect();

        // The sysvar account holds the rent-exempt lamport added after
        // reward calculation, so the bank capitalization exceeds the cached
        // value by this amount.
        let epoch_rewards_sysvar_balance = bank1.get_balance(&solana_sysvar::epoch_rewards::id());
        assert_eq!(epoch_rewards_sysvar_balance, 1);

        assert_cached_rewards(
            &bank1,
            1,                     // expected_cache_len
            &voters,               // expected_voters
            &stakers,              // expected_stakers
            0,                     // expected_reward_commissions
            499500,                // expected_stake_rewards
            499542,                // expected_rewards
            8_400_000_000_000u128, // expected_points
            None,                  // parent_capitalization
        );

        add_voters_and_populate(&bank1, &mut voters, &mut stakers, 5, 5_000_000_000, 10);
        let parent_capitalization = bank1.capitalization();

        let bank2 = Arc::new(Bank::new_from_parent(
            Arc::clone(&bank1),
            SlotLeader::default(),
            SLOTS_PER_EPOCH * 2,
        ));

        assert_cached_rewards(
            &bank2,
            2,                           // expected_cache_len
            &voters,                     // expected_voters
            &stakers,                    // expected_stakers
            5555,                        // expected_reward_commissions
            494730,                      // expected_stake_rewards
            500313,                      // expected_rewards
            9_450_000_000_000u128,       // expected_points
            Some(parent_capitalization), // parent_capitalization
        );

        add_voters_and_populate(&bank2, &mut voters, &mut stakers, 10, 8_000_000_000, 10);
        let parent_capitalization = bank2.capitalization();

        let bank3 = Arc::new(Bank::new_from_parent(
            Arc::clone(&bank2),
            SlotLeader::default(),
            SLOTS_PER_EPOCH * 3,
        ));

        assert_cached_rewards(
            &bank3,
            3,                           // expected_cache_len
            &voters,                     // expected_voters
            &stakers,                    // expected_stakers
            17300,                       // expected_reward_commissions
            485365,                      // expected_stake_rewards
            502779,                      // expected_rewards
            12_810_000_000_000u128,      // expected_points
            Some(parent_capitalization), // parent_capitalization
        );
    }

    #[test]
    fn test_load_and_reward_commission_accounts_empty() {
        let (genesis_config, _mint_keypair) = create_genesis_config(LAMPORTS_PER_SOL);
        let bank = Bank::new_for_tests(&genesis_config);
        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let reward_commissions = RewardCommissions::default();
        let result = bank.load_and_reward_commission_accounts(&reward_commissions, &thread_pool);
        assert!(result.accounts_with_rewards.is_empty());
    }

    #[test]
    fn test_load_and_reward_commission_accounts_overflow() {
        let (genesis_config, _mint_keypair) = create_genesis_config(LAMPORTS_PER_SOL);
        let bank = Bank::new_for_tests(&genesis_config);
        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let pubkey = solana_pubkey::new_rand();
        let mut commission_account = AccountSharedData::default();
        commission_account.set_lamports(u64::MAX);
        bank.store_account_and_update_capitalization(&pubkey, &commission_account);
        let mut reward_commissions = RewardCommissions::default();
        reward_commissions.insert(
            pubkey,
            RewardCommission {
                commission_bps: Some(0),
                commission_lamports: 1, // enough to overflow
                burned_lamports: 0,
                is_vote_account: true,
            },
        );
        let result = bank.load_and_reward_commission_accounts(&reward_commissions, &thread_pool);
        assert!(result.accounts_with_rewards.is_empty());
    }

    #[test]
    fn test_load_and_reward_commission_accounts_reflects_vat_burn() {
        let (genesis_config, _mint_keypair) = create_genesis_config(1_000 * LAMPORTS_PER_SOL);
        let bank = Bank::new_for_tests(&genesis_config);
        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let pubkey = solana_pubkey::new_rand();

        let pre_burn_balance = 10 * crate::bank::DEFAULT_VAT_TO_BURN_PER_EPOCH;
        let commission_lamports = 12_345;

        // Commission is planned against the pre-burn account state.
        let mut commission_account = AccountSharedData::default();
        commission_account.set_lamports(pre_burn_balance);
        bank.store_account_and_update_capitalization(&pubkey, &commission_account);
        let mut reward_commissions = RewardCommissions::default();
        reward_commissions.insert(
            pubkey,
            RewardCommission {
                commission_bps: Some(500),
                commission_lamports,
                burned_lamports: 0,
                is_vote_account: true,
            },
        );

        // Simulate the VAT burn that would run in `update_epoch_stakes`
        // between reward calculation and distribution.
        let post_burn_balance = pre_burn_balance - crate::bank::DEFAULT_VAT_TO_BURN_PER_EPOCH;
        let mut burned_account = commission_account.clone();
        burned_account.set_lamports(post_burn_balance);
        bank.store_account_and_update_capitalization(&pubkey, &burned_account);

        let result = bank.load_and_reward_commission_accounts(&reward_commissions, &thread_pool);

        assert_eq!(result.accounts_with_rewards.len(), 1);
        let (pubkey_result, reward_info, account) = &result.accounts_with_rewards[0];
        assert_eq!(*pubkey_result, pubkey);
        // Commission is credited on top of the post-burn balance, not the
        // pre-burn snapshot captured at calculation time.
        let expected_post_balance = post_burn_balance + commission_lamports;
        assert_eq!(account.lamports(), expected_post_balance);
        assert_eq!(
            *reward_info,
            RewardInfo {
                reward_type: RewardType::Voting,
                lamports: commission_lamports as i64,
                post_balance: expected_post_balance,
                commission_bps: Some(500),
            }
        );
        assert_eq!(result.amounts.distributed_lamports, commission_lamports);
    }

    #[test]
    fn test_load_and_reward_commission_accounts_normal() {
        let (genesis_config, _mint_keypair) = create_genesis_config(1_000 * LAMPORTS_PER_SOL);
        let bank = Bank::new_for_tests(&genesis_config);
        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let pubkey = solana_pubkey::new_rand();
        for commission_bps in [0, 100] {
            for commission_lamports in 0..2 {
                let mut commission_account = AccountSharedData::default();
                commission_account.set_lamports(1);
                bank.store_account_and_update_capitalization(&pubkey, &commission_account);
                let mut reward_commissions = RewardCommissions::default();
                reward_commissions.insert(
                    pubkey,
                    RewardCommission {
                        commission_bps: Some(commission_bps),
                        commission_lamports,
                        burned_lamports: 0,
                        is_vote_account: true,
                    },
                );
                let result =
                    bank.load_and_reward_commission_accounts(&reward_commissions, &thread_pool);
                assert_eq!(result.accounts_with_rewards.len(), 1);
                let (pubkey_result, rewards, account) = &result.accounts_with_rewards[0];
                _ = commission_account.checked_add_lamports(commission_lamports);
                assert!(accounts_equal(account, &commission_account));

                let expected_reward_info = RewardInfo {
                    reward_type: RewardType::Voting,
                    lamports: commission_lamports as i64,
                    post_balance: commission_account.lamports(),
                    commission_bps: Some(commission_bps),
                };
                assert_eq!(*rewards, expected_reward_info);
                assert_eq!(*pubkey_result, pubkey);
            }
        }
    }

    #[test]
    fn test_inflation_rewards_collector() {
        let GenesisConfigInfo {
            mut genesis_config, ..
        } = genesis_utils::create_genesis_config_with_leader(
            1_000_000 * LAMPORTS_PER_SOL,
            &Pubkey::new_unique(),
            42 * LAMPORTS_PER_SOL,
        );

        genesis_config.rent = Rent::default();
        genesis_config.epoch_schedule = EpochSchedule::new(SLOTS_PER_EPOCH);

        let (bank, bank_forks) =
            Bank::new_for_tests(&genesis_config).wrap_with_bank_forks_for_tests();
        let vote_address = Pubkey::new_unique();

        // Vote account just created
        let mut bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 0,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        create_with_balance: Some(LAMPORTS_PER_SOL),
                        new_commission: Some(1),
                        earned_credits: Some(1000),
                        delegate_stake_amount: Some(LAMPORTS_PER_SOL),
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        for (epoch, (collector_address, maybe_account, expect_reward)) in [
            // system account with lamports, success
            (
                Pubkey::new_unique(),
                Some(AccountSharedData::new(
                    LAMPORTS_PER_SOL,
                    0,
                    &solana_sdk_ids::system_program::id(),
                )),
                true,
            ),
            // vote account, success
            (vote_address, None, true),
            // incinerator, success
            (incinerator::id(), None, true),
            // non-rent-exempt system account with 1 lamport, success with relaxed checks
            (
                Pubkey::new_unique(),
                Some(AccountSharedData::new(
                    1,
                    0,
                    &solana_sdk_ids::system_program::id(),
                )),
                true,
            ),
            // invalid owner, no commission
            (
                Pubkey::new_unique(),
                Some(AccountSharedData::new(
                    LAMPORTS_PER_SOL,
                    0,
                    &Pubkey::new_unique(),
                )),
                false,
            ),
            // reserved account, no commission
            (solana_sdk_ids::native_loader::id(), None, false),
            // non-rent-exempt system account, no commission
            (Pubkey::new_unique(), None, false),
        ]
        .into_iter()
        .enumerate()
        {
            if let Some(account) = maybe_account {
                bank.store_account(&collector_address, &account);
            }
            bank = apply_epoch_operations(
                bank,
                bank_forks.as_ref(),
                EpochOperations {
                    epoch: epoch as u64 + 1,
                    vote_operations: vec![(
                        vote_address,
                        VoteOperations {
                            earned_credits: Some(1),
                            new_inflation_rewards_collector: Some(collector_address),
                            expect_reward,
                            ..VoteOperations::default()
                        },
                    )],
                },
            );
        }
    }

    #[test]
    fn test_inflation_rewards_collector_becomes_rent_exempt() {
        let GenesisConfigInfo {
            mut genesis_config, ..
        } = genesis_utils::create_genesis_config_with_leader(
            1_000_000 * LAMPORTS_PER_SOL,
            &Pubkey::new_unique(),
            42 * LAMPORTS_PER_SOL,
        );

        genesis_config.rent = Rent::default();
        genesis_config.epoch_schedule = EpochSchedule::new(SLOTS_PER_EPOCH);

        let (bank, bank_forks) =
            Bank::new_for_tests(&genesis_config).wrap_with_bank_forks_for_tests();
        let vote_address = Pubkey::new_unique();

        // Vote account just created
        let bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 0,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        create_with_balance: Some(LAMPORTS_PER_SOL),
                        new_commission: Some(100),
                        earned_credits: Some(1000),
                        delegate_stake_amount: Some(LAMPORTS_PER_SOL),
                        new_inflation_rewards_collector: Some(Pubkey::new_unique()),
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        // next epoch, get reward into new account
        let epoch = bank.epoch();
        apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        earned_credits: Some(1),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );
    }

    #[test]
    fn test_repeated_inflation_rewards_collector() {
        let GenesisConfigInfo {
            mut genesis_config, ..
        } = genesis_utils::create_genesis_config_with_leader(
            1_000_000 * LAMPORTS_PER_SOL,
            &Pubkey::new_unique(),
            42 * LAMPORTS_PER_SOL,
        );

        genesis_config.rent = Rent::default();
        genesis_config.epoch_schedule = EpochSchedule::new(SLOTS_PER_EPOCH);

        let (bank, bank_forks) =
            Bank::new_for_tests(&genesis_config).wrap_with_bank_forks_for_tests();

        let collector_address = Pubkey::new_unique();
        let vote1_address = Pubkey::new_unique();
        let vote2_address = Pubkey::new_unique();
        // Vote account just created
        let bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 0,
                vote_operations: vec![
                    (
                        vote1_address,
                        VoteOperations {
                            create_with_balance: Some(LAMPORTS_PER_SOL),
                            new_commission: Some(50),
                            earned_credits: Some(1000),
                            delegate_stake_amount: Some(LAMPORTS_PER_SOL),
                            new_inflation_rewards_collector: Some(collector_address),
                            ..VoteOperations::default()
                        },
                    ),
                    (
                        vote2_address,
                        VoteOperations {
                            create_with_balance: Some(LAMPORTS_PER_SOL),
                            new_commission: Some(100),
                            earned_credits: Some(1000),
                            delegate_stake_amount: Some(LAMPORTS_PER_SOL),
                            new_inflation_rewards_collector: Some(collector_address),
                            ..VoteOperations::default()
                        },
                    ),
                ],
            },
        );

        // next epoch, get double reward into collector
        let epoch = bank.epoch();
        apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch,
                vote_operations: vec![
                    (
                        vote1_address,
                        VoteOperations {
                            earned_credits: Some(1),
                            expect_reward: true,
                            ..VoteOperations::default()
                        },
                    ),
                    (
                        vote2_address,
                        VoteOperations {
                            earned_credits: Some(1),
                            expect_reward: true,
                            ..VoteOperations::default()
                        },
                    ),
                ],
            },
        );
    }

    #[test]
    fn test_invalid_inflation_rewards_collector_burns_sysvar_rewards() {
        let GenesisConfigInfo {
            mut genesis_config, ..
        } = genesis_utils::create_genesis_config_with_leader(
            1_000_000 * LAMPORTS_PER_SOL,
            &Pubkey::new_unique(),
            42 * LAMPORTS_PER_SOL,
        );

        genesis_config.rent = Rent::default();
        genesis_config.epoch_schedule = EpochSchedule::new(SLOTS_PER_EPOCH);

        let (bank, bank_forks) =
            Bank::new_for_tests(&genesis_config).wrap_with_bank_forks_for_tests();
        let vote_address = Pubkey::new_unique();

        // Create a vote account with delegated stake and 100% commission.
        // Using 100% commission makes the expected accounting simple: every lamport
        // of the epoch reward should go through the commission collector path.
        let bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 0,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        create_with_balance: Some(LAMPORTS_PER_SOL),
                        new_commission: Some(100),
                        earned_credits: Some(1000),
                        delegate_stake_amount: Some(LAMPORTS_PER_SOL),
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        // Simulate a collector account that is invalid at reward distribution time.
        // Started as system account but now it's owned by a random program
        let invalid_collector = Pubkey::new_unique();
        bank.store_account(
            &invalid_collector,
            &AccountSharedData::new(LAMPORTS_PER_SOL, 0, &Pubkey::new_unique()),
        );

        // Point the vote account at the invalid collector and advance to the reward
        // boundary. Account is not credited, so the commission lamports are burned.
        let bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 1,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        earned_credits: Some(1000),
                        new_inflation_rewards_collector: Some(invalid_collector),
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        let epoch_rewards = bank.get_epoch_rewards_sysvar();

        // The burned commission lamports must be reflected in the epoch rewards
        // sysvar. Since this test uses 100% commission, all calculated rewards
        // went through the invalid collector path.
        assert!(epoch_rewards.total_rewards > 0);
        assert_eq!(
            epoch_rewards.total_rewards,
            epoch_rewards.distributed_rewards
        );
    }

    #[test]
    fn test_incinerator_not_included_load_and_reward_commission_accounts() {
        let (genesis_config, _mint_keypair) = create_genesis_config(1_000 * LAMPORTS_PER_SOL);
        let bank = Bank::new_for_tests(&genesis_config);
        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();

        let pubkey = incinerator::id();
        let mut incinerator_account = AccountSharedData::default();
        incinerator_account.set_lamports(1);
        bank.store_account_and_update_capitalization(&pubkey, &incinerator_account);
        let mut reward_commissions = RewardCommissions::default();

        let commission_lamports = 100;
        reward_commissions.insert(
            pubkey,
            RewardCommission {
                commission_bps: None,
                commission_lamports,
                burned_lamports: 0,
                is_vote_account: false,
            },
        );
        let result = bank.load_and_reward_commission_accounts(&reward_commissions, &thread_pool);
        assert_eq!(
            result.amounts.distributed_to_incinerator_lamports,
            commission_lamports
        );
        assert_eq!(result.amounts.distributed_lamports, 0);
        assert_eq!(result.amounts.burned_lamports, 0);
    }

    #[test]
    fn test_inflation_collector_becomes_vote_account_burns_rewards() {
        let GenesisConfigInfo {
            mut genesis_config, ..
        } = genesis_utils::create_genesis_config_with_leader(
            1_000_000 * LAMPORTS_PER_SOL,
            &Pubkey::new_unique(),
            42 * LAMPORTS_PER_SOL,
        );

        genesis_config.rent = Rent::default();
        genesis_config.epoch_schedule = EpochSchedule::new(SLOTS_PER_EPOCH);

        let (bank, bank_forks) =
            Bank::new_for_tests(&genesis_config).wrap_with_bank_forks_for_tests();
        let vote_address = Pubkey::new_unique();
        let collector_into_vote_address = Pubkey::new_unique();

        // Create a normal vote account with a currently valid inflation collector
        let bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 0,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        create_with_balance: Some(LAMPORTS_PER_SOL),
                        new_commission: Some(100),
                        earned_credits: Some(1000),
                        delegate_stake_amount: Some(LAMPORTS_PER_SOL),
                        new_inflation_rewards_collector: Some(collector_into_vote_address),
                        ..VoteOperations::default()
                    },
                )],
            },
        );

        // New vote account gets nothing
        let rewards = bank.get_balance(&collector_into_vote_address);
        assert_eq!(rewards, 0);

        // Next epoch gets something
        let bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 1,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        earned_credits: Some(1000),
                        expect_reward: true,
                        ..VoteOperations::default()
                    },
                )],
            },
        );
        let pre_balance = bank.get_balance(&collector_into_vote_address);
        assert_ne!(pre_balance, 0);
        // Fund the converted vote account enough to pass VAT filtering.
        let pre_balance =
            pre_balance.max(bank.get_minimum_balance_for_rent_exemption(VoteStateV4::size_of()));

        // Transform the collector into a vote account, see that all rewards
        // are burned for this epoch
        let bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 2,
                vote_operations: vec![
                    (
                        vote_address,
                        VoteOperations {
                            earned_credits: Some(1000),
                            expect_reward: true,
                            ..VoteOperations::default()
                        },
                    ),
                    (
                        collector_into_vote_address,
                        VoteOperations {
                            create_with_balance: Some(pre_balance),
                            new_commission: Some(100),
                            earned_credits: Some(1000),
                            delegate_stake_amount: Some(LAMPORTS_PER_SOL),
                            ..VoteOperations::default()
                        },
                    ),
                ],
            },
        );

        let vote_reward = bank
            .rewards
            .read()
            .unwrap()
            .iter()
            .find(|(address, _reward)| *address == collector_into_vote_address)
            .map(|(_address, reward)| *reward)
            .unwrap();
        assert_eq!(vote_reward.lamports, 0);

        let unchanged_balance = bank.get_balance(&collector_into_vote_address);
        assert_eq!(unchanged_balance, pre_balance);

        // `collector_into_vote_address` receives its rewards, but `vote_address`
        // has its rewards burned
        let bank = apply_epoch_operations(
            bank,
            bank_forks.as_ref(),
            EpochOperations {
                epoch: 3,
                vote_operations: vec![
                    (
                        vote_address,
                        VoteOperations {
                            earned_credits: Some(1000),
                            expect_reward: true,
                            ..VoteOperations::default()
                        },
                    ),
                    (
                        collector_into_vote_address,
                        VoteOperations {
                            earned_credits: Some(1000),
                            expect_reward: true,
                            ..VoteOperations::default()
                        },
                    ),
                ],
            },
        );

        // Some rewards were distributed
        let post_balance = bank.get_balance(&collector_into_vote_address);
        assert!(post_balance > pre_balance);

        // They're reflected in the reported rewards
        let vote_reward = bank
            .rewards
            .read()
            .unwrap()
            .iter()
            .find(|(address, _reward)| *address == collector_into_vote_address)
            .map(|(_address, reward)| *reward)
            .unwrap();
        assert_eq!(vote_reward.lamports as u64, post_balance - pre_balance);

        // Some lamports were burned
        let reward_commissions = recalculate_reward_commissions_for_tests(&bank);
        let reward_commission = reward_commissions
            .get(&collector_into_vote_address)
            .unwrap();
        assert_ne!(reward_commission.burned_lamports, 0);

        // The burned lamports are included in the epoch rewards sysvar
        let epoch_rewards = bank.get_epoch_rewards_sysvar();
        assert_eq!(
            reward_commission.burned_lamports + reward_commission.commission_lamports,
            epoch_rewards.distributed_rewards
        );
    }
}