LCOV - code coverage report
Current view: top level - flamenco/rewards - fd_rewards.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 0 674 0.0 %
Date: 2025-01-08 12:08:44 Functions: 0 30 0.0 %

          Line data    Source code
       1             : #include "fd_rewards.h"
       2             : #include <math.h>
       3             : 
       4             : #include "../runtime/fd_executor_err.h"
       5             : #include "../runtime/fd_system_ids.h"
       6             : #include "../runtime/context/fd_exec_epoch_ctx.h"
       7             : #include "../runtime/context/fd_exec_slot_ctx.h"
       8             : #include "../../ballet/siphash13/fd_siphash13.h"
       9             : #include "../runtime/program/fd_program_util.h"
      10             : 
      11             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/sdk/program/src/native_token.rs#L6 */
      12           0 : #define LAMPORTS_PER_SOL   ( 1000000000UL )
      13             : 
      14             : /* Number of blocks for reward calculation and storing vote accounts.
      15             :    Distributing rewards to stake accounts begins AFTER this many blocks.
      16             : 
      17             :    https://github.com/anza-xyz/agave/blob/9a7bf72940f4b3cd7fc94f54e005868ce707d53d/runtime/src/bank/partitioned_epoch_rewards/mod.rs#L27 */
      18           0 : #define REWARD_CALCULATION_NUM_BLOCKS ( 1UL )
      19             : 
      20             : /* stake accounts to store in one block during partitioned reward interval. Target to store 64 rewards per entry/tick in a block. A block has a minimum of 64 entries/tick. This gives 4096 total rewards to store in one block. */
      21           0 : #define STAKE_ACCOUNT_STORES_PER_BLOCK          ( 4096UL )
      22             : 
      23             : /* https://github.com/anza-xyz/agave/blob/2316fea4c0852e59c071f72d72db020017ffd7d0/runtime/src/bank/partitioned_epoch_rewards/mod.rs#L219 */
      24           0 : #define MAX_FACTOR_OF_REWARD_BLOCKS_IN_EPOCH    ( 10UL )
      25             : 
      26             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/sdk/src/inflation.rs#L85 */
      27             : static double
      28           0 : total( fd_inflation_t const * inflation, double year ) {
      29           0 :     if ( FD_UNLIKELY( year == 0.0 ) ) {
      30           0 :         FD_LOG_ERR(( "inflation year 0" ));
      31           0 :     }
      32           0 :     double tapered = inflation->initial * pow((1.0 - inflation->taper), year);
      33           0 :     return (tapered > inflation->terminal) ? tapered : inflation->terminal;
      34           0 : }
      35             : 
      36             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/sdk/src/inflation.rs#L102 */
      37             : static double
      38           0 : foundation( fd_inflation_t const * inflation, double year ) {
      39           0 :     return (year < inflation->foundation_term) ? inflation->foundation * total(inflation, year) : 0.0;
      40           0 : }
      41             : 
      42             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/sdk/src/inflation.rs#L97 */
      43             : static double
      44           0 : validator( fd_inflation_t const * inflation, double year) {
      45             :     /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/sdk/src/inflation.rs#L96-L99 */
      46           0 :     FD_LOG_DEBUG(("Validator Rate: %.16f %.16f %.16f %.16f %.16f", year, total( inflation, year ), foundation( inflation, year ), inflation->taper, inflation->initial));
      47           0 :     return total( inflation, year ) - foundation( inflation, year );
      48           0 : }
      49             : 
      50             : /* Calculates the starting slot for inflation from the activation slot. The activation slot is the earliest
      51             :     activation slot of the following features:
      52             :     - devnet_and_testnet
      53             :     - full_inflation_enable, if full_inflation_vote has been activated
      54             : 
      55             :     https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank.rs#L2095 */
      56             : static FD_FN_CONST ulong
      57           0 : get_inflation_start_slot( fd_exec_slot_ctx_t * slot_ctx ) {
      58           0 :     ulong devnet_and_testnet = FD_FEATURE_ACTIVE(slot_ctx, devnet_and_testnet) ? slot_ctx->epoch_ctx->features.devnet_and_testnet : ULONG_MAX;
      59             : 
      60           0 :     ulong enable = ULONG_MAX;
      61           0 :     if ( FD_FEATURE_ACTIVE( slot_ctx, full_inflation_vote ) && FD_FEATURE_ACTIVE(slot_ctx, full_inflation_enable ) ) {
      62           0 :         enable = slot_ctx->epoch_ctx->features.full_inflation_enable;
      63           0 :     }
      64             : 
      65           0 :     ulong min_slot = fd_ulong_min( enable, devnet_and_testnet );
      66           0 :     if ( min_slot == ULONG_MAX ) {
      67           0 :         if ( FD_FEATURE_ACTIVE( slot_ctx, pico_inflation ) ) {
      68           0 :             min_slot = slot_ctx->epoch_ctx->features.pico_inflation;
      69           0 :         } else {
      70           0 :             min_slot = 0;
      71           0 :         }
      72           0 :     }
      73           0 :     return min_slot;
      74           0 : }
      75             : 
      76             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank.rs#L2110 */
      77             : static ulong
      78             : get_inflation_num_slots( fd_exec_slot_ctx_t * slot_ctx,
      79             :                          fd_epoch_schedule_t const * epoch_schedule,
      80           0 :                          ulong slot ) {
      81           0 :     ulong inflation_activation_slot = get_inflation_start_slot( slot_ctx );
      82           0 :     ulong inflation_start_slot = fd_epoch_slot0(
      83           0 :         epoch_schedule,
      84           0 :         fd_ulong_sat_sub(
      85           0 :             fd_slot_to_epoch( epoch_schedule, inflation_activation_slot, NULL ),
      86           0 :             1 )
      87           0 :         );
      88             : 
      89           0 :     ulong epoch = fd_slot_to_epoch(epoch_schedule, slot, NULL);
      90             : 
      91           0 :     return fd_epoch_slot0(epoch_schedule, epoch) - inflation_start_slot;
      92           0 : }
      93             : 
      94             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank.rs#L2121 */
      95             : static double
      96           0 : slot_in_year_for_inflation( fd_exec_slot_ctx_t * slot_ctx ) {
      97           0 :     fd_epoch_bank_t const * epoch_bank = fd_exec_epoch_ctx_epoch_bank( slot_ctx->epoch_ctx );
      98           0 :     ulong num_slots = get_inflation_num_slots( slot_ctx, &epoch_bank->epoch_schedule, slot_ctx->slot_bank.slot );
      99           0 :     return (double)num_slots / (double)epoch_bank->slots_per_year;
     100           0 : }
     101             : 
     102             : /* For a given stake and vote_state, calculate how many points were earned (credits * stake) and new value
     103             :    for credits_observed were the points paid
     104             : 
     105             :     https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/points.rs#L109 */
     106             : static void
     107             : calculate_stake_points_and_credits(
     108             :   fd_stake_history_t const *     stake_history,
     109             :   fd_stake_t *                   stake,
     110             :   fd_vote_state_versioned_t *    vote_state_versioned,
     111             :   ulong *                        new_rate_activation_epoch,
     112             :   fd_calculated_stake_points_t * result
     113           0 : ) {
     114             : 
     115           0 :     ulong credits_in_stake = stake->credits_observed;
     116             : 
     117           0 :     fd_vote_epoch_credits_t * epoch_credits;
     118           0 :     switch (vote_state_versioned->discriminant) {
     119           0 :         case fd_vote_state_versioned_enum_current:
     120           0 :             epoch_credits = vote_state_versioned->inner.current.epoch_credits;
     121           0 :             break;
     122           0 :         case fd_vote_state_versioned_enum_v0_23_5:
     123           0 :             epoch_credits = vote_state_versioned->inner.v0_23_5.epoch_credits;
     124           0 :             break;
     125           0 :         case fd_vote_state_versioned_enum_v1_14_11:
     126           0 :             epoch_credits = vote_state_versioned->inner.v1_14_11.epoch_credits;
     127           0 :             break;
     128           0 :         default:
     129           0 :             FD_LOG_ERR(( "invalid vote account, should never happen" ));
     130           0 :     }
     131           0 :     ulong credits_in_vote = 0UL;
     132           0 :     if ( FD_LIKELY( !deq_fd_vote_epoch_credits_t_empty( epoch_credits ) ) ) {
     133           0 :         credits_in_vote = deq_fd_vote_epoch_credits_t_peek_tail_const( epoch_credits )->credits;
     134           0 :     }
     135             : 
     136             :     /* If the Vote account has less credits observed than the Stake account,
     137             :        something is wrong and we need to force an update.
     138             : 
     139             :        https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/points.rs#L142 */
     140           0 :     if ( FD_UNLIKELY( credits_in_vote < credits_in_stake ) ) {
     141           0 :         result->points = 0;
     142           0 :         result->new_credits_observed = credits_in_vote;
     143           0 :         result->force_credits_update_with_skipped_reward = 1;
     144           0 :         return;
     145           0 :     }
     146             : 
     147             :     /* If the Vote account has the same amount of credits observed as the Stake account,
     148             :        then the Vote account hasn't earnt any credits and so there is nothing to update.
     149             : 
     150             :        https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/points.rs#L148 */
     151           0 :     if ( FD_UNLIKELY( credits_in_vote == credits_in_stake ) ) {
     152           0 :         result->points = 0;
     153           0 :         result->new_credits_observed = credits_in_vote;
     154           0 :         result->force_credits_update_with_skipped_reward = 0;
     155           0 :         return;
     156           0 :     }
     157             : 
     158             :     /* Calculate the points for each epoch credit */
     159           0 :     uint128 points = 0;
     160           0 :     ulong new_credits_observed = credits_in_stake;
     161           0 :     for ( deq_fd_vote_epoch_credits_t_iter_t iter = deq_fd_vote_epoch_credits_t_iter_init( epoch_credits );
     162           0 :           !deq_fd_vote_epoch_credits_t_iter_done( epoch_credits, iter );
     163           0 :           iter = deq_fd_vote_epoch_credits_t_iter_next( epoch_credits, iter ) ) {
     164             : 
     165           0 :         fd_vote_epoch_credits_t * ele = deq_fd_vote_epoch_credits_t_iter_ele( epoch_credits, iter );
     166           0 :         ulong final_epoch_credits = ele->credits;
     167           0 :         ulong initial_epoch_credits = ele->prev_credits;
     168           0 :         uint128 earned_credits = 0;
     169           0 :         if ( FD_LIKELY( credits_in_stake < initial_epoch_credits ) ) {
     170           0 :             earned_credits = (uint128)(final_epoch_credits - initial_epoch_credits);
     171           0 :         } else if ( FD_UNLIKELY( credits_in_stake < final_epoch_credits ) ) {
     172           0 :             earned_credits = (uint128)(final_epoch_credits - new_credits_observed);
     173           0 :         }
     174             : 
     175           0 :         new_credits_observed = fd_ulong_max( new_credits_observed, final_epoch_credits );
     176             : 
     177           0 :         ulong stake_amount = fd_stake_activating_and_deactivating( &stake->delegation, ele->epoch, stake_history, new_rate_activation_epoch ).effective;
     178             : 
     179           0 :         points += (uint128)stake_amount * earned_credits;
     180           0 :     }
     181             : 
     182           0 :     result->points = points;
     183           0 :     result->new_credits_observed = new_credits_observed;
     184           0 :     result->force_credits_update_with_skipped_reward = 0;
     185           0 : }
     186             : 
     187             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/rewards.rs#L127 */
     188             : static int
     189             : calculate_stake_rewards(
     190             :   fd_stake_history_t const *      stake_history,
     191             :   fd_stake_state_v2_t *           stake_state,
     192             :   fd_vote_state_versioned_t *     vote_state_versioned,
     193             :   ulong                           rewarded_epoch,
     194             :   fd_point_value_t *              point_value,
     195             :   ulong *                         new_rate_activation_epoch,
     196             :   fd_calculated_stake_rewards_t * result
     197           0 : ) {
     198           0 :     fd_calculated_stake_points_t stake_points_result = {0};
     199           0 :     calculate_stake_points_and_credits( stake_history, &stake_state->inner.stake.stake, vote_state_versioned, new_rate_activation_epoch, &stake_points_result);
     200             : 
     201             :     // Drive credits_observed forward unconditionally when rewards are disabled
     202             :     // or when this is the stake's activation epoch
     203           0 :     if ( ( point_value->rewards == 0 ) ||
     204           0 :          ( stake_state->inner.stake.stake.delegation.activation_epoch == rewarded_epoch ) ) {
     205           0 :         stake_points_result.force_credits_update_with_skipped_reward |= 1;
     206           0 :     }
     207             : 
     208           0 :     if (stake_points_result.force_credits_update_with_skipped_reward) {
     209           0 :         result->staker_rewards = 0;
     210           0 :         result->voter_rewards = 0;
     211           0 :         result->new_credits_observed = stake_points_result.new_credits_observed;
     212           0 :         return 0;
     213           0 :     }
     214           0 :     if ( stake_points_result.points == 0 || point_value->points == 0 ) {
     215           0 :         return 1;
     216           0 :     }
     217             : 
     218             :     /* FIXME: need to error out if the conversion from uint128 to u64 fails, also use 128 checked mul and div */
     219           0 :     ulong rewards = (ulong)(stake_points_result.points * (uint128)(point_value->rewards) / (uint128) point_value->points);
     220           0 :     if (rewards == 0) {
     221           0 :         return 1;
     222           0 :     }
     223             : 
     224           0 :     fd_commission_split_t split_result;
     225           0 :     fd_vote_commission_split( vote_state_versioned, rewards, &split_result );
     226           0 :     if (split_result.is_split && (split_result.voter_portion == 0 || split_result.staker_portion == 0)) {
     227           0 :         return 1;
     228           0 :     }
     229             : 
     230           0 :     result->staker_rewards = split_result.staker_portion;
     231           0 :     result->voter_rewards = split_result.voter_portion;
     232           0 :     result->new_credits_observed = stake_points_result.new_credits_observed;
     233           0 :     return 0;
     234           0 : }
     235             : 
     236             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/rewards.rs#L33 */
     237             : static int
     238             : redeem_rewards( fd_stake_history_t const *      stake_history,
     239             :                 fd_stake_state_v2_t *           stake_state,
     240             :                 fd_vote_state_versioned_t *     vote_state_versioned,
     241             :                 ulong                           rewarded_epoch,
     242             :                 fd_point_value_t *              point_value,
     243             :                 ulong *                         new_rate_activation_epoch,
     244           0 :                 fd_calculated_stake_rewards_t * calculated_stake_rewards) {
     245             : 
     246           0 :     int rc = calculate_stake_rewards( stake_history, stake_state, vote_state_versioned, rewarded_epoch, point_value, new_rate_activation_epoch, calculated_stake_rewards );
     247           0 :     if ( FD_UNLIKELY( rc != 0 ) ) {
     248           0 :         return rc;
     249           0 :     }
     250             : 
     251           0 :     return FD_EXECUTOR_INSTR_SUCCESS;
     252           0 : }
     253             : 
     254             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/points.rs#L70 */
     255             : static int
     256             : calculate_points(
     257             :     fd_stake_t                * stake,
     258             :     fd_vote_state_versioned_t * vote_state_versioned,
     259             :     fd_stake_history_t const  * stake_history,
     260             :     ulong *                     new_rate_activation_epoch,
     261             :     uint128 *                   result
     262           0 : ) {
     263           0 :     fd_calculated_stake_points_t stake_point_result;
     264           0 :     calculate_stake_points_and_credits( stake_history, stake, vote_state_versioned, new_rate_activation_epoch, &stake_point_result );
     265           0 :     *result = stake_point_result.points;
     266             : 
     267           0 :     return FD_EXECUTOR_INSTR_SUCCESS;
     268           0 : }
     269             : 
     270             : /* Returns the length of the given epoch in slots
     271             : 
     272             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/sdk/program/src/epoch_schedule.rs#L103 */
     273             : static ulong
     274             : get_slots_in_epoch(
     275             :     ulong epoch,
     276             :     fd_epoch_bank_t const * epoch_bank
     277           0 : ) {
     278           0 :     return (epoch < epoch_bank->epoch_schedule.first_normal_epoch) ?
     279           0 :         1UL << fd_ulong_sat_add(epoch, FD_EPOCH_LEN_MIN_TRAILING_ZERO) :
     280           0 :         epoch_bank->epoch_schedule.slots_per_epoch;
     281           0 : }
     282             : 
     283             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank.rs#L2082 */
     284             : static double
     285             : epoch_duration_in_years(
     286             :     fd_epoch_bank_t const * epoch_bank,
     287             :     ulong prev_epoch
     288           0 : ) {
     289           0 :     ulong slots_in_epoch = get_slots_in_epoch( prev_epoch, epoch_bank );
     290           0 :     return (double)slots_in_epoch / (double) epoch_bank->slots_per_year;
     291           0 : }
     292             : 
     293             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank.rs#L2128 */
     294             : static void
     295             : calculate_previous_epoch_inflation_rewards(
     296             :     fd_exec_slot_ctx_t * slot_ctx,
     297             :     ulong prev_epoch_capitalization,
     298             :     ulong prev_epoch,
     299             :     fd_prev_epoch_inflation_rewards_t * rewards
     300           0 : ) {
     301           0 :     double slot_in_year = slot_in_year_for_inflation( slot_ctx );
     302             : 
     303           0 :     fd_epoch_bank_t const * epoch_bank = fd_exec_epoch_ctx_epoch_bank( slot_ctx->epoch_ctx );
     304           0 :     rewards->validator_rate = validator( &epoch_bank->inflation, slot_in_year );
     305           0 :     rewards->foundation_rate = foundation( &epoch_bank->inflation, slot_in_year );
     306           0 :     rewards->prev_epoch_duration_in_years = epoch_duration_in_years(epoch_bank, prev_epoch);
     307           0 :     rewards->validator_rewards = (ulong)(rewards->validator_rate * (double)prev_epoch_capitalization * rewards->prev_epoch_duration_in_years);
     308           0 :     FD_LOG_DEBUG(("Rewards %lu, Rate %.16f, Duration %.18f Capitalization %lu Slot in year %.16f", rewards->validator_rewards, rewards->validator_rate, rewards->prev_epoch_duration_in_years, prev_epoch_capitalization, slot_in_year));
     309           0 : }
     310             : 
     311             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/lib.rs#L29 */
     312             : static ulong
     313           0 : get_minimum_stake_delegation( fd_exec_slot_ctx_t * slot_ctx ) {
     314           0 :     if ( !FD_FEATURE_ACTIVE( slot_ctx, stake_minimum_delegation_for_rewards ) ) {
     315           0 :         return 0UL;
     316           0 :     }
     317             : 
     318           0 :     if ( FD_FEATURE_ACTIVE( slot_ctx, stake_raise_minimum_delegation_to_1_sol ) ) {
     319           0 :         return LAMPORTS_PER_SOL;
     320           0 :     }
     321             : 
     322           0 :     return 1;
     323           0 : }
     324             : 
     325             : /* Calculates epoch reward points from stake/vote accounts.
     326             : 
     327             :     https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L472 */
     328             : static void
     329             : calculate_reward_points_partitioned(
     330             :     fd_exec_slot_ctx_t *       slot_ctx,
     331             :     fd_stake_history_t const * stake_history,
     332             :     ulong                      rewards,
     333             :     fd_point_value_t *         result,
     334             :     fd_epoch_info_t           *temp_info
     335           0 : ) {
     336             :     /* There is a cache of vote account keys stored in the slot context */
     337             :     /* TODO: check this cache is correct */
     338             : 
     339           0 :     uint128 points = 0;
     340           0 :     ulong minimum_stake_delegation = get_minimum_stake_delegation( slot_ctx );
     341             : 
     342             :     /* Calculate the points for each stake delegation */
     343           0 :     int _err[1];
     344           0 :     ulong * new_warmup_cooldown_rate_epoch = fd_scratch_alloc( alignof(ulong), sizeof(ulong) );
     345           0 :     int is_some = fd_new_warmup_cooldown_rate_epoch( slot_ctx, new_warmup_cooldown_rate_epoch, _err );
     346           0 :     if( FD_UNLIKELY( !is_some ) ) {
     347           0 :         new_warmup_cooldown_rate_epoch = NULL;
     348           0 :     }
     349             : 
     350           0 :     for ( ulong idx = 0; idx < temp_info->infos_len; idx++ ) {
     351           0 :         FD_SCRATCH_SCOPE_BEGIN {
     352           0 :             fd_valloc_t valloc = fd_scratch_virtual();
     353           0 :             fd_stake_t * stake = &temp_info->infos[idx].stake;
     354             : 
     355           0 :             if ( FD_UNLIKELY( stake->delegation.stake < minimum_stake_delegation ) ) {
     356           0 :                 continue;
     357           0 :             }
     358             : 
     359             :             /* Check that the vote account is present in our cache */
     360           0 :             fd_vote_accounts_pair_t_mapnode_t key;
     361           0 :             fd_pubkey_t const * voter_acc = &stake->delegation.voter_pubkey;
     362           0 :             fd_memcpy( &key.elem.key, voter_acc, sizeof(fd_pubkey_t) );
     363           0 :             fd_epoch_bank_t const * epoch_bank = fd_exec_epoch_ctx_epoch_bank(
     364           0 :                 slot_ctx->epoch_ctx );
     365           0 :             if ( FD_UNLIKELY( fd_vote_accounts_pair_t_map_find(
     366           0 :                 epoch_bank->stakes.vote_accounts.vote_accounts_pool,
     367           0 :                 epoch_bank->stakes.vote_accounts.vote_accounts_root,
     368           0 :                 &key ) == NULL ) ) {
     369           0 :                 FD_LOG_DEBUG(( "vote account missing from cache" ));
     370           0 :                 continue;
     371           0 :             }
     372             : 
     373             :             /* Check that the vote account is valid and has the correct owner */
     374             :             // TODO: we need to cache this away...
     375           0 :             FD_BORROWED_ACCOUNT_DECL(voter_acc_rec);
     376           0 :             int err = fd_acc_mgr_view( slot_ctx->acc_mgr, slot_ctx->funk_txn, voter_acc, voter_acc_rec );
     377           0 :             if ( FD_UNLIKELY( err ) ) {
     378           0 :                 FD_LOG_DEBUG(( "failed to read vote account from funk" ));
     379           0 :                 continue;
     380           0 :             }
     381           0 :             if( FD_UNLIKELY( memcmp( &voter_acc_rec->const_meta->info.owner, fd_solana_vote_program_id.key, sizeof(fd_pubkey_t) ) != 0 ) ) {
     382           0 :                 FD_LOG_DEBUG(( "vote account has wrong owner" ));
     383           0 :                 continue;
     384           0 :             }
     385           0 :             fd_bincode_decode_ctx_t decode = {
     386           0 :                 .data    = voter_acc_rec->const_data,
     387           0 :                 .dataend = voter_acc_rec->const_data + voter_acc_rec->const_meta->dlen,
     388           0 :                 .valloc  = valloc,
     389           0 :             };
     390           0 :             fd_vote_state_versioned_t vote_state[1] = {0};
     391           0 :             if( FD_UNLIKELY( 0!=fd_vote_state_versioned_decode( vote_state, &decode ) ) ) {
     392           0 :                 FD_LOG_DEBUG(( "vote_state_versioned_decode failed" ));
     393           0 :                 continue;
     394           0 :             }
     395             : 
     396           0 :             uint128 account_points;
     397           0 :             err = calculate_points( stake, vote_state, stake_history, new_warmup_cooldown_rate_epoch, &account_points );
     398           0 :             if ( FD_UNLIKELY( err ) ) {
     399           0 :                 FD_LOG_DEBUG(( "failed to calculate points" ));
     400           0 :                 continue;
     401           0 :             }
     402             : 
     403           0 :             points += account_points;
     404           0 :         } FD_SCRATCH_SCOPE_END;
     405           0 :     }
     406             : 
     407           0 :     if (points > 0) {
     408           0 :         result->points = points;
     409           0 :         result->rewards = rewards;
     410           0 :     }
     411           0 : }
     412             : 
     413             : /* Calculate the partitioned stake rewards for a single stake/vote account pair, updates result with these. */
     414             : static void
     415             : calculate_stake_vote_rewards_account(
     416             :     fd_exec_slot_ctx_t *                        slot_ctx,
     417             :     fd_stake_history_t const *                  stake_history,
     418             :     ulong                                       rewarded_epoch,
     419             :     fd_point_value_t *                          point_value,
     420             :     fd_pubkey_t const *                         stake_acc,
     421             :     fd_calculate_stake_vote_rewards_result_t *  result
     422           0 : ) {
     423           0 :     FD_SCRATCH_SCOPE_BEGIN {
     424           0 :         int _err[1];
     425           0 :         ulong * new_warmup_cooldown_rate_epoch = fd_scratch_alloc( alignof(ulong), sizeof(ulong) );
     426           0 :         int is_some = fd_new_warmup_cooldown_rate_epoch( slot_ctx, new_warmup_cooldown_rate_epoch, _err );
     427           0 :         if( FD_UNLIKELY( !is_some ) ) {
     428           0 :             new_warmup_cooldown_rate_epoch = NULL;
     429           0 :         }
     430             : 
     431           0 :         fd_epoch_bank_t const * epoch_bank = fd_exec_epoch_ctx_epoch_bank( slot_ctx->epoch_ctx );
     432           0 :         ulong minimum_stake_delegation = get_minimum_stake_delegation( slot_ctx );
     433             : 
     434           0 :         FD_BORROWED_ACCOUNT_DECL( stake_acc_rec );
     435           0 :         if( fd_acc_mgr_view( slot_ctx->acc_mgr, slot_ctx->funk_txn, stake_acc, stake_acc_rec) != 0 ) {
     436           0 :             FD_LOG_DEBUG(( "Stake acc not found %s", FD_BASE58_ENC_32_ALLOCA( stake_acc->uc ) ));
     437           0 :             return;
     438           0 :         }
     439             : 
     440           0 :         fd_stake_state_v2_t stake_state[1] = {0};
     441           0 :         if ( fd_stake_get_state( stake_acc_rec, &slot_ctx->valloc, stake_state ) != 0 ) {
     442           0 :             FD_LOG_DEBUG(( "Failed to read stake state from stake account %s", FD_BASE58_ENC_32_ALLOCA( stake_acc ) ));
     443           0 :             return;
     444           0 :         }
     445           0 :         if ( !fd_stake_state_v2_is_stake( stake_state ) ) {
     446           0 :             FD_LOG_DEBUG(( "stake account does not have active delegation" ));
     447           0 :             return;
     448           0 :         }
     449           0 :         fd_pubkey_t const * voter_acc = &stake_state->inner.stake.stake.delegation.voter_pubkey;
     450             : 
     451           0 :         if ( FD_FEATURE_ACTIVE(slot_ctx, stake_minimum_delegation_for_rewards )) {
     452           0 :             if ( stake_state->inner.stake.stake.delegation.stake < minimum_stake_delegation ) {
     453           0 :                 return;
     454           0 :             }
     455           0 :         }
     456             : 
     457           0 :         fd_vote_accounts_pair_t_mapnode_t key;
     458           0 :         fd_memcpy( &key.elem.key, voter_acc, sizeof(fd_pubkey_t) );
     459           0 :         if ( fd_vote_accounts_pair_t_map_find( epoch_bank->stakes.vote_accounts.vote_accounts_pool, epoch_bank->stakes.vote_accounts.vote_accounts_root, &key ) == NULL
     460           0 :             && fd_vote_accounts_pair_t_map_find( slot_ctx->slot_bank.vote_account_keys.vote_accounts_pool, slot_ctx->slot_bank.vote_account_keys.vote_accounts_root, &key ) == NULL) {
     461           0 :         return;
     462           0 :         }
     463             : 
     464           0 :         FD_BORROWED_ACCOUNT_DECL( voter_acc_rec );
     465           0 :         int read_err = fd_acc_mgr_view( slot_ctx->acc_mgr, slot_ctx->funk_txn, voter_acc, voter_acc_rec );
     466           0 :         if( read_err!=0 || memcmp( &voter_acc_rec->const_meta->info.owner, fd_solana_vote_program_id.key, sizeof(fd_pubkey_t) ) != 0 ) {
     467           0 :         return;
     468           0 :         }
     469             : 
     470           0 :         fd_valloc_t valloc = fd_scratch_virtual();
     471           0 :         fd_bincode_decode_ctx_t decode = {
     472           0 :             .data    = voter_acc_rec->const_data,
     473           0 :             .dataend = voter_acc_rec->const_data + voter_acc_rec->const_meta->dlen,
     474           0 :             .valloc  = valloc,
     475           0 :         };
     476           0 :         fd_vote_state_versioned_t vote_state_versioned[1] = {0};
     477           0 :         if( fd_vote_state_versioned_decode( vote_state_versioned, &decode ) != 0 ) {
     478           0 :             FD_LOG_ERR(( "failed to decode vote state" ));
     479           0 :             return;
     480           0 :         }
     481             : 
     482             :         /* Note, this doesn't actually redeem any rewards.. this is a misnomer. */
     483           0 :         fd_calculated_stake_rewards_t calculated_stake_rewards[1] = {0};
     484           0 :         int err = redeem_rewards( stake_history, stake_state, vote_state_versioned, rewarded_epoch, point_value, new_warmup_cooldown_rate_epoch, calculated_stake_rewards );
     485           0 :         if ( err != 0) {
     486           0 :             FD_LOG_DEBUG(( "redeem_rewards failed for %s with error %d", FD_BASE58_ENC_32_ALLOCA( stake_acc->key ), err ));
     487           0 :             return;
     488           0 :         }
     489             : 
     490             :         /* Fetch the comission for the vote account */
     491           0 :         uchar commission = 0;
     492           0 :         switch (vote_state_versioned->discriminant) {
     493           0 :             case fd_vote_state_versioned_enum_current:
     494           0 :                 commission = vote_state_versioned->inner.current.commission;
     495           0 :                 break;
     496           0 :             case fd_vote_state_versioned_enum_v0_23_5:
     497           0 :                 commission = vote_state_versioned->inner.v0_23_5.commission;
     498           0 :                 break;
     499           0 :             case fd_vote_state_versioned_enum_v1_14_11:
     500           0 :                 commission = vote_state_versioned->inner.v1_14_11.commission;
     501           0 :                 break;
     502           0 :             default:
     503           0 :                 FD_LOG_DEBUG(( "unsupported vote account" ));
     504           0 :                 return;
     505           0 :         }
     506             : 
     507             :         /* Update the vote reward in the map */
     508           0 :         fd_vote_reward_t_mapnode_t vote_map_key[1];
     509           0 :         fd_memcpy( &vote_map_key->elem.pubkey, voter_acc, sizeof(fd_pubkey_t) );
     510           0 :         fd_vote_reward_t_mapnode_t * vote_reward_node = fd_vote_reward_t_map_find( result->vote_reward_map_pool, result->vote_reward_map_root, vote_map_key );
     511           0 :         if ( vote_reward_node == NULL ) {
     512           0 :             vote_reward_node = fd_vote_reward_t_map_acquire( result->vote_reward_map_pool );
     513           0 :             fd_memcpy( &vote_reward_node->elem.pubkey, voter_acc, sizeof(fd_pubkey_t) );
     514           0 :             vote_reward_node->elem.commission = commission;
     515           0 :             vote_reward_node->elem.vote_rewards = calculated_stake_rewards->voter_rewards;
     516           0 :             vote_reward_node->elem.needs_store = 1;
     517           0 :             fd_vote_reward_t_map_insert( result->vote_reward_map_pool, &result->vote_reward_map_root, vote_reward_node );
     518           0 :         } else {
     519           0 :             vote_reward_node->elem.needs_store = 1;
     520           0 :             vote_reward_node->elem.vote_rewards = fd_ulong_sat_add(
     521           0 :                 vote_reward_node->elem.vote_rewards, calculated_stake_rewards->voter_rewards
     522           0 :             );
     523           0 :         }
     524             : 
     525             :         /* Add the stake reward to list of all stake rewards */
     526           0 :         fd_stake_reward_t * stake_reward = fd_stake_reward_pool_ele_acquire( result->stake_reward_calculation.pool );
     527           0 :         fd_memcpy( &stake_reward->stake_pubkey, stake_acc, FD_PUBKEY_FOOTPRINT );
     528           0 :         stake_reward->lamports = calculated_stake_rewards->staker_rewards;
     529           0 :         stake_reward->credits_observed = calculated_stake_rewards->new_credits_observed;
     530             : 
     531           0 :         fd_stake_reward_dlist_ele_push_tail(
     532           0 :             &result->stake_reward_calculation.stake_rewards,
     533           0 :             stake_reward,
     534           0 :             result->stake_reward_calculation.pool );
     535           0 :         result->stake_reward_calculation.stake_rewards_len += 1;
     536             : 
     537             :         /* Update the total stake rewards */
     538           0 :         result->stake_reward_calculation.total_stake_rewards_lamports += calculated_stake_rewards->staker_rewards;
     539           0 :     } FD_SCRATCH_SCOPE_END;
     540           0 : }
     541             : 
     542             : /* Calculates epoch rewards for stake/vote accounts.
     543             :    Returns vote rewards, stake rewards, and the sum of all stake rewards in lamports.
     544             : 
     545             :    This uses a pool to allocate the stake rewards, which means that we can use dlists to
     546             :    distribute these into partitions of variable size without copying them or over-allocating
     547             :    the partitions.
     548             :    - We use a single dlist to put all the stake rewards during the calculation phase.
     549             :    - We then distribute these into partitions (whose size cannot be known in advance), where each
     550             :      partition is a seperate dlist.
     551             :    - The dlist elements are all backed by the same pool, and allocated once.
     552             :    This approach optimizes memory usage and reduces copying.
     553             : 
     554             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L334 */
     555             : static void
     556             : calculate_stake_vote_rewards(
     557             :     fd_exec_slot_ctx_t *                       slot_ctx,
     558             :     fd_stake_history_t const *                 stake_history,
     559             :     ulong                                      rewarded_epoch,
     560             :     fd_point_value_t *                         point_value,
     561             :     fd_calculate_stake_vote_rewards_result_t * result
     562           0 : ) {
     563           0 :     fd_epoch_bank_t const * epoch_bank = fd_exec_epoch_ctx_epoch_bank( slot_ctx->epoch_ctx );
     564           0 :     ulong rewards_max_count = fd_ulong_sat_add(
     565           0 :         fd_delegation_pair_t_map_size( epoch_bank->stakes.stake_delegations_pool, epoch_bank->stakes.stake_delegations_root ),
     566           0 :         fd_stake_accounts_pair_t_map_size( slot_ctx->slot_bank.stake_account_keys.stake_accounts_pool, slot_ctx->slot_bank.stake_account_keys.stake_accounts_root ) );
     567             : 
     568             :     /* Create the stake rewards pool and dlist. The pool will be destoyed after the stake rewards have been distributed. */
     569           0 :     result->stake_reward_calculation.pool = fd_stake_reward_pool_join(
     570           0 :         fd_stake_reward_pool_new(
     571           0 :             fd_valloc_malloc(
     572           0 :                 slot_ctx->valloc,
     573           0 :                 fd_stake_reward_pool_align(),
     574           0 :                 fd_stake_reward_pool_footprint( rewards_max_count ) ), rewards_max_count ) );
     575           0 :     fd_stake_reward_dlist_new( &result->stake_reward_calculation.stake_rewards );
     576           0 :     result->stake_reward_calculation.stake_rewards_len = 0UL;
     577             : 
     578             :     /* Create the vote rewards map. This will be destroyed after the vote rewards have been distributed. */
     579           0 :     result->vote_reward_map_pool = fd_vote_reward_t_map_join( fd_vote_reward_t_map_new( fd_valloc_malloc(
     580           0 :         slot_ctx->valloc,
     581           0 :         fd_vote_reward_t_map_align(),
     582           0 :         fd_vote_reward_t_map_footprint( rewards_max_count )), rewards_max_count ) );
     583           0 :     result->vote_reward_map_root = NULL;
     584             : 
     585             :     /* Loop over all the delegations
     586             : 
     587             :         https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L367  */
     588           0 :     for( fd_delegation_pair_t_mapnode_t const * n = fd_delegation_pair_t_map_minimum_const(
     589           0 :          epoch_bank->stakes.stake_delegations_pool, epoch_bank->stakes.stake_delegations_root );
     590           0 :          n;
     591           0 :          n = fd_delegation_pair_t_map_successor_const( epoch_bank->stakes.stake_delegations_pool, n )
     592           0 :     ) {
     593           0 :         fd_pubkey_t const * stake_acc = &n->elem.account;
     594             : 
     595           0 :         calculate_stake_vote_rewards_account(
     596           0 :             slot_ctx,
     597           0 :             stake_history,
     598           0 :             rewarded_epoch,
     599           0 :             point_value,
     600           0 :             stake_acc,
     601           0 :             result );
     602           0 :     }
     603             : 
     604             :     /* Loop over all the stake accounts in the slot bank pool */
     605           0 :     for ( fd_stake_accounts_pair_t_mapnode_t const * n =
     606           0 :         fd_stake_accounts_pair_t_map_minimum_const(
     607           0 :             slot_ctx->slot_bank.stake_account_keys.stake_accounts_pool, slot_ctx->slot_bank.stake_account_keys.stake_accounts_root );
     608           0 :          n;
     609           0 :          n = fd_stake_accounts_pair_t_map_successor_const( slot_ctx->slot_bank.stake_account_keys.stake_accounts_pool, n) ) {
     610             : 
     611           0 :         fd_pubkey_t const * stake_acc = &n->elem.key;
     612           0 :         calculate_stake_vote_rewards_account(
     613           0 :             slot_ctx,
     614           0 :             stake_history,
     615           0 :             rewarded_epoch,
     616           0 :             point_value,
     617           0 :             stake_acc,
     618           0 :             result );
     619           0 :     }
     620           0 : }
     621             : 
     622             : /* Calculate epoch reward and return vote and stake rewards.
     623             : 
     624             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L273 */
     625             : static void
     626             : calculate_validator_rewards(
     627             :     fd_exec_slot_ctx_t * slot_ctx,
     628             :     ulong rewarded_epoch,
     629             :     ulong rewards,
     630             :     fd_calculate_validator_rewards_result_t * result,
     631             :     fd_epoch_info_t           *temp_info
     632           0 : ) {
     633             :     /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L2759-L2786 */
     634           0 :     fd_stake_history_t const * stake_history = fd_sysvar_cache_stake_history( slot_ctx->sysvar_cache );
     635           0 :     if( FD_UNLIKELY( !stake_history ) ) {
     636           0 :         FD_LOG_ERR(( "StakeHistory sysvar is missing from sysvar cache" ));
     637           0 :     }
     638             : 
     639             :     /* Calculate the epoch reward points from stake/vote accounts */
     640           0 :     calculate_reward_points_partitioned( slot_ctx, stake_history, rewards, &result->point_value, temp_info );
     641             : 
     642             :     /* Calculate the stake and vote rewards for each account */
     643           0 :     calculate_stake_vote_rewards(
     644           0 :         slot_ctx,
     645           0 :         stake_history,
     646           0 :         rewarded_epoch,
     647           0 :         &result->point_value,
     648           0 :         &result->calculate_stake_vote_rewards_result );
     649           0 : }
     650             : 
     651             : /* Calculate the number of blocks required to distribute rewards to all stake accounts.
     652             : 
     653             :     https://github.com/anza-xyz/agave/blob/9a7bf72940f4b3cd7fc94f54e005868ce707d53d/runtime/src/bank/partitioned_epoch_rewards/mod.rs#L214
     654             :  */
     655             : static ulong
     656             : get_reward_distribution_num_blocks(
     657             :     fd_epoch_schedule_t const * epoch_schedule,
     658             :     ulong slot,
     659             :     ulong total_stake_accounts
     660           0 : ) {
     661             :     /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L1250-L1267 */
     662           0 :     if ( epoch_schedule->warmup &&
     663           0 :          fd_slot_to_epoch( epoch_schedule, slot, NULL ) < epoch_schedule->first_normal_epoch ) {
     664           0 :         return 1UL;
     665           0 :     }
     666             : 
     667           0 :     ulong num_chunks = total_stake_accounts / (ulong)STAKE_ACCOUNT_STORES_PER_BLOCK + (total_stake_accounts % STAKE_ACCOUNT_STORES_PER_BLOCK != 0);
     668           0 :     num_chunks = fd_ulong_max( num_chunks, 1 );
     669           0 :     num_chunks = fd_ulong_min(
     670           0 :         num_chunks,
     671           0 :         fd_ulong_max(
     672           0 :             epoch_schedule->slots_per_epoch / (ulong)MAX_FACTOR_OF_REWARD_BLOCKS_IN_EPOCH,
     673           0 :             1) );
     674           0 :     return num_chunks;
     675           0 : }
     676             : 
     677             : static void
     678             : hash_rewards_into_partitions(
     679             :     fd_exec_slot_ctx_t *                        slot_ctx,
     680             :     fd_stake_reward_calculation_t *             stake_reward_calculation,
     681             :     const fd_hash_t *                           parent_blockhash,
     682             :     fd_stake_reward_calculation_partitioned_t * result
     683           0 : ) {
     684             :     /* Initialize a dlist for every partition.
     685             :        These will all use the same pool - we do not re-allocate the stake rewards, only move them into partitions. */
     686           0 :     result->partitioned_stake_rewards.pool = stake_reward_calculation->pool;
     687           0 :     ulong num_partitions = get_reward_distribution_num_blocks(
     688           0 :         &fd_exec_epoch_ctx_epoch_bank( slot_ctx->epoch_ctx )->epoch_schedule,
     689           0 :         slot_ctx->slot_bank.slot,
     690           0 :         stake_reward_calculation->stake_rewards_len);
     691           0 :     result->partitioned_stake_rewards.partitions_len = num_partitions;
     692           0 :     result->partitioned_stake_rewards.partitions = fd_valloc_malloc(
     693           0 :         slot_ctx->valloc,
     694           0 :         fd_stake_reward_dlist_align(),
     695           0 :         fd_stake_reward_dlist_footprint() * num_partitions
     696           0 :     );
     697             : 
     698             :     /* Ownership of these dlist's and the pool gets transferred to stake_rewards_by_partition, which then gets transferred to epoch_reward_status.
     699             :        These are eventually cleaned up when epoch_reward_status_inactive is called. */
     700           0 :     for ( ulong i = 0; i < num_partitions; ++i ) {
     701           0 :         fd_stake_reward_dlist_new( &result->partitioned_stake_rewards.partitions[ i ] );
     702           0 :     }
     703             : 
     704             :     /* Iterate over all the stake rewards, moving references to them into the appropiate partitions.
     705             :        IMPORTANT: after this, we cannot use the original stake rewards dlist anymore. */
     706           0 :     fd_stake_reward_dlist_iter_t next_iter;
     707           0 :     for ( fd_stake_reward_dlist_iter_t iter = fd_stake_reward_dlist_iter_fwd_init(
     708           0 :             &stake_reward_calculation->stake_rewards, stake_reward_calculation->pool );
     709           0 :           !fd_stake_reward_dlist_iter_done( iter, &stake_reward_calculation->stake_rewards, stake_reward_calculation->pool );
     710           0 :         iter = next_iter
     711           0 :     ) {
     712           0 :         fd_stake_reward_t * stake_reward = fd_stake_reward_dlist_iter_ele( iter, &stake_reward_calculation->stake_rewards, stake_reward_calculation->pool );
     713             :         /* Cache the next iter here, as we will overwrite the DLIST_NEXT value further down in the loop iteration. */
     714           0 :         next_iter = fd_stake_reward_dlist_iter_fwd_next( iter, &stake_reward_calculation->stake_rewards, stake_reward_calculation->pool );
     715             : 
     716             :         /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/epoch_rewards_hasher.rs#L43C31-L61 */
     717           0 :         fd_siphash13_t  _sip[1] = {0};
     718           0 :         fd_siphash13_t * hasher = fd_siphash13_init( _sip, 0UL, 0UL );
     719             : 
     720           0 :         hasher = fd_siphash13_append( hasher, parent_blockhash->hash, sizeof(fd_hash_t) );
     721           0 :         fd_siphash13_append( hasher, (const uchar *) stake_reward->stake_pubkey.key, sizeof(fd_pubkey_t) );
     722             : 
     723           0 :         ulong hash64 = fd_siphash13_fini( hasher );
     724             :         /* hash_to_partition */
     725             :         /* FIXME: should be saturating add */
     726           0 :         ulong partition_index = (ulong)(
     727           0 :             (uint128) num_partitions *
     728           0 :             (uint128) hash64 /
     729           0 :             ((uint128)ULONG_MAX + 1)
     730           0 :         );
     731             : 
     732             :         /* Move the stake reward to the partition's dlist */
     733           0 :         fd_stake_reward_dlist_t * partition = &result->partitioned_stake_rewards.partitions[ partition_index ];
     734           0 :         fd_stake_reward_dlist_ele_push_tail( partition, stake_reward, stake_reward_calculation->pool );
     735           0 :     }
     736           0 : }
     737             : 
     738             : /* Calculate rewards from previous epoch to prepare for partitioned distribution.
     739             : 
     740             :    https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L214 */
     741             : static void
     742             : calculate_rewards_for_partitioning(
     743             :     fd_exec_slot_ctx_t                   * slot_ctx,
     744             :     ulong                                  prev_epoch,
     745             :     const fd_hash_t                      * parent_blockhash,
     746             :     fd_partitioned_rewards_calculation_t * result,
     747             :     fd_epoch_info_t                      * temp_info
     748           0 : ) {
     749             :     /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L227 */
     750           0 :     fd_prev_epoch_inflation_rewards_t rewards;
     751           0 :     calculate_previous_epoch_inflation_rewards( slot_ctx, slot_ctx->slot_bank.capitalization, prev_epoch, &rewards );
     752             : 
     753           0 :     fd_slot_bank_t const * slot_bank = &slot_ctx->slot_bank;
     754             : 
     755           0 :     fd_calculate_validator_rewards_result_t validator_result[1] = {0};
     756           0 :     calculate_validator_rewards( slot_ctx, prev_epoch, rewards.validator_rewards, validator_result, temp_info );
     757             : 
     758           0 :     hash_rewards_into_partitions(
     759           0 :         slot_ctx,
     760           0 :         &validator_result->calculate_stake_vote_rewards_result.stake_reward_calculation,
     761           0 :         parent_blockhash,
     762           0 :         &result->stake_rewards_by_partition );
     763           0 :     result->stake_rewards_by_partition.total_stake_rewards_lamports =
     764           0 :         validator_result->calculate_stake_vote_rewards_result.stake_reward_calculation.total_stake_rewards_lamports;
     765             : 
     766           0 :     result->vote_reward_map_pool = validator_result->calculate_stake_vote_rewards_result.vote_reward_map_pool;
     767           0 :     result->vote_reward_map_root = validator_result->calculate_stake_vote_rewards_result.vote_reward_map_root;
     768           0 :     result->validator_rewards = rewards.validator_rewards;
     769           0 :     result->validator_rate = rewards.validator_rate;
     770           0 :     result->foundation_rate = rewards.foundation_rate;
     771           0 :     result->prev_epoch_duration_in_years = rewards.prev_epoch_duration_in_years;
     772           0 :     result->capitalization = slot_bank->capitalization;
     773           0 :     fd_memcpy( &result->point_value, &validator_result->point_value, FD_POINT_VALUE_FOOTPRINT );
     774           0 : }
     775             : 
     776             : /* Calculate rewards from previous epoch and distribute vote rewards
     777             : 
     778             :    https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L97 */
     779             : static void
     780             : calculate_rewards_and_distribute_vote_rewards(
     781             :     fd_exec_slot_ctx_t *                                        slot_ctx,
     782             :     ulong                                                       prev_epoch,
     783             :     const fd_hash_t *                                           parent_blockhash,
     784             :     fd_calculate_rewards_and_distribute_vote_rewards_result_t * result,
     785             :     fd_epoch_info_t                                            *temp_info
     786           0 : ) {
     787             :     /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L2406-L2492 */
     788           0 :     fd_partitioned_rewards_calculation_t rewards_calc_result[1] = {0};
     789           0 :     calculate_rewards_for_partitioning( slot_ctx, prev_epoch, parent_blockhash, rewards_calc_result, temp_info );
     790             : 
     791             :     /* Iterate over all the vote reward nodes */
     792           0 :     for ( fd_vote_reward_t_mapnode_t* vote_reward_node = fd_vote_reward_t_map_minimum(
     793           0 :             rewards_calc_result->vote_reward_map_pool,
     794           0 :             rewards_calc_result->vote_reward_map_root);
     795           0 :             vote_reward_node;
     796           0 :             vote_reward_node = fd_vote_reward_t_map_successor( rewards_calc_result->vote_reward_map_pool, vote_reward_node ) ) {
     797             : 
     798           0 :         fd_pubkey_t const * vote_pubkey = &vote_reward_node->elem.pubkey;
     799           0 :         FD_BORROWED_ACCOUNT_DECL( vote_rec );
     800           0 :         FD_TEST( fd_acc_mgr_modify( slot_ctx->acc_mgr, slot_ctx->funk_txn, vote_pubkey, 1, 0UL, vote_rec ) == FD_ACC_MGR_SUCCESS );
     801           0 :         vote_rec->meta->slot = slot_ctx->slot_bank.slot;
     802             : 
     803           0 :         FD_TEST( fd_borrowed_account_checked_add_lamports( vote_rec, vote_reward_node->elem.vote_rewards ) == 0 );
     804           0 :         result->distributed_rewards = fd_ulong_sat_add( result->distributed_rewards, vote_reward_node->elem.vote_rewards );
     805           0 :     }
     806             : 
     807             :     /* Free the vote reward map */
     808           0 :     fd_valloc_free( slot_ctx->valloc,
     809           0 :         fd_vote_reward_t_map_delete(
     810           0 :             fd_vote_reward_t_map_leave( rewards_calc_result->vote_reward_map_pool ) ) );
     811             : 
     812             :     /* Verify that we didn't pay any more than we expected to */
     813           0 :     result->total_rewards = fd_ulong_sat_add( result->distributed_rewards, rewards_calc_result->stake_rewards_by_partition.total_stake_rewards_lamports );
     814           0 :     FD_TEST( rewards_calc_result->validator_rewards >= result->total_rewards );
     815             : 
     816           0 :     slot_ctx->slot_bank.capitalization += result->distributed_rewards;
     817             : 
     818             :     /* Cheap because this doesn't copy all the rewards, just pointers to the dlist */
     819           0 :     fd_memcpy( &result->stake_rewards_by_partition, &rewards_calc_result->stake_rewards_by_partition, FD_STAKE_REWARD_CALCULATION_PARTITIONED_FOOTPRINT );
     820           0 :     fd_memcpy( &result->point_value, &rewards_calc_result->point_value, FD_POINT_VALUE_FOOTPRINT );
     821           0 : }
     822             : 
     823             : /* Distributes a single partitioned reward to a single stake account */
     824             : static int
     825             : distribute_epoch_reward_to_stake_acc(
     826             :     fd_exec_slot_ctx_t * slot_ctx,
     827             :     fd_pubkey_t *        stake_pubkey,
     828             :     ulong                reward_lamports,
     829             :     ulong                new_credits_observed
     830           0 :  ) {
     831             : 
     832           0 :     FD_BORROWED_ACCOUNT_DECL( stake_acc_rec );
     833           0 :     FD_TEST( fd_acc_mgr_modify( slot_ctx->acc_mgr, slot_ctx->funk_txn, stake_pubkey, 0, 0UL, stake_acc_rec ) == FD_ACC_MGR_SUCCESS );
     834           0 :     stake_acc_rec->meta->slot = slot_ctx->slot_bank.slot;
     835             : 
     836           0 :     fd_stake_state_v2_t stake_state[1] = {0};
     837           0 :     if ( fd_stake_get_state(stake_acc_rec, &slot_ctx->valloc, stake_state) != 0 ) {
     838           0 :         FD_LOG_DEBUG(( "failed to read stake state for %s", FD_BASE58_ENC_32_ALLOCA( stake_pubkey ) ));
     839           0 :         return 1;
     840           0 :     }
     841             : 
     842           0 :     if ( !fd_stake_state_v2_is_stake( stake_state ) ) {
     843           0 :         FD_LOG_DEBUG(( "non-stake stake account, this should never happen" ));
     844           0 :         return 1;
     845           0 :     }
     846             : 
     847           0 :     if( fd_borrowed_account_checked_add_lamports( stake_acc_rec, reward_lamports ) ) {
     848           0 :         FD_LOG_DEBUG(( "failed to add lamports to stake account" ));
     849           0 :         return 1;
     850           0 :     }
     851             : 
     852           0 :     stake_state->inner.stake.stake.credits_observed = new_credits_observed;
     853           0 :     stake_state->inner.stake.stake.delegation.stake = fd_ulong_sat_add(
     854           0 :         stake_state->inner.stake.stake.delegation.stake,
     855           0 :         reward_lamports
     856           0 :     );
     857             : 
     858           0 :     if ( FD_UNLIKELY( write_stake_state( stake_acc_rec, stake_state ) != 0 ) ) {
     859           0 :         FD_LOG_ERR(( "write_stake_state failed" ));
     860           0 :     }
     861             : 
     862           0 :     return 0;
     863           0 : }
     864             : 
     865             : /* Sets the epoch reward status to inactive, and destroys any allocated state associated with the active state. */
     866             : static void
     867             : set_epoch_reward_status_inactive(
     868             :     fd_exec_slot_ctx_t * slot_ctx
     869           0 : ) {
     870           0 :     if ( slot_ctx->epoch_reward_status.discriminant == fd_epoch_reward_status_enum_Active ) {
     871           0 :         fd_partitioned_stake_rewards_t * partitioned_rewards = &slot_ctx->epoch_reward_status.inner.Active.partitioned_stake_rewards;
     872             :         /* Destroy the partitions */
     873           0 :         fd_valloc_free( slot_ctx->valloc,
     874           0 :             fd_stake_reward_dlist_delete(
     875           0 :                 fd_stake_reward_dlist_leave( partitioned_rewards->partitions ) ) );
     876             : 
     877             :         /* Destroy the underlying pool */
     878           0 :         fd_valloc_free(
     879           0 :             slot_ctx->valloc,
     880           0 :                 fd_stake_reward_pool_delete(
     881           0 :                     fd_stake_reward_pool_leave( partitioned_rewards->pool ) ) );
     882           0 :     }
     883           0 :     slot_ctx->epoch_reward_status.discriminant = fd_epoch_reward_status_enum_Inactive;
     884           0 : }
     885             : 
     886             : /* Sets the epoch reward status to active.
     887             : 
     888             :     Takes ownership of the given stake_rewards_by_partition data structure,
     889             :     which will be destroyed when set_epoch_reward_status_inactive is called. */
     890             : static void
     891             : set_epoch_reward_status_active(
     892             :     fd_exec_slot_ctx_t * slot_ctx,
     893             :     ulong distribution_starting_block_height,
     894           0 :     fd_partitioned_stake_rewards_t * partitioned_rewards ) {
     895             : 
     896           0 :     slot_ctx->epoch_reward_status.discriminant = fd_epoch_reward_status_enum_Active;
     897           0 :     slot_ctx->epoch_reward_status.inner.Active.distribution_starting_block_height = distribution_starting_block_height;
     898             : 
     899           0 :     fd_memcpy( &slot_ctx->epoch_reward_status.inner.Active.partitioned_stake_rewards, partitioned_rewards, FD_PARTITIONED_STAKE_REWARDS_FOOTPRINT );
     900           0 : }
     901             : 
     902             : /*  Process reward credits for a partition of rewards.
     903             :     Store the rewards to AccountsDB, update reward history record and total capitalization
     904             : 
     905             :     https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/distribution.rs#L88 */
     906             : static void
     907             : distribute_epoch_rewards_in_partition(
     908             :     fd_stake_reward_dlist_t * partition,
     909             :     fd_stake_reward_t *pool,
     910             :     fd_exec_slot_ctx_t * slot_ctx
     911           0 : ) {
     912             : 
     913           0 :     ulong lamports_distributed = 0UL;
     914           0 :     ulong lamports_burned = 0UL;
     915             : 
     916           0 :     for ( fd_stake_reward_dlist_iter_t iter = fd_stake_reward_dlist_iter_fwd_init( partition, pool );
     917           0 :           !fd_stake_reward_dlist_iter_done( iter, partition, pool );
     918           0 :         iter = fd_stake_reward_dlist_iter_fwd_next( iter, partition, pool )
     919           0 :     ) {
     920           0 :         fd_stake_reward_t * stake_reward = fd_stake_reward_dlist_iter_ele( iter, partition, pool );
     921             : 
     922           0 :         if ( distribute_epoch_reward_to_stake_acc(
     923           0 :             slot_ctx,
     924           0 :             &stake_reward->stake_pubkey,
     925           0 :             stake_reward->lamports,
     926           0 :             stake_reward->credits_observed ) == 0 ) {
     927           0 :             lamports_distributed += stake_reward->lamports;
     928           0 :         } else {
     929           0 :             lamports_burned += stake_reward->lamports;
     930           0 :         }
     931             : 
     932           0 :     }
     933             : 
     934             :     /* Update the epoch rewards sysvar with the amount distributed and burnt */
     935           0 :     if ( FD_LIKELY( (
     936           0 :         FD_FEATURE_ACTIVE( slot_ctx, enable_partitioned_epoch_reward ) ||
     937           0 :         FD_FEATURE_ACTIVE( slot_ctx, partitioned_epoch_rewards_superfeature ) ) ) ) {
     938           0 :         fd_sysvar_epoch_rewards_distribute( slot_ctx, lamports_distributed + lamports_burned );
     939           0 :     }
     940             : 
     941           0 :     FD_LOG_DEBUG(( "lamports burned: %lu, lamports distributed: %lu", lamports_burned, lamports_distributed ));
     942             : 
     943           0 :     slot_ctx->slot_bank.capitalization += lamports_distributed;
     944           0 : }
     945             : 
     946             : /* Process reward distribution for the block if it is inside reward interval.
     947             : 
     948             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/distribution.rs#L42 */
     949             : void
     950             : fd_distribute_partitioned_epoch_rewards(
     951             :     fd_exec_slot_ctx_t * slot_ctx
     952           0 : ) {
     953           0 :     if ( slot_ctx->epoch_reward_status.discriminant == fd_epoch_reward_status_enum_Inactive ) {
     954           0 :         return;
     955           0 :     }
     956           0 :     fd_start_block_height_and_rewards_t * status = &slot_ctx->epoch_reward_status.inner.Active;
     957             : 
     958           0 :     fd_slot_bank_t * slot_bank = &slot_ctx->slot_bank;
     959           0 :     ulong height = slot_bank->block_height;
     960           0 :     fd_epoch_bank_t const * epoch_bank = fd_exec_epoch_ctx_epoch_bank_const( slot_ctx->epoch_ctx );
     961             : 
     962           0 :     ulong distribution_starting_block_height = status->distribution_starting_block_height;
     963           0 :     ulong distribution_end_exclusive = distribution_starting_block_height + status->partitioned_stake_rewards.partitions_len;
     964             : 
     965             :     /* TODO: track current epoch in epoch ctx? */
     966           0 :     ulong epoch = fd_slot_to_epoch( &epoch_bank->epoch_schedule, slot_bank->slot, NULL );
     967           0 :     FD_TEST( get_slots_in_epoch( epoch, epoch_bank ) > status->partitioned_stake_rewards.partitions_len );
     968             : 
     969           0 :     if ( ( height >= distribution_starting_block_height ) && ( height < distribution_end_exclusive ) ) {
     970           0 :         ulong partition_index = height - distribution_starting_block_height;
     971           0 :         distribute_epoch_rewards_in_partition(
     972           0 :             &status->partitioned_stake_rewards.partitions[ partition_index ],
     973           0 :             status->partitioned_stake_rewards.pool,
     974           0 :             slot_ctx
     975           0 :         );
     976           0 :     }
     977             : 
     978             :     /* If we have finished distributing rewards, set the status to inactive */
     979           0 :     if ( fd_ulong_sat_add( height, 1UL ) >= distribution_end_exclusive ) {
     980           0 :         set_epoch_reward_status_inactive( slot_ctx );
     981           0 :         fd_sysvar_epoch_rewards_set_inactive( slot_ctx );
     982           0 :     }
     983           0 : }
     984             : 
     985             : /* Non-partitioned epoch rewards entry-point. This uses the same logic as the partitioned epoch rewards code,
     986             :    but distributes the rewards in one go.  */
     987             : void
     988             : fd_update_rewards(
     989             :     fd_exec_slot_ctx_t * slot_ctx,
     990             :     const fd_hash_t *    parent_blockhash,
     991             :     ulong                parent_epoch,
     992             :     fd_epoch_info_t    * temp_info
     993           0 : ) {
     994             : 
     995             :     /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L55 */
     996           0 :     fd_calculate_rewards_and_distribute_vote_rewards_result_t rewards_result[1] = {0};
     997           0 :     calculate_rewards_and_distribute_vote_rewards(
     998           0 :         slot_ctx,
     999           0 :         parent_epoch,
    1000           0 :         parent_blockhash,
    1001           0 :         rewards_result,
    1002           0 :         temp_info
    1003           0 :     );
    1004             : 
    1005             :     /* Distribute all of the partitioned epoch rewards in one go */
    1006           0 :     for ( ulong i = 0UL; i < rewards_result->stake_rewards_by_partition.partitioned_stake_rewards.partitions_len; i++ ) {
    1007           0 :         distribute_epoch_rewards_in_partition(
    1008           0 :             &rewards_result->stake_rewards_by_partition.partitioned_stake_rewards.partitions[ i ],
    1009           0 :             rewards_result->stake_rewards_by_partition.partitioned_stake_rewards.pool,
    1010           0 :             slot_ctx
    1011           0 :         );
    1012           0 :     }
    1013           0 : }
    1014             : 
    1015             : /* Partitioned epoch rewards entry-point.
    1016             : 
    1017             :    https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L41
    1018             : */
    1019             : void
    1020             : fd_begin_partitioned_rewards(
    1021             :     fd_exec_slot_ctx_t * slot_ctx,
    1022             :     const fd_hash_t *    parent_blockhash,
    1023             :     ulong                parent_epoch,
    1024             :     fd_epoch_info_t    * temp_info
    1025           0 : ) {
    1026           0 :   FD_SCRATCH_SCOPE_BEGIN {
    1027             :     /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L55 */
    1028           0 :     fd_calculate_rewards_and_distribute_vote_rewards_result_t rewards_result[1] = {0};
    1029           0 :     calculate_rewards_and_distribute_vote_rewards(
    1030           0 :         slot_ctx,
    1031           0 :         parent_epoch,
    1032           0 :         parent_blockhash,
    1033           0 :         rewards_result,
    1034           0 :         temp_info
    1035           0 :     );
    1036             : 
    1037             :     /* https://github.com/anza-xyz/agave/blob/9a7bf72940f4b3cd7fc94f54e005868ce707d53d/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L62 */
    1038           0 :     ulong distribution_starting_block_height = slot_ctx->slot_bank.block_height + REWARD_CALCULATION_NUM_BLOCKS;
    1039             : 
    1040             :     /* Set the epoch reward status to be active */
    1041           0 :     set_epoch_reward_status_active( slot_ctx, distribution_starting_block_height, &rewards_result->stake_rewards_by_partition.partitioned_stake_rewards );
    1042             : 
    1043             :     /* Initialise the epoch rewards sysvar
    1044             : 
    1045             :         https://github.com/anza-xyz/agave/blob/9a7bf72940f4b3cd7fc94f54e005868ce707d53d/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L78 */
    1046           0 :     fd_sysvar_epoch_rewards_init(
    1047           0 :         slot_ctx,
    1048           0 :         rewards_result->total_rewards,
    1049           0 :         rewards_result->distributed_rewards,
    1050           0 :         distribution_starting_block_height,
    1051           0 :         rewards_result->stake_rewards_by_partition.partitioned_stake_rewards.partitions_len,
    1052           0 :         rewards_result->point_value,
    1053           0 :         parent_blockhash
    1054           0 :      );
    1055           0 :   } FD_SCRATCH_SCOPE_END;
    1056           0 : }
    1057             : 
    1058             : /*
    1059             :     Re-calculates partitioned stake rewards.
    1060             :     This updates the slot context's epoch reward status with the recalculated partitioned rewards.
    1061             : 
    1062             :     https://github.com/anza-xyz/agave/blob/2316fea4c0852e59c071f72d72db020017ffd7d0/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L536 */
    1063             : void
    1064             : fd_rewards_recalculate_partitioned_rewards(
    1065             :     fd_exec_slot_ctx_t * slot_ctx
    1066           0 : ) {
    1067           0 :     fd_sysvar_epoch_rewards_t epoch_rewards[1];
    1068           0 :     if ( FD_UNLIKELY( fd_sysvar_epoch_rewards_read( epoch_rewards, slot_ctx ) == NULL ) ) {
    1069           0 :       FD_LOG_NOTICE(( "failed to read sysvar epoch rewards - the sysvar may not have been created yet" ));
    1070           0 :       set_epoch_reward_status_inactive( slot_ctx );
    1071           0 :       return;
    1072           0 :     }
    1073             : 
    1074           0 :     if ( FD_UNLIKELY( epoch_rewards->active ) ) {
    1075             :         /* If partitioned rewards are active, the rewarded epoch is always the immediately
    1076             :            preceeding epoch.
    1077             : 
    1078             :            https://github.com/anza-xyz/agave/blob/2316fea4c0852e59c071f72d72db020017ffd7d0/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L566 */
    1079           0 :         fd_epoch_schedule_t * epoch_schedule = &fd_exec_epoch_ctx_epoch_bank( slot_ctx->epoch_ctx )->epoch_schedule;
    1080           0 :         ulong epoch = fd_slot_to_epoch( epoch_schedule, slot_ctx->slot_bank.slot, NULL );
    1081           0 :         ulong rewarded_epoch = fd_ulong_sat_sub( epoch, 1UL );
    1082             : 
    1083           0 :         fd_stake_history_t const * stake_history = fd_sysvar_cache_stake_history( slot_ctx->sysvar_cache );
    1084           0 :         if( FD_UNLIKELY( !stake_history ) ) {
    1085           0 :             FD_LOG_ERR(( "StakeHistory sysvar is missing from sysvar cache" ));
    1086           0 :         }
    1087             : 
    1088           0 :         fd_point_value_t point_value = {
    1089           0 :             .points = epoch_rewards->total_points,
    1090           0 :             .rewards = epoch_rewards->total_rewards
    1091           0 :         };
    1092             : 
    1093             :         /* In future, the calculation will be cached in the snapshot, but for now we just re-calculate it
    1094             :            (as Agave does). */
    1095           0 :         fd_calculate_stake_vote_rewards_result_t calculate_stake_vote_rewards_result[1];
    1096           0 :         calculate_stake_vote_rewards(
    1097           0 :             slot_ctx,
    1098           0 :             stake_history,
    1099           0 :             rewarded_epoch,
    1100           0 :             &point_value,
    1101           0 :             calculate_stake_vote_rewards_result
    1102           0 :         );
    1103             : 
    1104             :         /* Free the vote reward map, as this isn't actually used in this code path. */
    1105           0 :         fd_valloc_free( slot_ctx->valloc,
    1106           0 :             fd_vote_reward_t_map_delete(
    1107           0 :                 fd_vote_reward_t_map_leave( calculate_stake_vote_rewards_result->vote_reward_map_pool ) ) );
    1108             : 
    1109           0 :         fd_stake_reward_calculation_partitioned_t stake_rewards_by_partition[1];
    1110           0 :         hash_rewards_into_partitions(
    1111           0 :             slot_ctx,
    1112           0 :             &calculate_stake_vote_rewards_result->stake_reward_calculation,
    1113           0 :             &epoch_rewards->parent_blockhash,
    1114           0 :             stake_rewards_by_partition );
    1115             : 
    1116             :         /* Update the epoch reward status with the newly re-calculated partitions. */
    1117           0 :         set_epoch_reward_status_active(
    1118           0 :             slot_ctx,
    1119           0 :             epoch_rewards->distribution_starting_block_height,
    1120           0 :             &stake_rewards_by_partition->partitioned_stake_rewards );
    1121           0 :     } else {
    1122           0 :         set_epoch_reward_status_inactive( slot_ctx );
    1123           0 :     }
    1124             : 
    1125           0 : }

Generated by: LCOV version 1.14