solana-runtime 4.0.0-beta.7

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
use {
    super::{
        Bank, CachedVoteAccounts, CalculateValidatorRewardsResult, EpochRewardCalculateParamInfo,
        FilteredStakeDelegations, PartitionedRewardsCalculation, PartitionedStakeReward,
        PartitionedStakeRewards, REWARD_CALCULATION_NUM_BLOCKS, RewardCommissionAccounts,
        RewardCommissionAccountsStorable, StakeRewardCalculation,
        epoch_rewards_hasher::hash_rewards_into_partitions,
    },
    crate::{
        bank::{
            EpochInflationRewards, RewardCalcTracer, RewardCalculationEvent, RewardCommission,
            RewardCommissions, RewardsMetrics, null_tracer,
        },
        inflation_rewards::{
            points::{DelegatedVoteState, PointValue, calculate_points},
            redeem_rewards,
        },
        stake_account::StakeAccount,
        stake_utils,
        stakes::Stakes,
    },
    agave_feature_set as feature_set,
    log::{debug, info},
    rayon::{
        ThreadPool,
        iter::{IndexedParallelIterator, ParallelIterator},
    },
    solana_clock::{Epoch, Slot},
    solana_measure::{measure::Measure, measure_us},
    solana_native_token::LAMPORTS_PER_SOL,
    solana_pubkey::Pubkey,
    solana_stake_interface::{stake_history::StakeHistory, state::Delegation},
    solana_sysvar::epoch_rewards::EpochRewards,
    std::sync::{Arc, atomic::Ordering::Relaxed},
};

#[derive(Debug)]
struct DelegationRewards {
    stake_reward: PartitionedStakeReward,
    commission_pubkey: Pubkey,
    reward_commission: RewardCommission,
}

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

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| {
                dst_reward_commission.commission_lamports = dst_reward_commission
                    .commission_lamports
                    .saturating_add(reward_commission.commission_lamports)
            })
            .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| {
                    dst_reward_commission.commission_lamports = dst_reward_commission
                        .commission_lamports
                        .saturating_add(reward_commission.commission_lamports)
                })
                .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.
    #[allow(clippy::too_many_arguments)]
    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: &RewardsMetrics,
    ) {
        self.distribute_reward_commissions(parent_epoch, rewards_calculation, rewards_metrics);

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

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

        let distributed_rewards = reward_commission_accounts.total_reward_commission_lamports;
        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_rewards,
            distribution_starting_block_height,
            num_partitions,
            point_value,
        );

        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),
        );
    }

    // 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<'_>,
        prev_epoch: Epoch,
        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(|| {
                let stake_delegations = self.filter_stake_delegations(stake_delegations);
                Arc::new(self.calculate_rewards_for_partitioning(
                    stake_history,
                    &stake_delegations,
                    cached_vote_accounts,
                    prev_epoch,
                    reward_calc_tracer,
                    thread_pool,
                    metrics,
                ))
            })
            .clone();
        drop(epoch_rewards_calculation_cache);

        rewards_calculation
    }

    pub(in crate::bank) fn distribute_reward_commissions(
        &mut self,
        prev_epoch: Epoch,
        rewards_calculation: &PartitionedRewardsCalculation,
        rewards_metrics: &RewardsMetrics,
    ) {
        let PartitionedRewardsCalculation {
            reward_commission_accounts,
            stake_rewards,
            validator_rate,
            foundation_rate,
            capitalization,
            point_value,
            ..
        } = rewards_calculation;

        let total_reward_commissions = reward_commission_accounts.total_reward_commission_lamports;
        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 >= total_reward_commissions + total_stake_rewards_lamports);
        info!(
            "distributed reward commissions: {} out of {}, remaining {}",
            total_reward_commissions, point_value.rewards, total_stake_rewards_lamports
        );

        let (num_stake_accounts, num_vote_accounts) = {
            let stakes = self.stakes_cache.stakes();
            let filtered_vote_accounts =
                self.maybe_filter_vote_accounts_for_vat(stakes.vote_accounts());
            (
                stakes.stake_delegations().len(),
                filtered_vote_accounts.len(),
            )
        };
        self.capitalization
            .fetch_add(total_reward_commissions, 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_rate", *validator_rate, f64),
            ("foundation_rate", *foundation_rate, f64),
            ("validator_rewards", total_reward_commissions, 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),
        );
    }

    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: &'a FilteredStakeDelegations<'a>,
        cached_vote_accounts: CachedVoteAccounts<'_>,
        rewarded_epoch: Epoch,
        reward_calc_tracer: Option<impl Fn(&RewardCalculationEvent) + Send + Sync>,
        thread_pool: &ThreadPool,
        metrics: &mut RewardsMetrics,
    ) -> PartitionedRewardsCalculation {
        let capitalization = self.capitalization();
        let EpochInflationRewards {
            validator_rewards_lamports,
            validator_rate,
            foundation_rate,
        } = self.calculate_epoch_inflation_rewards(capitalization, rewarded_epoch);

        let CalculateValidatorRewardsResult {
            reward_commission_accounts,
            stake_reward_calculation: stake_rewards,
            point_value,
        } = self
            .calculate_validator_rewards(
                stake_history,
                stake_delegations,
                cached_vote_accounts,
                rewarded_epoch,
                validator_rewards_lamports,
                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_commission_accounts,
            stake_rewards,
            validator_rate,
            foundation_rate,
            capitalization,
            point_value,
        }
    }

    /// Calculate epoch reward and return stake rewards and commissions.
    fn calculate_validator_rewards<'a>(
        &self,
        stake_history: &StakeHistory,
        stake_delegations: &'a FilteredStakeDelegations<'a>,
        cached_vote_accounts: CachedVoteAccounts<'_>,
        rewarded_epoch: Epoch,
        rewards: u64,
        reward_calc_tracer: Option<impl RewardCalcTracer>,
        thread_pool: &ThreadPool,
        metrics: &mut RewardsMetrics,
    ) -> Option<CalculateValidatorRewardsResult> {
        self.calculate_reward_points_partitioned(
            stake_history,
            stake_delegations,
            &cached_vote_accounts,
            rewards,
            thread_pool,
            metrics,
        )
        .map(|point_value| {
            let (reward_commission_accounts, stake_reward_calculation) = self
                .calculate_stake_rewards_and_commissions(
                    stake_history,
                    stake_delegations,
                    cached_vote_accounts,
                    rewarded_epoch,
                    point_value.clone(),
                    thread_pool,
                    reward_calc_tracer,
                    metrics,
                );
            CalculateValidatorRewardsResult {
                reward_commission_accounts,
                stake_reward_calculation,
                point_value,
            }
        })
    }

    pub(in crate::bank) fn filter_stake_delegations<'a>(
        &self,
        stake_delegations: Vec<(&'a Pubkey, &'a StakeAccount<Delegation>)>,
    ) -> FilteredStakeDelegations<'a> {
        let min_stake_delegation = if self
            .feature_set
            .is_active(&feature_set::stake_minimum_delegation_for_rewards::id())
        {
            let min_stake_delegation = stake_utils::get_minimum_delegation(
                self.feature_set
                    .is_active(&agave_feature_set::upgrade_bpf_stake_program_to_v5::id()),
            )
            .max(LAMPORTS_PER_SOL);
            Some(min_stake_delegation)
        } else {
            None
        };
        FilteredStakeDelegations {
            stake_delegations,
            min_stake_delegation,
        }
    }

    /// 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();
        let stake_delegations = self.filter_stake_delegations(stake_delegations);

        // 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,
        }
    }

    #[allow(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,
    ) -> Option<DelegationRewards> {
        // 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 stake_pubkey = *stake_pubkey;
        let vote_pubkey = stake_account.delegation().voter_pubkey;
        let Some(vote_account) = distribution_epoch_vote_accounts.get(&vote_pubkey) else {
            debug!("could not find vote account {vote_pubkey} in cache");
            return None;
        };
        let vote_state = vote_account.vote_state_view();
        let stake_state = stake_account.stake_state();

        // 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(
            rewarded_epoch,
            stake_state,
            commission_bps,
            DelegatedVoteState::from(vote_state),
            point_value,
            stake_history,
            reward_calc_tracer,
            new_rate_activation_epoch,
            commission_rate_in_basis_points,
        ) {
            Ok((stake_reward, commission_lamports, stake)) => {
                let stake_reward = PartitionedStakeReward {
                    stake_pubkey,
                    stake,
                    stake_reward,
                    commission_bps,
                };
                let vote_account = vote_account.into();
                let reward_commission = RewardCommission {
                    commission_bps,
                    commission_account: vote_account,
                    commission_lamports,
                };
                Some(DelegationRewards {
                    stake_reward,
                    commission_pubkey: vote_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
    fn calculate_stake_rewards_and_commissions<'a>(
        &self,
        stake_history: &StakeHistory,
        stake_delegations: &'a FilteredStakeDelegations<'a>,
        cached_vote_accounts: CachedVoteAccounts<'_>,
        rewarded_epoch: Epoch,
        point_value: PointValue,
        thread_pool: &ThreadPool,
        reward_calc_tracer: Option<impl RewardCalcTracer>,
        metrics: &mut RewardsMetrics,
    ) -> (RewardCommissionAccounts, StakeRewardCalculation) {
        let new_warmup_cooldown_rate_epoch = self.new_warmup_cooldown_rate_epoch();
        let delay_commission_updates = self
            .feature_set
            .is_active(&agave_feature_set::delay_commission_updates::id());
        let commission_rate_in_basis_points = self
            .feature_set
            .is_active(&feature_set::commission_rate_in_basis_points::id());

        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(|(maybe_stake_delegation, stake_reward_ref)| {
                    let maybe_reward_record =
                        maybe_stake_delegation.and_then(|(stake_pubkey, stake_account)| {
                            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,
                            )
                        });
                    let (stake_reward, maybe_reward_record) = match maybe_reward_record {
                        Some(res) => {
                            let DelegationRewards {
                                stake_reward,
                                commission_pubkey,
                                reward_commission,
                            } = res;
                            let stakers_reward = stake_reward.stake_reward;
                            (
                                Some(stake_reward),
                                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);
        }
        let reward_commission_accounts = Self::calculate_commission_accounts(reward_commissions);
        measure_redeem_rewards.stop();
        metrics.redeem_rewards_us = measure_redeem_rewards.as_us();

        (
            reward_commission_accounts,
            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: &'a FilteredStakeDelegations<'a>,
        cached_vote_accounts: &CachedVoteAccounts<'_>,
        rewards: u64,
        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();
        let (points, measure_us) = measure_us!(thread_pool.install(|| {
            stake_delegations
                .par_iter()
                .filter_map(|stake_delegation| stake_delegation)
                .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(
                        stake_account.stake_state(),
                        DelegatedVoteState::from(vote_account.vote_state_view()),
                        stake_history,
                        new_warmup_cooldown_rate_epoch,
                    )
                    .unwrap_or(0)
                })
                .sum::<u128>()
        }));
        metrics.calculate_points_us.fetch_add(measure_us, Relaxed);

        (points > 0).then_some(PointValue { 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,
    ) -> (
        RewardCommissionAccounts,
        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);

        // 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.
        let (reward_commission_accounts, StakeRewardCalculation { stake_rewards, .. }) = self
            .calculate_stake_rewards_and_commissions(
                &stake_history,
                &stake_delegations,
                cached_vote_accounts,
                rewarded_epoch,
                point_value,
                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,
        );
        (reward_commission_accounts, stake_rewards, partition_indices)
    }
}

#[cfg(test)]
mod tests {
    use {
        super::*,
        crate::{
            bank::{
                RewardCommission, RewardInfo, 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,
            },
            genesis_utils::{self, GenesisConfigInfo, deactivate_features},
            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,
        rayon::ThreadPoolBuilder,
        solana_account::{
            AccountSharedData, ReadableAccount, accounts_equal, state_traits::StateMut,
        },
        solana_accounts_db::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_reward_info::RewardType,
        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::HashSet,
            sync::{Arc, RwLockReadGuard},
        },
        test_case::test_case,
    };

    #[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 reward_commissions = (0..num_reward_commissions)
            .map(|_| (Pubkey::new_unique(), RewardCommission::new_random()))
            .collect::<Vec<_>>();

        let mut reward_commission_accounts = RewardCommissionAccounts::default();
        reward_commissions
            .iter()
            .for_each(|(commission_pubkey, reward_commission)| {
                let info = RewardInfo {
                    reward_type: RewardType::Voting,
                    lamports: reward_commission.commission_lamports as i64,
                    post_balance: reward_commission.commission_lamports,
                    commission_bps: Some(reward_commission.commission_bps),
                };
                reward_commission_accounts.accounts_with_rewards.push((
                    *commission_pubkey,
                    info,
                    reward_commission.commission_account.clone(),
                ));
                reward_commission_accounts.total_reward_commission_lamports +=
                    reward_commission.commission_lamports;
            });

        let metrics = RewardsMetrics::default();

        let total_reward_commissions = reward_commission_accounts.total_reward_commission_lamports;
        bank.store_commission_accounts_partitioned(&reward_commission_accounts, &metrics);
        assert_eq!(
            num_reward_commissions,
            reward_commission_accounts.accounts_with_rewards.len()
        );
        assert_eq!(
            reward_commissions
                .iter()
                .map(|(_, reward_commission)| reward_commission.commission_lamports)
                .sum::<u64>(),
            total_reward_commissions
        );

        // load accounts to make sure they were stored correctly
        reward_commissions
            .iter()
            .for_each(|(commission_pubkey, reward_commission)| {
                let loaded_account = bank
                    .load_slow_with_fixed_root(&bank.ancestors, commission_pubkey)
                    .unwrap();
                assert!(accounts_equal(
                    &loaded_account.0,
                    &reward_commission.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.total_reward_commission_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 with sufficient stake to get rewards (2 SOL).
        let delegations_with_rewards = 100;
        // Delegations with insufficient stake (0.5 SOL).
        let delegations_without_rewards = 10;
        let stakes = (0..delegations_with_rewards)
            .map(|_| 2_000_000_000)
            .chain((0..delegations_without_rewards).map(|_| 500_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 = 1;
        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,
            null_tracer(),
            &thread_pool,
            &mut rewards_metrics,
        );

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

        let total_reward_commissions: u64 = reward_commission_accounts
            .accounts_with_rewards
            .iter()
            .map(|(_, reward_info, _)| reward_info.lamports)
            .sum::<i64>() as u64;

        // 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_with_rewards
        );
    }

    #[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,
            &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,
            &thread_pool,
            &rewards_metrics,
        );

        assert!(point_value.is_none());
    }

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

    #[derive(Default)]
    struct VoteOperations {
        expected_reward_commission: Option<u8>,
        // ops to perform before epoch ends
        create_with_balance: Option<u64>,
        delegate_stake_amount: Option<u64>,
        new_commission: Option<u8>,
        earned_credits: Option<u64>,
    }

    fn recalculate_reward_commission_for_tests(
        bank: &Bank,
        commission_pubkey: &Pubkey,
    ) -> Option<RewardInfo> {
        let epoch_rewards_sysvar = bank.get_epoch_rewards_sysvar();
        let thread_pool = ThreadPoolBuilder::new().num_threads(1).build().unwrap();
        let (reward_commissions, ..) =
            bank.recalculate_stake_rewards(&epoch_rewards_sysvar, &thread_pool);
        reward_commissions
            .accounts_with_rewards
            .iter()
            .find(|(reward_address, ..)| reward_address == commission_pubkey)
            .map(|(_, reward, _)| *reward)
    }

    fn apply_epoch_operations(mut bank: Bank, op: EpochOperations) -> 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, &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 mut stake_account =
                    AccountSharedData::new(lamports, size, &solana_sdk_ids::stake::id());

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

                let stake = Stake {
                    delegation: Delegation::new(vote_address, *stake_amount, bank.epoch()),
                    credits_observed: 0,
                };

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

                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(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 = Arc::new(bank);
        bank = Bank::new_from_parent(prev_bank.clone(), &Pubkey::new_unique(), slot);

        for (vote_address, vote_op) in &op.vote_operations {
            let expected_commission = vote_op.expected_reward_commission;
            let recalculated_vote_reward =
                recalculate_reward_commission_for_tests(&bank, vote_address);
            let vote_reward = bank
                .rewards
                .read()
                .unwrap()
                .iter()
                .find(|(address, _reward)| address == vote_address)
                .map(|(_address, reward)| *reward);

            let prev_vote_balance = prev_bank
                .get_account(vote_address)
                .unwrap_or_default()
                .lamports();
            let vote_balance = bank.get_balance(vote_address);

            if let Some(expected_commission) = &expected_commission {
                let reward_lamports = vote_balance - prev_vote_balance;
                let expected_vote_reward = RewardInfo {
                    reward_type: RewardType::Voting,
                    lamports: reward_lamports as i64,
                    post_balance: vote_balance,
                    commission_bps: Some(*expected_commission as u16 * 100),
                };

                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 mut bank = Bank::new_for_tests(&genesis_config);
        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
        bank = apply_epoch_operations(
            bank,
            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 = {
            let expected_commission = if delay_commission_updates { 1 } else { 2 };
            apply_epoch_operations(
                bank,
                EpochOperations {
                    epoch: 1,
                    vote_operations: vec![(
                        vote_address,
                        VoteOperations {
                            new_commission: Some(2),
                            earned_credits: Some(1000),
                            expected_reward_commission: Some(expected_commission),
                            ..VoteOperations::default()
                        },
                    )],
                },
            )
        };

        let expected_commission = if delay_commission_updates { 1 } else { 3 };
        apply_epoch_operations(
            bank,
            EpochOperations {
                epoch: 2,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        new_commission: Some(3),
                        earned_credits: Some(1000),
                        expected_reward_commission: Some(expected_commission),
                        ..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 mut bank = Bank::new_for_tests(&genesis_config);
        assert!(bank.feature_set.is_active(&delay_commission_updates::id()));

        let vote_address = Pubkey::new_unique();
        bank = apply_epoch_operations(
            bank,
            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,
            EpochOperations {
                epoch: 1,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        create_with_balance: Some(LAMPORTS_PER_SOL),
                        new_commission: Some(1),
                        earned_credits: Some(1000),
                        expected_reward_commission: Some(1),
                        ..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,
            EpochOperations {
                epoch: 2,
                vote_operations: vec![(
                    vote_address,
                    VoteOperations {
                        new_commission: Some(2),
                        earned_credits: Some(1000),
                        expected_reward_commission: Some(1),
                        ..VoteOperations::default()
                    },
                )],
            },
        );

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

    #[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 mut bank = Bank::new_for_tests(&genesis_config);
        assert!(bank.feature_set.is_active(&delay_commission_updates::id()));

        let genesis_vote_address = voting_keypair.pubkey();

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

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

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

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

        apply_epoch_operations(
            bank,
            EpochOperations {
                epoch: 4,
                vote_operations: vec![(
                    genesis_vote_address,
                    VoteOperations {
                        earned_credits: Some(1000),
                        expected_reward_commission: Some(2),
                        ..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,
                &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.accounts_with_rewards.len(), 1);
        let (vote_pubkey_from_result, rewards, account) =
            &vote_rewards_accounts.accounts_with_rewards[0];
        let vote_rewards = 0;
        let commission_bps = vote_state.inflation_rewards_commission_bps;
        assert_eq!(account.lamports(), vote_account.lamports());
        assert!(accounts_equal(account, &vote_account));
        assert_eq!(
            *rewards,
            RewardInfo {
                reward_type: RewardType::Voting,
                lamports: vote_rewards as i64,
                post_balance: vote_account.lamports(),
                commission_bps: Some(commission_bps),
            }
        );
        assert_eq!(vote_pubkey_from_result, vote_pubkey);

        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,
                stake_pubkey,
                stake_reward,
                commission_bps,
            }
        };
        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, .. }, _) = create_reward_bank(
            expected_num_delegations,
            num_rewards_per_block,
            SLOTS_PER_EPOCH,
        );
        let rewarded_epoch = bank.epoch();

        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,
            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 = Arc::new(Bank::new_from_parent(bank, &Pubkey::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 to last distribution slot
        let new_slot = bank.slot() + 1;
        let bank = Arc::new(Bank::new_from_parent(bank, &Pubkey::default(), new_slot));

        let epoch_rewards_sysvar = bank.get_epoch_rewards_sysvar();
        assert!(!epoch_rewards_sysvar.active);
        // Recalculation would panic, tested separately
    }

    #[test]
    #[should_panic]
    fn test_recalculate_stake_rewards_distribution_complete() {
        let expected_num_delegations = 2;
        let num_rewards_per_block = 2;
        // Distribute 2 rewards over 1 block
        let (RewardBank { bank, .. }, _) = create_reward_bank(
            expected_num_delegations,
            num_rewards_per_block,
            SLOTS_PER_EPOCH,
        );
        let rewarded_epoch = bank.epoch();

        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,
            null_tracer(),
            &thread_pool,
            &mut rewards_metrics,
        );
        drop(stakes);

        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);

        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);

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

        // Advance to first distribution slot
        let new_slot = bank.slot() + 1;
        let bank = Arc::new(Bank::new_from_parent(bank, &Pubkey::default(), new_slot));

        let epoch_rewards_sysvar = bank.get_epoch_rewards_sysvar();
        assert!(!epoch_rewards_sysvar.active);
        // Should panic
        let _recalculated_rewards =
            bank.recalculate_stake_rewards(&epoch_rewards_sysvar, &thread_pool);
    }

    #[test]
    fn test_recalculate_partitioned_rewards() {
        let expected_num_delegations = 3;
        let num_rewards_per_block = 2;
        // Distribute 4 rewards over 2 blocks
        let mut stakes = vec![2_000_000_000; expected_num_delegations];
        // Add stake large enough to be affected by total-rewards discrepancy
        stakes.push(40_000_000_000);
        let (RewardBank { bank, .. }, _) = 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, &Pubkey::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,
            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
        let mut bank =
            Bank::new_from_parent(Arc::new(bank), &Pubkey::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 to last distribution slot
        let mut bank =
            Bank::new_from_parent(Arc::new(bank), &Pubkey::default(), SLOTS_PER_EPOCH + 2);
        bank.recalculate_partitioned_rewards_if_active(|| &thread_pool);
        assert_eq!(bank.epoch_reward_status, EpochRewardStatus::Inactive);
    }

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

        // Advance to next epoch boundary
        let new_slot = bank.slot() + 1;
        let mut bank = Bank::new_from_parent(bank, &Pubkey::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
        );
    }

    #[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, &Pubkey::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_account_a = AccountSharedData::default();

        let commission_pubkey_b = Pubkey::new_unique();
        let commission_account_b = AccountSharedData::default();

        let commission_pubkey_c = Pubkey::new_unique();
        let commission_account_c = AccountSharedData::default();

        accumulator1.add_reward(
            commission_pubkey_a,
            RewardCommission {
                commission_account: commission_account_a.clone(),
                commission_bps: 1_000,
                commission_lamports: 50,
            },
            50,
        );
        accumulator1.add_reward(
            commission_pubkey_b,
            RewardCommission {
                commission_account: commission_account_b.clone(),
                commission_bps: 1_000,
                commission_lamports: 50,
            },
            50,
        );
        accumulator2.add_reward(
            commission_pubkey_b,
            RewardCommission {
                commission_account: commission_account_b,
                commission_bps: 1_000,
                commission_lamports: 30,
            },
            30,
        );
        accumulator2.add_reward(
            commission_pubkey_c,
            RewardCommission {
                commission_account: commission_account_c,
                commission_bps: 1_000,
                commission_lamports: 50,
            },
            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, 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, 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, 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, 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, 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, 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, 1_000);
        assert_eq!(reward_commission_c.commission_lamports, 50);
    }

    #[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 = Arc::new(Bank::new_for_tests(&genesis_config));
        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(Arc::clone(&bank), &Pubkey::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"
            );
        }

        let bank_fork2 = Bank::new_from_parent(bank, &Pubkey::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.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 RewardCommissionAccounts {
            accounts_with_rewards,
            total_reward_commission_lamports,
            ..
        } = &partitioned.reward_commission_accounts;
        let StakeRewardCalculation {
            stake_rewards,
            total_stake_rewards_lamports,
            ..
        } = &partitioned.stake_rewards;
        let point_value = &partitioned.point_value;
        let voters: HashSet<_> = accounts_with_rewards
            .iter()
            .map(|(pubkey, _reward, _acc)| *pubkey)
            .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);
        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),
            &Pubkey::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),
            &Pubkey::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
        );
    }
}