LCOV - code coverage report
Current view: top level - flamenco/rewards - fd_rewards.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 0 796 0.0 %
Date: 2025-07-14 05:02:59 Functions: 0 32 0.0 %

          Line data    Source code
       1             : #include "fd_rewards.h"
       2             : #include <math.h>
       3             : 
       4             : #include "../../ballet/siphash13/fd_siphash13.h"
       5             : #include "../runtime/fd_executor_err.h"
       6             : #include "../runtime/fd_system_ids.h"
       7             : #include "../runtime/fd_runtime.h"
       8             : #include "../runtime/context/fd_exec_slot_ctx.h"
       9             : #include "../runtime/program/fd_program_util.h"
      10             : #include "../runtime/sysvar/fd_sysvar_stake_history.h"
      11             : 
      12             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/sdk/program/src/native_token.rs#L6 */
      13           0 : #define LAMPORTS_PER_SOL                     (1000000000UL)
      14             : 
      15             : /* Number of blocks for reward calculation and storing vote accounts.
      16             :    Distributing rewards to stake accounts begins AFTER this many blocks.
      17             : 
      18             :    https://github.com/anza-xyz/agave/blob/9a7bf72940f4b3cd7fc94f54e005868ce707d53d/runtime/src/bank/partitioned_epoch_rewards/mod.rs#L27 */
      19           0 : #define REWARD_CALCULATION_NUM_BLOCKS        (1UL)
      20             : 
      21             : /* 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. */
      22           0 : #define STAKE_ACCOUNT_STORES_PER_BLOCK       (4096UL)
      23             : 
      24             : /* https://github.com/anza-xyz/agave/blob/2316fea4c0852e59c071f72d72db020017ffd7d0/runtime/src/bank/partitioned_epoch_rewards/mod.rs#L219 */
      25           0 : #define MAX_FACTOR_OF_REWARD_BLOCKS_IN_EPOCH (10UL)
      26             : 
      27             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/sdk/src/inflation.rs#L85 */
      28             : static double
      29           0 : total( fd_inflation_t const * inflation, double year ) {
      30           0 :   if ( FD_UNLIKELY( year == 0.0 ) ) {
      31           0 :     FD_LOG_ERR(( "inflation year 0" ));
      32           0 :   }
      33           0 :   double tapered = inflation->initial * pow( (1.0 - inflation->taper), year );
      34           0 :   return (tapered > inflation->terminal) ? tapered : inflation->terminal;
      35           0 : }
      36             : 
      37             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/sdk/src/inflation.rs#L102 */
      38             : static double
      39           0 : foundation( fd_inflation_t const * inflation, double year ) {
      40           0 :   return (year < inflation->foundation_term) ? inflation->foundation * total(inflation, year) : 0.0;
      41           0 : }
      42             : 
      43             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/sdk/src/inflation.rs#L97 */
      44             : static double
      45           0 : validator( fd_inflation_t const * inflation, double year) {
      46             :   /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/sdk/src/inflation.rs#L96-L99 */
      47           0 :   FD_LOG_DEBUG(("Validator Rate: %.16f %.16f %.16f %.16f %.16f", year, total( inflation, year ), foundation( inflation, year ), inflation->taper, inflation->initial));
      48           0 :   return total( inflation, year ) - foundation( inflation, year );
      49           0 : }
      50             : 
      51             : /* Calculates the starting slot for inflation from the activation slot. The activation slot is the earliest
      52             :     activation slot of the following features:
      53             :     - devnet_and_testnet
      54             :     - full_inflation_enable, if full_inflation_vote has been activated
      55             : 
      56             :     https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank.rs#L2095 */
      57             : static FD_FN_CONST ulong
      58           0 : get_inflation_start_slot( fd_exec_slot_ctx_t * slot_ctx ) {
      59           0 :     ulong devnet_and_testnet = FD_FEATURE_ACTIVE_BANK( slot_ctx->bank, devnet_and_testnet ) ? fd_bank_features_query( slot_ctx->bank )->devnet_and_testnet : ULONG_MAX;
      60             : 
      61           0 :     ulong enable = ULONG_MAX;
      62           0 :     if( FD_FEATURE_ACTIVE_BANK( slot_ctx->bank, full_inflation_vote ) &&
      63           0 :         FD_FEATURE_ACTIVE_BANK( slot_ctx->bank, full_inflation_enable ) ) {
      64           0 :       enable = fd_bank_features_query( slot_ctx->bank )->full_inflation_enable;
      65           0 :     }
      66             : 
      67           0 :     ulong min_slot = fd_ulong_min( enable, devnet_and_testnet );
      68           0 :     if( min_slot == ULONG_MAX ) {
      69           0 :       if( FD_FEATURE_ACTIVE_BANK( slot_ctx->bank, pico_inflation ) ) {
      70           0 :         min_slot = fd_bank_features_query( slot_ctx->bank )->pico_inflation;
      71           0 :       } else {
      72           0 :         min_slot = 0;
      73           0 :       }
      74           0 :     }
      75           0 :     return min_slot;
      76           0 : }
      77             : 
      78             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank.rs#L2110 */
      79             : static ulong
      80             : get_inflation_num_slots( fd_exec_slot_ctx_t * slot_ctx,
      81             :                          fd_epoch_schedule_t const * epoch_schedule,
      82           0 :                          ulong slot ) {
      83           0 :   ulong inflation_activation_slot = get_inflation_start_slot( slot_ctx );
      84           0 :   ulong inflation_start_slot      = fd_epoch_slot0( epoch_schedule,
      85           0 :                                                     fd_ulong_sat_sub( fd_slot_to_epoch( epoch_schedule,
      86           0 :                                                                                         inflation_activation_slot, NULL ),
      87           0 :                                                                       1UL ) );
      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_schedule_t const * epoch_schedule = fd_bank_epoch_schedule_query( slot_ctx->bank );
      98             : 
      99           0 :   ulong num_slots = get_inflation_num_slots( slot_ctx, epoch_schedule, fd_bank_slot_get( slot_ctx->bank ) );
     100           0 :   return (double)num_slots / (double)fd_bank_slots_per_year_get( slot_ctx->bank );
     101           0 : }
     102             : 
     103             : /* For a given stake and vote_state, calculate how many points were earned (credits * stake) and new value
     104             :    for credits_observed were the points paid
     105             : 
     106             :     https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/points.rs#L109 */
     107             : static void
     108             : calculate_stake_points_and_credits( fd_stake_history_t const *     stake_history,
     109             :                                     fd_stake_t const *             stake,
     110             :                                     fd_vote_state_versioned_t *    vote_state_versioned,
     111             :                                     ulong *                        new_rate_activation_epoch,
     112           0 :                                     fd_calculated_stake_points_t * result ) {
     113             : 
     114           0 :   ulong credits_in_stake = stake->credits_observed;
     115             : 
     116           0 :   fd_vote_epoch_credits_t * epoch_credits;
     117           0 :   switch( vote_state_versioned->discriminant ) {
     118           0 :     case fd_vote_state_versioned_enum_current:
     119           0 :       epoch_credits = vote_state_versioned->inner.current.epoch_credits;
     120           0 :       break;
     121           0 :     case fd_vote_state_versioned_enum_v0_23_5:
     122           0 :       epoch_credits = vote_state_versioned->inner.v0_23_5.epoch_credits;
     123           0 :       break;
     124           0 :     case fd_vote_state_versioned_enum_v1_14_11:
     125           0 :       epoch_credits = vote_state_versioned->inner.v1_14_11.epoch_credits;
     126           0 :       break;
     127           0 :     default:
     128           0 :       FD_LOG_ERR(( "invalid vote account, should never happen" ));
     129           0 :   }
     130             : 
     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( fd_stake_history_t const *      stake_history,
     190             :                          fd_stake_t const *              stake,
     191             :                          fd_vote_state_versioned_t *     vote_state_versioned,
     192             :                          ulong                           rewarded_epoch,
     193             :                          fd_point_value_t *              point_value,
     194             :                          ulong *                         new_rate_activation_epoch,
     195           0 :                          fd_calculated_stake_rewards_t * result ) {
     196           0 :   fd_calculated_stake_points_t stake_points_result = {0};
     197           0 :   calculate_stake_points_and_credits( stake_history, stake, vote_state_versioned, new_rate_activation_epoch, &stake_points_result);
     198             : 
     199             :   // Drive credits_observed forward unconditionally when rewards are disabled
     200             :   // or when this is the stake's activation epoch
     201           0 :   if( ( point_value->rewards==0UL ) ||
     202           0 :       ( stake->delegation.activation_epoch==rewarded_epoch ) ) {
     203           0 :       stake_points_result.force_credits_update_with_skipped_reward |= 1;
     204           0 :   }
     205             : 
     206           0 :   if( stake_points_result.force_credits_update_with_skipped_reward ) {
     207           0 :     result->staker_rewards = 0;
     208           0 :     result->voter_rewards = 0;
     209           0 :     result->new_credits_observed = stake_points_result.new_credits_observed;
     210           0 :     return 0;
     211           0 :   }
     212           0 :   if( stake_points_result.points == 0 || point_value->points == 0 ) {
     213           0 :     return 1;
     214           0 :   }
     215             : 
     216             :   /* FIXME: need to error out if the conversion from uint128 to u64 fails, also use 128 checked mul and div */
     217           0 :   ulong rewards = (ulong)(stake_points_result.points * (uint128)(point_value->rewards) / (uint128) point_value->points);
     218           0 :   if( rewards == 0 ) {
     219           0 :     return 1;
     220           0 :   }
     221             : 
     222           0 :   fd_commission_split_t split_result;
     223           0 :   fd_vote_commission_split( vote_state_versioned, rewards, &split_result );
     224           0 :   if( split_result.is_split && (split_result.voter_portion == 0 || split_result.staker_portion == 0) ) {
     225           0 :     return 1;
     226           0 :   }
     227             : 
     228           0 :   result->staker_rewards = split_result.staker_portion;
     229           0 :   result->voter_rewards = split_result.voter_portion;
     230           0 :   result->new_credits_observed = stake_points_result.new_credits_observed;
     231           0 :   return 0;
     232           0 : }
     233             : 
     234             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/rewards.rs#L33 */
     235             : static int
     236             : redeem_rewards( fd_stake_history_t const *      stake_history,
     237             :                 fd_stake_t const *              stake,
     238             :                 fd_vote_state_versioned_t *     vote_state_versioned,
     239             :                 ulong                           rewarded_epoch,
     240             :                 fd_point_value_t *              point_value,
     241             :                 ulong *                         new_rate_activation_epoch,
     242           0 :                 fd_calculated_stake_rewards_t * calculated_stake_rewards) {
     243             : 
     244           0 :   int rc = calculate_stake_rewards( stake_history, stake, vote_state_versioned, rewarded_epoch, point_value, new_rate_activation_epoch, calculated_stake_rewards );
     245           0 :   if( FD_UNLIKELY( rc!=0 ) ) {
     246           0 :     return rc;
     247           0 :   }
     248             : 
     249           0 :   return FD_EXECUTOR_INSTR_SUCCESS;
     250           0 : }
     251             : 
     252             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/points.rs#L70 */
     253             : static int
     254             : calculate_points( fd_stake_t const *          stake,
     255             :                   fd_vote_state_versioned_t * vote_state_versioned,
     256             :                   fd_stake_history_t const  * stake_history,
     257             :                   ulong *                     new_rate_activation_epoch,
     258           0 :                   uint128 *                   result ) {
     259           0 :   fd_calculated_stake_points_t stake_point_result;
     260           0 :   calculate_stake_points_and_credits( stake_history, stake, vote_state_versioned, new_rate_activation_epoch, &stake_point_result );
     261           0 :   *result = stake_point_result.points;
     262             : 
     263           0 :   return FD_EXECUTOR_INSTR_SUCCESS;
     264           0 : }
     265             : 
     266             : /* Returns the length of the given epoch in slots
     267             : 
     268             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/sdk/program/src/epoch_schedule.rs#L103 */
     269             : static ulong
     270             : get_slots_in_epoch( ulong                       epoch,
     271           0 :                     fd_epoch_schedule_t const * epoch_schedule ) {
     272           0 :   return (epoch < epoch_schedule->first_normal_epoch) ?
     273           0 :           1UL << fd_ulong_sat_add(epoch, FD_EPOCH_LEN_MIN_TRAILING_ZERO) :
     274           0 :           epoch_schedule->slots_per_epoch;
     275           0 : }
     276             : 
     277             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank.rs#L2082 */
     278             : static double
     279             : epoch_duration_in_years( fd_exec_slot_ctx_t *    slot_ctx,
     280           0 :                          ulong                   prev_epoch ) {
     281           0 :   ulong slots_in_epoch = get_slots_in_epoch( prev_epoch, fd_bank_epoch_schedule_query( slot_ctx->bank ) );
     282           0 :   return (double)slots_in_epoch / (double)fd_bank_slots_per_year_get( slot_ctx->bank );
     283           0 : }
     284             : 
     285             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank.rs#L2128 */
     286             : static void
     287             : calculate_previous_epoch_inflation_rewards( fd_exec_slot_ctx_t *                slot_ctx,
     288             :                                             ulong                               prev_epoch_capitalization,
     289             :                                             ulong                               prev_epoch,
     290           0 :                                             fd_prev_epoch_inflation_rewards_t * rewards ) {
     291           0 :     double slot_in_year = slot_in_year_for_inflation( slot_ctx );
     292             : 
     293           0 :     rewards->validator_rate               = validator( fd_bank_inflation_query( slot_ctx->bank ), slot_in_year );
     294           0 :     rewards->foundation_rate              = foundation( fd_bank_inflation_query( slot_ctx->bank ), slot_in_year );
     295           0 :     rewards->prev_epoch_duration_in_years = epoch_duration_in_years( slot_ctx, prev_epoch );
     296           0 :     rewards->validator_rewards            = (ulong)(rewards->validator_rate * (double)prev_epoch_capitalization * rewards->prev_epoch_duration_in_years);
     297           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 ));
     298           0 : }
     299             : 
     300             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/lib.rs#L29 */
     301             : static ulong
     302           0 : get_minimum_stake_delegation( fd_exec_slot_ctx_t * slot_ctx ) {
     303           0 :   if( !FD_FEATURE_ACTIVE_BANK( slot_ctx->bank, stake_minimum_delegation_for_rewards ) ) {
     304           0 :     return 0UL;
     305           0 :   }
     306             : 
     307           0 :   if( FD_FEATURE_ACTIVE_BANK( slot_ctx->bank, stake_raise_minimum_delegation_to_1_sol ) ) {
     308           0 :     return LAMPORTS_PER_SOL;
     309           0 :   }
     310             : 
     311           0 :   return 1;
     312           0 : }
     313             : 
     314             : static void
     315             : calculate_points_range( fd_epoch_info_pair_t const *      stake_infos,
     316             :                         fd_calculate_points_task_args_t * task_args,
     317             :                         ulong                             start_idx,
     318           0 :                         ulong                             end_idx ) {
     319             : 
     320           0 :   fd_stake_history_t const *        stake_history                  = task_args->stake_history;
     321           0 :   ulong *                           new_warmup_cooldown_rate_epoch = task_args->new_warmup_cooldown_rate_epoch;
     322           0 :   ulong                             minimum_stake_delegation       = task_args->minimum_stake_delegation;
     323             : 
     324           0 :   uint128 total_points = 0;
     325           0 :   for( ulong i=start_idx; i<end_idx; i++ ) {
     326           0 :     fd_epoch_info_pair_t const * stake_info = stake_infos + i;
     327           0 :     fd_stake_t const *           stake      = &stake_info->stake;
     328             : 
     329           0 :     if( FD_UNLIKELY( stake->delegation.stake<minimum_stake_delegation ) ) {
     330           0 :       continue;
     331           0 :     }
     332             : 
     333             :     /* Check that the vote account is present in our cache */
     334           0 :     fd_vote_info_pair_t_mapnode_t query_key;
     335           0 :     query_key.elem.account = stake->delegation.voter_pubkey;
     336           0 :     fd_vote_info_pair_t_mapnode_t * vote_state_info = fd_vote_info_pair_t_map_find( task_args->vote_states_pool, task_args->vote_states_root, &query_key );
     337           0 :     if( FD_UNLIKELY( vote_state_info==NULL ) ) {
     338           0 :       FD_LOG_DEBUG(( "vote account missing from cache" ));
     339           0 :       continue;
     340           0 :     }
     341             : 
     342           0 :     uint128 account_points;
     343           0 :     int err = calculate_points( stake, &vote_state_info->elem.state, stake_history, new_warmup_cooldown_rate_epoch, &account_points );
     344           0 :     if( FD_UNLIKELY( err ) ) {
     345           0 :       FD_LOG_DEBUG(( "failed to calculate points" ));
     346           0 :       continue;
     347           0 :     }
     348             : 
     349           0 :     total_points += account_points;
     350           0 :   }
     351             : 
     352           0 :   FD_ATOMIC_FETCH_AND_ADD( task_args->total_points, total_points );
     353             : 
     354             : 
     355           0 : }
     356             : 
     357             : static void
     358             : calculate_points_tpool_task( void  *tpool,
     359             :                              ulong t0 FD_PARAM_UNUSED,      ulong t1 FD_PARAM_UNUSED,
     360             :                              void  *args,
     361             :                              void  *reduce FD_PARAM_UNUSED, ulong stride FD_PARAM_UNUSED,
     362             :                              ulong l0 FD_PARAM_UNUSED,      ulong l1 FD_PARAM_UNUSED,
     363             :                              ulong m0,                      ulong m1,
     364           0 :                              ulong n0 FD_PARAM_UNUSED,      ulong n1 FD_PARAM_UNUSED ) {
     365           0 :   fd_epoch_info_pair_t const *      stake_infos                    = ((fd_epoch_info_pair_t const *)tpool);
     366           0 :   fd_calculate_points_task_args_t * task_args                      = (fd_calculate_points_task_args_t *)args;
     367             : 
     368           0 :   calculate_points_range( stake_infos, task_args, m0, m1 );
     369           0 : }
     370             : 
     371             : /* Calculates epoch reward points from stake/vote accounts.
     372             : 
     373             :     https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L472 */
     374             : static void
     375             : calculate_reward_points_partitioned( fd_exec_slot_ctx_t *       slot_ctx,
     376             :                                      fd_stake_history_t const * stake_history,
     377             :                                      ulong                      rewards,
     378             :                                      fd_point_value_t *         result,
     379             :                                      fd_tpool_t *               tpool,
     380             :                                      fd_epoch_info_t *          temp_info,
     381           0 :                                      fd_spad_t *                runtime_spad ) {
     382             : 
     383           0 :   uint128 points = 0;
     384           0 :   ulong minimum_stake_delegation = get_minimum_stake_delegation( slot_ctx );
     385             : 
     386             :   /* Calculate the points for each stake delegation */
     387           0 :   int _err[1];
     388           0 :   ulong   new_warmup_cooldown_rate_epoch_val = 0UL;
     389           0 :   ulong * new_warmup_cooldown_rate_epoch     = &new_warmup_cooldown_rate_epoch_val;
     390           0 :   int is_some = fd_new_warmup_cooldown_rate_epoch(
     391           0 :       fd_bank_slot_get( slot_ctx->bank ),
     392           0 :       slot_ctx->funk,
     393           0 :       slot_ctx->funk_txn,
     394           0 :       runtime_spad,
     395           0 :       fd_bank_features_query( slot_ctx->bank ),
     396           0 :       new_warmup_cooldown_rate_epoch,
     397           0 :       _err );
     398           0 :   if( FD_UNLIKELY( !is_some ) ) {
     399           0 :     new_warmup_cooldown_rate_epoch = NULL;
     400           0 :   }
     401             : 
     402           0 :   fd_calculate_points_task_args_t task_args = {
     403           0 :     .stake_history                  = stake_history,
     404           0 :     .new_warmup_cooldown_rate_epoch = new_warmup_cooldown_rate_epoch,
     405           0 :     .minimum_stake_delegation       = minimum_stake_delegation,
     406           0 :     .vote_states_pool               = temp_info->vote_states_pool,
     407           0 :     .vote_states_root               = temp_info->vote_states_root,
     408           0 :     .total_points                   = &points,
     409           0 :   };
     410             : 
     411           0 :   if( !!tpool ) {
     412           0 :     fd_tpool_exec_all_batch( tpool, 0UL, fd_tpool_worker_cnt( tpool ), calculate_points_tpool_task,
     413           0 :                              temp_info->stake_infos, &task_args, NULL,
     414           0 :                              1UL, 0UL, temp_info->stake_infos_len );
     415           0 :   } else {
     416           0 :     calculate_points_range( temp_info->stake_infos, &task_args, 0UL, temp_info->stake_infos_len );
     417           0 :   }
     418             : 
     419           0 :   if( points > 0 ) {
     420           0 :     result->points  = points;
     421           0 :     result->rewards = rewards;
     422           0 :   }
     423           0 : }
     424             : 
     425             : static void
     426             : calculate_stake_vote_rewards_account( fd_epoch_info_t const *                             temp_info,
     427             :                                       fd_calculate_stake_vote_rewards_task_args_t const * task_args,
     428             :                                       ulong                                               start_idx,
     429           0 :                                       ulong                                               end_idx ) {
     430             : 
     431           0 :   fd_epoch_info_pair_t const *                        stake_infos                    = temp_info->stake_infos;
     432           0 :   fd_exec_slot_ctx_t *                                slot_ctx                       = task_args->slot_ctx;
     433           0 :   fd_stake_history_t const *                          stake_history                  = task_args->stake_history;
     434           0 :   ulong                                               rewarded_epoch                 = task_args->rewarded_epoch;
     435           0 :   ulong *                                             new_warmup_cooldown_rate_epoch = task_args->new_warmup_cooldown_rate_epoch;
     436           0 :   fd_point_value_t *                                  point_value                    = task_args->point_value;
     437           0 :   fd_calculate_stake_vote_rewards_result_t *          result                         = task_args->result; // written to
     438           0 :   fd_spad_t *                                         spad                           = task_args->exec_spads[ fd_tile_idx() ];
     439             : 
     440           0 :   FD_SPAD_FRAME_BEGIN( spad ) {
     441             : 
     442           0 :   ulong minimum_stake_delegation = get_minimum_stake_delegation( slot_ctx );
     443           0 :   ulong total_stake_rewards      = 0UL;
     444           0 :   ulong dlist_additional_cnt     = 0UL;
     445             : 
     446             :   /* Build a local vote reward map */
     447           0 :   fd_vote_reward_t_mapnode_t * vote_reward_map_pool = fd_vote_reward_t_map_join( fd_vote_reward_t_map_new( fd_spad_alloc( spad,
     448           0 :                                                                                                                           fd_vote_reward_t_map_align(),
     449           0 :                                                                                                                           fd_vote_reward_t_map_footprint( end_idx-start_idx )),
     450           0 :                                                                                   end_idx-start_idx ) );
     451           0 :   fd_vote_reward_t_mapnode_t * vote_reward_map_root = NULL;
     452             : 
     453           0 :   for( ulong i=start_idx; i<end_idx; i++ ) {
     454           0 :     fd_epoch_info_pair_t const * stake_info = stake_infos + i;
     455           0 :     fd_pubkey_t const *          stake_acc  = &stake_info->account;
     456           0 :     fd_stake_t const *           stake      = &stake_info->stake;
     457             : 
     458           0 :     if( FD_FEATURE_ACTIVE_BANK( slot_ctx->bank, stake_minimum_delegation_for_rewards ) ) {
     459           0 :       if( stake->delegation.stake<minimum_stake_delegation ) {
     460           0 :         continue;
     461           0 :       }
     462           0 :     }
     463             : 
     464           0 :     fd_pubkey_t const * voter_acc = &stake->delegation.voter_pubkey;
     465           0 :     fd_vote_info_pair_t_mapnode_t key;
     466           0 :     key.elem.account = *voter_acc;
     467           0 :     fd_vote_info_pair_t_mapnode_t * vote_state_entry = fd_vote_info_pair_t_map_find( temp_info->vote_states_pool,
     468           0 :                                                                                       temp_info->vote_states_root,
     469           0 :                                                                                       &key );
     470           0 :     if( FD_UNLIKELY( vote_state_entry==NULL ) ) {
     471           0 :       continue;
     472           0 :     }
     473             : 
     474           0 :     fd_vote_state_versioned_t * vote_state = &vote_state_entry->elem.state;
     475             : 
     476             :     /* Note, this doesn't actually redeem any rewards.. this is a misnomer. */
     477           0 :     fd_calculated_stake_rewards_t calculated_stake_rewards[1] = {0};
     478           0 :     int err = redeem_rewards( stake_history,
     479           0 :                               stake,
     480           0 :                               vote_state,
     481           0 :                               rewarded_epoch,
     482           0 :                               point_value,
     483           0 :                               new_warmup_cooldown_rate_epoch,
     484           0 :                               calculated_stake_rewards );
     485           0 :     if( FD_UNLIKELY( 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 :       continue;
     488           0 :     }
     489             : 
     490             :     /* Fetch the comission for the vote account */
     491           0 :     uchar commission = 0;
     492           0 :     switch( vote_state->discriminant ) {
     493           0 :       case fd_vote_state_versioned_enum_current:
     494           0 :         commission = vote_state->inner.current.commission;
     495           0 :         break;
     496           0 :       case fd_vote_state_versioned_enum_v0_23_5:
     497           0 :         commission = vote_state->inner.v0_23_5.commission;
     498           0 :         break;
     499           0 :       case fd_vote_state_versioned_enum_v1_14_11:
     500           0 :         commission = vote_state->inner.v1_14_11.commission;
     501           0 :         break;
     502           0 :       default:
     503           0 :         FD_LOG_DEBUG(( "unsupported vote account" ));
     504           0 :         continue;
     505           0 :     }
     506             : 
     507             :     // Find and update the vote reward node in the local map
     508           0 :     fd_vote_reward_t_mapnode_t vote_map_key[1];
     509           0 :     vote_map_key->elem.pubkey = *voter_acc;
     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( FD_UNLIKELY( vote_reward_node==NULL ) ) {
     512           0 :       FD_LOG_WARNING(( "vote account is missing from the vote rewards pool" ));
     513           0 :       continue;
     514           0 :     }
     515             : 
     516           0 :     vote_reward_node = fd_vote_reward_t_map_find( vote_reward_map_pool, vote_reward_map_root, vote_map_key );
     517             : 
     518           0 :     if( vote_reward_node==NULL ) {
     519           0 :       vote_reward_node                    = fd_vote_reward_t_map_acquire( vote_reward_map_pool );
     520           0 :       vote_reward_node->elem.pubkey       = *voter_acc;
     521           0 :       vote_reward_node->elem.commission   = commission;
     522           0 :       vote_reward_node->elem.vote_rewards = calculated_stake_rewards->voter_rewards;
     523           0 :       vote_reward_node->elem.needs_store  = 1;
     524           0 :       fd_vote_reward_t_map_insert( vote_reward_map_pool, &vote_reward_map_root, vote_reward_node );
     525           0 :     } else {
     526           0 :       vote_reward_node->elem.vote_rewards += calculated_stake_rewards->voter_rewards;
     527           0 :     }
     528             : 
     529             :     /* Add the stake reward to list of all stake rewards. The update is thread-safe because each index in the dlist
     530             :       is only ever accessed / written to once among all threads. */
     531           0 :     fd_stake_reward_t * stake_reward = fd_stake_reward_calculation_pool_ele( result->stake_reward_calculation.pool, i );
     532           0 :     if( FD_UNLIKELY( stake_reward==NULL ) ) {
     533           0 :       FD_LOG_WARNING(( "could not find stake reward node in pool" ));
     534           0 :       continue;
     535           0 :     }
     536             : 
     537           0 :     fd_memcpy( stake_reward->stake_pubkey.uc, stake_acc, sizeof(fd_pubkey_t) );
     538           0 :     stake_reward->lamports         = calculated_stake_rewards->staker_rewards;
     539           0 :     stake_reward->credits_observed = calculated_stake_rewards->new_credits_observed;
     540           0 :     stake_reward->valid            = 1;
     541             : 
     542             :     /* Update the total stake rewards */
     543           0 :     total_stake_rewards += calculated_stake_rewards->staker_rewards;
     544           0 :     dlist_additional_cnt++;
     545           0 :   }
     546             : 
     547             :   /* Merge vote rewards with result after */
     548           0 :   for( fd_vote_reward_t_mapnode_t * vote_reward_node = fd_vote_reward_t_map_minimum( vote_reward_map_pool, vote_reward_map_root );
     549           0 :         vote_reward_node;
     550           0 :         vote_reward_node = fd_vote_reward_t_map_successor( vote_reward_map_pool, vote_reward_node ) ) {
     551             : 
     552           0 :     fd_vote_reward_t_mapnode_t * result_reward_node = fd_vote_reward_t_map_find( result->vote_reward_map_pool, result->vote_reward_map_root, vote_reward_node );
     553           0 :     FD_ATOMIC_CAS( &result_reward_node->elem.commission, 0, vote_reward_node->elem.commission );
     554           0 :     FD_ATOMIC_FETCH_AND_ADD( &result_reward_node->elem.vote_rewards, vote_reward_node->elem.vote_rewards );
     555           0 :     FD_ATOMIC_CAS( &result_reward_node->elem.needs_store, 0, 1 );
     556           0 :   }
     557             : 
     558           0 :   FD_ATOMIC_FETCH_AND_ADD( &result->stake_reward_calculation.total_stake_rewards_lamports, total_stake_rewards );
     559           0 :   FD_ATOMIC_FETCH_AND_ADD( &result->stake_reward_calculation.stake_rewards_len, dlist_additional_cnt );
     560             : 
     561           0 :   } FD_SPAD_FRAME_END;
     562             : 
     563             : 
     564           0 : }
     565             : 
     566             : /* Calculate the partitioned stake rewards for a single stake/vote account pair, updates result with these. */
     567             : static void
     568             : calculate_stake_vote_rewards_account_tpool_task( void  *tpool,
     569             :                                                  ulong t0 FD_PARAM_UNUSED,      ulong t1 FD_PARAM_UNUSED,
     570             :                                                  void  *args,
     571             :                                                  void  *reduce FD_PARAM_UNUSED, ulong stride FD_PARAM_UNUSED,
     572             :                                                  ulong l0 FD_PARAM_UNUSED,      ulong l1 FD_PARAM_UNUSED,
     573             :                                                  ulong m0,                      ulong m1,
     574           0 :                                                  ulong n0 FD_PARAM_UNUSED,      ulong n1 FD_PARAM_UNUSED ) {
     575             : 
     576           0 :   fd_epoch_info_t const *                             temp_info                      = ((fd_epoch_info_t const *)tpool);
     577           0 :   fd_calculate_stake_vote_rewards_task_args_t const * task_args                      = (fd_calculate_stake_vote_rewards_task_args_t const *)args;
     578           0 :   calculate_stake_vote_rewards_account( temp_info, task_args, m0, m1 );
     579           0 : }
     580             : 
     581             : /* Calculates epoch rewards for stake/vote accounts.
     582             :    Returns vote rewards, stake rewards, and the sum of all stake rewards in lamports.
     583             : 
     584             :    This uses a pool to allocate the stake rewards, which means that we can use dlists to
     585             :    distribute these into partitions of variable size without copying them or over-allocating
     586             :    the partitions.
     587             :    - We use a single dlist to put all the stake rewards during the calculation phase.
     588             :    - We then distribute these into partitions (whose size cannot be known in advance), where each
     589             :      partition is a separate dlist.
     590             :    - The dlist elements are all backed by the same pool, and allocated once.
     591             :    This approach optimizes memory usage and reduces copying.
     592             : 
     593             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L334 */
     594             : static void
     595             : calculate_stake_vote_rewards( fd_exec_slot_ctx_t *                       slot_ctx,
     596             :                               fd_stake_history_t const *                 stake_history,
     597             :                               ulong                                      rewarded_epoch,
     598             :                               fd_point_value_t *                         point_value,
     599             :                               fd_calculate_stake_vote_rewards_result_t * result,
     600             :                               fd_epoch_info_t *                          temp_info,
     601             :                               fd_tpool_t *                               tpool,
     602             :                               fd_spad_t * *                              exec_spads,
     603             :                               ulong                                      exec_spad_cnt,
     604           0 :                               fd_spad_t *                                runtime_spad ) {
     605             : 
     606           0 :   int _err[1];
     607           0 :   ulong   new_warmup_cooldown_rate_epoch_val = 0UL;
     608           0 :   ulong * new_warmup_cooldown_rate_epoch     = &new_warmup_cooldown_rate_epoch_val;
     609           0 :   int is_some = fd_new_warmup_cooldown_rate_epoch(
     610           0 :       fd_bank_slot_get( slot_ctx->bank ),
     611           0 :       slot_ctx->funk,
     612           0 :       slot_ctx->funk_txn,
     613           0 :       runtime_spad,
     614           0 :       fd_bank_features_query( slot_ctx->bank ),
     615           0 :       new_warmup_cooldown_rate_epoch,
     616           0 :       _err );
     617           0 :   if( FD_UNLIKELY( !is_some ) ) {
     618           0 :     new_warmup_cooldown_rate_epoch = NULL;
     619           0 :   }
     620             : 
     621           0 :   ulong rewards_max_count = temp_info->stake_infos_len;
     622             : 
     623             :   /* Create the stake rewards pool and dlist. The pool will be destoyed after the stake rewards have been distributed. */
     624           0 :   result->stake_reward_calculation.pool = fd_stake_reward_calculation_pool_join( fd_stake_reward_calculation_pool_new( fd_spad_alloc( runtime_spad,
     625           0 :                                                                                                                                       fd_stake_reward_calculation_pool_align(),
     626           0 :                                                                                                                                       fd_stake_reward_calculation_pool_footprint( rewards_max_count ) ),
     627           0 :                                                                                                                                       rewards_max_count ) );
     628           0 :   result->stake_reward_calculation.stake_rewards = fd_spad_alloc( runtime_spad,
     629           0 :                                                                   fd_stake_reward_calculation_dlist_align(),
     630           0 :                                                                   fd_stake_reward_calculation_dlist_footprint() );
     631             : 
     632           0 :   fd_stake_reward_calculation_dlist_new( result->stake_reward_calculation.stake_rewards );
     633           0 :   result->stake_reward_calculation.stake_rewards_len = 0UL;
     634             : 
     635             :   /* Create the vote rewards map. This will be destroyed after the vote rewards have been distributed. */
     636           0 :   ulong vote_account_cnt       = fd_vote_info_pair_t_map_size( temp_info->vote_states_pool, temp_info->vote_states_root );
     637           0 :   result->vote_reward_map_pool = fd_vote_reward_t_map_join( fd_vote_reward_t_map_new( fd_spad_alloc( runtime_spad,
     638           0 :                                                                                                      fd_vote_reward_t_map_align(),
     639           0 :                                                                                                      fd_vote_reward_t_map_footprint( vote_account_cnt )),
     640           0 :                                                                                       vote_account_cnt ) );
     641           0 :   result->vote_reward_map_root = NULL;
     642             : 
     643             :   /* Pre-fill the vote pubkeys in the vote rewards map pool */
     644           0 :   for( fd_vote_info_pair_t_mapnode_t * vote_info = fd_vote_info_pair_t_map_minimum( temp_info->vote_states_pool, temp_info->vote_states_root );
     645           0 :        vote_info;
     646           0 :        vote_info = fd_vote_info_pair_t_map_successor( temp_info->vote_states_pool, vote_info ) ) {
     647             : 
     648           0 :     fd_pubkey_t const *          voter_pubkey     = &vote_info->elem.account;
     649           0 :     fd_vote_reward_t_mapnode_t * vote_reward_node = fd_vote_reward_t_map_acquire( result->vote_reward_map_pool );
     650             : 
     651           0 :     vote_reward_node->elem.pubkey       = *voter_pubkey;
     652           0 :     vote_reward_node->elem.vote_rewards = 0UL;
     653           0 :     vote_reward_node->elem.needs_store  = 0;
     654             : 
     655           0 :     fd_vote_reward_t_map_insert( result->vote_reward_map_pool, &result->vote_reward_map_root, vote_reward_node );
     656           0 :   }
     657             : 
     658             :   /* Pre-allocate the dlist stake reward elements */
     659           0 :   for( ulong i=0UL; i<temp_info->stake_infos_len; i++ ) {
     660           0 :     fd_stake_reward_t * stake_reward = fd_stake_reward_calculation_pool_ele_acquire( result->stake_reward_calculation.pool );
     661           0 :     if( FD_UNLIKELY( stake_reward==NULL ) ) {
     662           0 :       FD_LOG_ERR(( "insufficient space allocated for stake reward calculation pool" ));
     663           0 :       return;
     664           0 :     }
     665           0 :     stake_reward->valid = 0;
     666           0 :     fd_stake_reward_calculation_dlist_ele_push_tail( result->stake_reward_calculation.stake_rewards, stake_reward, result->stake_reward_calculation.pool );
     667           0 :   }
     668             : 
     669           0 :   fd_calculate_stake_vote_rewards_task_args_t task_args = {
     670           0 :     .slot_ctx                       = slot_ctx,
     671           0 :     .stake_history                  = stake_history,
     672           0 :     .rewarded_epoch                 = rewarded_epoch,
     673           0 :     .new_warmup_cooldown_rate_epoch = new_warmup_cooldown_rate_epoch,
     674           0 :     .point_value                    = point_value,
     675           0 :     .result                         = result,
     676           0 :     .exec_spads                     = exec_spads,
     677           0 :     .exec_spad_cnt                  = exec_spad_cnt,
     678           0 :   };
     679             : 
     680             :   /* Loop over all the delegations
     681             :      https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L367  */
     682           0 :   if( !!tpool ) {
     683           0 :     fd_tpool_exec_all_batch( tpool, 0UL, fd_tpool_worker_cnt( tpool ), calculate_stake_vote_rewards_account_tpool_task,
     684           0 :                              temp_info, &task_args,
     685           0 :                              NULL, 1UL, 0UL, temp_info->stake_infos_len );
     686           0 :   } else {
     687           0 :     calculate_stake_vote_rewards_account( temp_info, &task_args, 0UL, temp_info->stake_infos_len );
     688           0 :   }
     689           0 : }
     690             : 
     691             : /* Calculate epoch reward and return vote and stake rewards.
     692             : 
     693             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L273 */
     694             : static void
     695             : calculate_validator_rewards( fd_exec_slot_ctx_t *                      slot_ctx,
     696             :                              ulong                                     rewarded_epoch,
     697             :                              ulong                                     rewards,
     698             :                              fd_calculate_validator_rewards_result_t * result,
     699             :                              fd_epoch_info_t *                         temp_info,
     700             :                              fd_tpool_t *                              tpool,
     701             :                              fd_spad_t * *                             exec_spads,
     702             :                              ulong                                     exec_spad_cnt,
     703           0 :                              fd_spad_t *                               runtime_spad ) {
     704             :     /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L2759-L2786 */
     705           0 :   fd_stake_history_t const * stake_history = fd_sysvar_stake_history_read( slot_ctx->funk, slot_ctx->funk_txn, runtime_spad );
     706           0 :     if( FD_UNLIKELY( !stake_history ) ) {
     707           0 :     FD_LOG_ERR(( "Unable to read and decode stake history sysvar" ));
     708           0 :   }
     709             : 
     710             :   /* Calculate the epoch reward points from stake/vote accounts */
     711           0 :   calculate_reward_points_partitioned( slot_ctx,
     712           0 :                                        stake_history,
     713           0 :                                        rewards,
     714           0 :                                        &result->point_value,
     715           0 :                                        tpool,
     716           0 :                                        temp_info,
     717           0 :                                        runtime_spad );
     718             : 
     719             :   /* Calculate the stake and vote rewards for each account */
     720           0 :   calculate_stake_vote_rewards( slot_ctx,
     721           0 :                                 stake_history,
     722           0 :                                 rewarded_epoch,
     723           0 :                                 &result->point_value,
     724           0 :                                 &result->calculate_stake_vote_rewards_result,
     725           0 :                                 temp_info,
     726           0 :                                 tpool,
     727           0 :                                 exec_spads,
     728           0 :                                 exec_spad_cnt,
     729           0 :                                 runtime_spad );
     730           0 : }
     731             : 
     732             : /* Calculate the number of blocks required to distribute rewards to all stake accounts.
     733             : 
     734             :     https://github.com/anza-xyz/agave/blob/9a7bf72940f4b3cd7fc94f54e005868ce707d53d/runtime/src/bank/partitioned_epoch_rewards/mod.rs#L214
     735             :  */
     736             : static ulong
     737             : get_reward_distribution_num_blocks( fd_epoch_schedule_t const * epoch_schedule,
     738             :                                     ulong                       slot,
     739           0 :                                     ulong                       total_stake_accounts ) {
     740             :   /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L1250-L1267 */
     741           0 :   if( epoch_schedule->warmup &&
     742           0 :       fd_slot_to_epoch( epoch_schedule, slot, NULL ) < epoch_schedule->first_normal_epoch ) {
     743           0 :     return 1UL;
     744           0 :   }
     745             : 
     746           0 :   ulong num_chunks = total_stake_accounts / (ulong)STAKE_ACCOUNT_STORES_PER_BLOCK + (total_stake_accounts % STAKE_ACCOUNT_STORES_PER_BLOCK != 0);
     747           0 :   num_chunks       = fd_ulong_max( num_chunks, 1UL );
     748           0 :   num_chunks       = fd_ulong_min( num_chunks,
     749           0 :                                    fd_ulong_max( epoch_schedule->slots_per_epoch / (ulong)MAX_FACTOR_OF_REWARD_BLOCKS_IN_EPOCH, 1UL ) );
     750           0 :   return num_chunks;
     751           0 : }
     752             : 
     753             : static void
     754             : hash_rewards_into_partitions( fd_stake_reward_calculation_t *             stake_reward_calculation,
     755             :                               fd_hash_t const *                           parent_blockhash,
     756             :                               ulong                                       num_partitions,
     757             :                               fd_stake_reward_calculation_partitioned_t * result,
     758           0 :                               fd_spad_t *                                 runtime_spad ) {
     759             : 
     760             :   /* Initialize a dlist for every partition.
     761             :       These will all use the same pool - we do not re-allocate the stake rewards, only move them into partitions. */
     762           0 :   result->partitioned_stake_rewards.pool           = stake_reward_calculation->pool;
     763           0 :   result->partitioned_stake_rewards.partitions_len = num_partitions;
     764           0 :   result->partitioned_stake_rewards.partitions     = fd_spad_alloc( runtime_spad,
     765           0 :                                                                     fd_partitioned_stake_rewards_dlist_align(),
     766           0 :                                                                     fd_partitioned_stake_rewards_dlist_footprint() * num_partitions );
     767             : 
     768             :   /* Ownership of these dlist's and the pool gets transferred to stake_rewards_by_partition, which then gets transferred to epoch_reward_status.
     769             :       These are eventually cleaned up when epoch_reward_status_inactive is called. */
     770           0 :   for( ulong i = 0; i < num_partitions; ++i ) {
     771           0 :     fd_partitioned_stake_rewards_dlist_new( &result->partitioned_stake_rewards.partitions[ i ] );
     772           0 :   }
     773             : 
     774             :   /* Iterate over all the stake rewards, moving references to them into the appropiate partitions.
     775             :       IMPORTANT: after this, we cannot use the original stake rewards dlist anymore. */
     776           0 :   fd_stake_reward_calculation_dlist_iter_t next_iter;
     777           0 :   for( fd_stake_reward_calculation_dlist_iter_t iter = fd_stake_reward_calculation_dlist_iter_fwd_init( stake_reward_calculation->stake_rewards, stake_reward_calculation->pool );
     778           0 :         !fd_stake_reward_calculation_dlist_iter_done( iter, stake_reward_calculation->stake_rewards, stake_reward_calculation->pool );
     779           0 :         iter = next_iter ) {
     780           0 :     fd_stake_reward_t * stake_reward = fd_stake_reward_calculation_dlist_iter_ele( iter, stake_reward_calculation->stake_rewards, stake_reward_calculation->pool );
     781             :     /* Cache the next iter here, as we will overwrite the DLIST_NEXT value further down in the loop iteration. */
     782           0 :     next_iter = fd_stake_reward_calculation_dlist_iter_fwd_next( iter, stake_reward_calculation->stake_rewards, stake_reward_calculation->pool );
     783             : 
     784           0 :     if( FD_UNLIKELY( !stake_reward->valid ) ) {
     785           0 :       continue;
     786           0 :     }
     787             : 
     788             :     /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/epoch_rewards_hasher.rs#L43C31-L61 */
     789           0 :     fd_siphash13_t  _sip[1] = {0};
     790           0 :     fd_siphash13_t * hasher = fd_siphash13_init( _sip, 0UL, 0UL );
     791             : 
     792           0 :     hasher = fd_siphash13_append( hasher, parent_blockhash->hash, sizeof(fd_hash_t) );
     793           0 :     fd_siphash13_append( hasher, (const uchar *) stake_reward->stake_pubkey.key, sizeof(fd_pubkey_t) );
     794             : 
     795           0 :     ulong hash64 = fd_siphash13_fini( hasher );
     796             :     /* hash_to_partition */
     797             :     /* FIXME: should be saturating add */
     798           0 :     ulong partition_index = (ulong)((uint128) num_partitions *
     799           0 :                                     (uint128) hash64 /
     800           0 :                                     ((uint128)ULONG_MAX + 1));
     801             : 
     802             :     /* Move the stake reward to the partition's dlist */
     803           0 :     fd_partitioned_stake_rewards_dlist_t * partition = &result->partitioned_stake_rewards.partitions[ partition_index ];
     804           0 :     fd_partitioned_stake_rewards_dlist_ele_push_tail( partition, stake_reward, stake_reward_calculation->pool );
     805           0 :     result->partitioned_stake_rewards.partitions_lengths[ partition_index ]++;
     806           0 :   }
     807           0 : }
     808             : 
     809             : /* Calculate rewards from previous epoch to prepare for partitioned distribution.
     810             : 
     811             :    https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L214 */
     812             : static void
     813             : calculate_rewards_for_partitioning( fd_exec_slot_ctx_t *                   slot_ctx,
     814             :                                     ulong                                  prev_epoch,
     815             :                                     const fd_hash_t *                      parent_blockhash,
     816             :                                     fd_partitioned_rewards_calculation_t * result,
     817             :                                     fd_epoch_info_t *                      temp_info,
     818             :                                     fd_tpool_t *                           tpool,
     819             :                                     fd_spad_t * *                          exec_spads,
     820             :                                     ulong                                  exec_spad_cnt,
     821           0 :                                     fd_spad_t *                            runtime_spad ) {
     822             :   /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L227 */
     823           0 :   fd_prev_epoch_inflation_rewards_t rewards;
     824             : 
     825           0 :   calculate_previous_epoch_inflation_rewards( slot_ctx,
     826           0 :                                               fd_bank_capitalization_get( slot_ctx->bank ),
     827           0 :                                               prev_epoch,
     828           0 :                                               &rewards );
     829             : 
     830           0 :   fd_calculate_validator_rewards_result_t validator_result[1] = {0};
     831           0 :   calculate_validator_rewards( slot_ctx,
     832           0 :                                prev_epoch,
     833           0 :                                rewards.validator_rewards,
     834           0 :                                validator_result,
     835           0 :                                temp_info,
     836           0 :                                tpool,
     837           0 :                                exec_spads,
     838           0 :                                exec_spad_cnt,
     839           0 :                                runtime_spad );
     840             : 
     841           0 :   fd_stake_reward_calculation_t * stake_reward_calculation = &validator_result->calculate_stake_vote_rewards_result.stake_reward_calculation;
     842           0 :   fd_epoch_schedule_t const *     epoch_schedule           = fd_bank_epoch_schedule_query( slot_ctx->bank );
     843           0 :   ulong                           num_partitions           = get_reward_distribution_num_blocks( epoch_schedule,
     844           0 :                                                                                                  fd_bank_slot_get( slot_ctx->bank ),
     845           0 :                                                                                                  stake_reward_calculation->stake_rewards_len );
     846           0 :   hash_rewards_into_partitions( stake_reward_calculation,
     847           0 :                                 parent_blockhash,
     848           0 :                                 num_partitions,
     849           0 :                                 &result->stake_rewards_by_partition,
     850           0 :                                 runtime_spad );
     851             : 
     852           0 :   result->stake_rewards_by_partition.total_stake_rewards_lamports =
     853           0 :     validator_result->calculate_stake_vote_rewards_result.stake_reward_calculation.total_stake_rewards_lamports;
     854             : 
     855           0 :   result->vote_reward_map_pool         = validator_result->calculate_stake_vote_rewards_result.vote_reward_map_pool;
     856           0 :   result->vote_reward_map_root         = validator_result->calculate_stake_vote_rewards_result.vote_reward_map_root;
     857           0 :   result->validator_rewards            = rewards.validator_rewards;
     858           0 :   result->validator_rate               = rewards.validator_rate;
     859           0 :   result->foundation_rate              = rewards.foundation_rate;
     860           0 :   result->prev_epoch_duration_in_years = rewards.prev_epoch_duration_in_years;
     861           0 :   result->capitalization               = fd_bank_capitalization_get( slot_ctx->bank );
     862           0 :   result->point_value                  = validator_result->point_value;
     863           0 : }
     864             : 
     865             : /* Calculate rewards from previous epoch and distribute vote rewards
     866             : 
     867             :    https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L97 */
     868             : static void
     869             : calculate_rewards_and_distribute_vote_rewards( fd_exec_slot_ctx_t *                                        slot_ctx,
     870             :                                                ulong                                                       prev_epoch,
     871             :                                                fd_hash_t const *                                           parent_blockhash,
     872             :                                                fd_calculate_rewards_and_distribute_vote_rewards_result_t * result,
     873             :                                                fd_epoch_info_t *                                           temp_info,
     874             :                                                fd_tpool_t *                                                tpool,
     875             :                                                fd_spad_t * *                                               exec_spads,
     876             :                                                ulong                                                       exec_spad_cnt,
     877           0 :                                                fd_spad_t *                                                 runtime_spad ) {
     878             : 
     879             :   /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L2406-L2492 */
     880           0 :   fd_partitioned_rewards_calculation_t rewards_calc_result[1] = {0};
     881           0 :   calculate_rewards_for_partitioning( slot_ctx,
     882           0 :                                       prev_epoch,
     883           0 :                                       parent_blockhash,
     884           0 :                                       rewards_calc_result,
     885           0 :                                       temp_info,
     886           0 :                                       tpool,
     887           0 :                                       exec_spads,
     888           0 :                                       exec_spad_cnt,
     889           0 :                                       runtime_spad );
     890             : 
     891             :   /* Iterate over all the vote reward nodes */
     892           0 :   for( fd_vote_reward_t_mapnode_t * vote_reward_node = fd_vote_reward_t_map_minimum( rewards_calc_result->vote_reward_map_pool, rewards_calc_result->vote_reward_map_root);
     893           0 :        vote_reward_node;
     894           0 :        vote_reward_node = fd_vote_reward_t_map_successor( rewards_calc_result->vote_reward_map_pool, vote_reward_node ) ) {
     895             : 
     896           0 :     if( FD_UNLIKELY( !vote_reward_node->elem.needs_store ) ) {
     897           0 :       continue;
     898           0 :     }
     899             : 
     900           0 :     fd_pubkey_t const * vote_pubkey = &vote_reward_node->elem.pubkey;
     901           0 :     FD_TXN_ACCOUNT_DECL( vote_rec );
     902             : 
     903           0 :     if( FD_UNLIKELY( fd_txn_account_init_from_funk_mutable( vote_rec,
     904           0 :                                                             vote_pubkey,
     905           0 :                                                             slot_ctx->funk,
     906           0 :                                                             slot_ctx->funk_txn,
     907           0 :                                                             1,
     908           0 :                                                             0UL ) != FD_ACC_MGR_SUCCESS ) ) {
     909           0 :       FD_LOG_ERR(( "Unable to modify vote account" ));
     910           0 :     }
     911             : 
     912           0 :     vote_rec->vt->set_slot( vote_rec, fd_bank_slot_get( slot_ctx->bank ) );
     913             : 
     914           0 :     if( FD_UNLIKELY( vote_rec->vt->checked_add_lamports( vote_rec, vote_reward_node->elem.vote_rewards ) ) ) {
     915           0 :       FD_LOG_ERR(( "Adding lamports to vote account would cause overflow" ));
     916           0 :     }
     917             : 
     918           0 :     fd_txn_account_mutable_fini( vote_rec, slot_ctx->funk, slot_ctx->funk_txn );
     919             : 
     920           0 :     result->distributed_rewards = fd_ulong_sat_add( result->distributed_rewards, vote_reward_node->elem.vote_rewards );
     921           0 :   }
     922             : 
     923             :   /* There is no need to free the vote reward map since it was spad*/
     924             : 
     925             :   /* Verify that we didn't pay any more than we expected to */
     926           0 :   result->total_rewards = fd_ulong_sat_add( result->distributed_rewards, rewards_calc_result->stake_rewards_by_partition.total_stake_rewards_lamports );
     927           0 :   if( FD_UNLIKELY( rewards_calc_result->validator_rewards < result->total_rewards ) ) {
     928           0 :     FD_LOG_ERR(( "Unexpected rewards calculation result" ));
     929           0 :   }
     930             : 
     931           0 :   fd_bank_capitalization_set( slot_ctx->bank, fd_bank_capitalization_get( slot_ctx->bank ) + result->distributed_rewards );
     932             : 
     933             :   /* Cheap because this doesn't copy all the rewards, just pointers to the dlist */
     934           0 :   result->stake_rewards_by_partition = rewards_calc_result->stake_rewards_by_partition;
     935           0 :   result->point_value                = rewards_calc_result->point_value;
     936           0 : }
     937             : 
     938             : /* Distributes a single partitioned reward to a single stake account */
     939             : static int
     940             : distribute_epoch_reward_to_stake_acc( fd_exec_slot_ctx_t * slot_ctx,
     941             :                                       fd_pubkey_t *        stake_pubkey,
     942             :                                       ulong                reward_lamports,
     943           0 :                                       ulong                new_credits_observed ) {
     944           0 :   FD_TXN_ACCOUNT_DECL( stake_acc_rec );
     945           0 :   if( FD_UNLIKELY( fd_txn_account_init_from_funk_mutable( stake_acc_rec,
     946           0 :                                                           stake_pubkey,
     947           0 :                                                           slot_ctx->funk,
     948           0 :                                                           slot_ctx->funk_txn,
     949           0 :                                                           0,
     950           0 :                                                           0UL ) != FD_ACC_MGR_SUCCESS ) ) {
     951           0 :     FD_LOG_ERR(( "Unable to modify stake account" ));
     952           0 :   }
     953             : 
     954           0 :   stake_acc_rec->vt->set_slot( stake_acc_rec, fd_bank_slot_get( slot_ctx->bank ) );
     955             : 
     956           0 :   fd_stake_state_v2_t stake_state[1] = {0};
     957           0 :   if( fd_stake_get_state( stake_acc_rec, stake_state ) != 0 ) {
     958           0 :     FD_LOG_DEBUG(( "failed to read stake state for %s", FD_BASE58_ENC_32_ALLOCA( stake_pubkey ) ));
     959           0 :     return 1;
     960           0 :   }
     961             : 
     962           0 :   if ( !fd_stake_state_v2_is_stake( stake_state ) ) {
     963           0 :     FD_LOG_DEBUG(( "non-stake stake account, this should never happen" ));
     964           0 :     return 1;
     965           0 :   }
     966             : 
     967           0 :   if( stake_acc_rec->vt->checked_add_lamports( stake_acc_rec, reward_lamports ) ) {
     968           0 :     FD_LOG_DEBUG(( "failed to add lamports to stake account" ));
     969           0 :     return 1;
     970           0 :   }
     971             : 
     972           0 :   stake_state->inner.stake.stake.credits_observed = new_credits_observed;
     973           0 :   stake_state->inner.stake.stake.delegation.stake = fd_ulong_sat_add( stake_state->inner.stake.stake.delegation.stake,
     974           0 :                                                                       reward_lamports );
     975             : 
     976           0 :   if( FD_UNLIKELY( write_stake_state( stake_acc_rec, stake_state ) != 0 ) ) {
     977           0 :     FD_LOG_ERR(( "write_stake_state failed" ));
     978           0 :   }
     979             : 
     980           0 :   fd_txn_account_mutable_fini( stake_acc_rec, slot_ctx->funk, slot_ctx->funk_txn );
     981             : 
     982           0 :   return 0;
     983           0 : }
     984             : 
     985             : /* Sets the epoch reward status to inactive, and destroys any allocated state associated with the active state. */
     986             : static void
     987           0 : set_epoch_reward_status_inactive( fd_exec_slot_ctx_t * slot_ctx ) {
     988           0 :   fd_epoch_reward_status_global_t * epoch_reward_status = fd_bank_epoch_reward_status_locking_modify( slot_ctx->bank );
     989           0 :   if( epoch_reward_status->discriminant == fd_epoch_reward_status_enum_Active ) {
     990           0 :     FD_LOG_NOTICE(( "Done partitioning rewards for current epoch" ));
     991           0 :   }
     992           0 :   epoch_reward_status->discriminant = fd_epoch_reward_status_enum_Inactive;
     993           0 :   fd_bank_epoch_reward_status_end_locking_modify( slot_ctx->bank );
     994           0 : }
     995             : 
     996             : /* Sets the epoch reward status to active.
     997             : 
     998             :     Takes ownership of the given stake_rewards_by_partition data structure,
     999             :     which will be destroyed when set_epoch_reward_status_inactive is called. */
    1000             : static void
    1001             : set_epoch_reward_status_active( fd_exec_slot_ctx_t *             slot_ctx,
    1002             :                                 ulong                            distribution_starting_block_height,
    1003           0 :                                 fd_partitioned_stake_rewards_t * partitioned_rewards ) {
    1004             : 
    1005           0 :   FD_LOG_NOTICE(( "Setting epoch reward status as active" ));
    1006             : 
    1007           0 :   fd_epoch_reward_status_global_t * epoch_reward_status                = fd_bank_epoch_reward_status_locking_modify( slot_ctx->bank );
    1008           0 :   epoch_reward_status->discriminant                                    = fd_epoch_reward_status_enum_Active;
    1009           0 :   epoch_reward_status->inner.Active.distribution_starting_block_height = distribution_starting_block_height;
    1010             : 
    1011           0 :   epoch_reward_status->inner.Active.partitioned_stake_rewards.partitions_len     = partitioned_rewards->partitions_len;
    1012           0 :   fd_memcpy( epoch_reward_status->inner.Active.partitioned_stake_rewards.partitions_lengths,
    1013           0 :              partitioned_rewards->partitions_lengths,
    1014           0 :              sizeof(ulong[4096]) );
    1015             : 
    1016           0 :   ulong pool_max       = fd_stake_reward_calculation_pool_max( partitioned_rewards->pool );
    1017           0 :   ulong pool_footprint = fd_stake_reward_calculation_pool_footprint( pool_max );
    1018             : 
    1019             :   /* Copy in the pool */
    1020           0 :   uchar * pool_mem = (uchar *)fd_ulong_align_up( (ulong)epoch_reward_status + sizeof(fd_epoch_reward_status_global_t),
    1021           0 :                                                  fd_stake_reward_calculation_pool_align() );
    1022           0 :   fd_memcpy( pool_mem, fd_stake_reward_calculation_pool_leave( partitioned_rewards->pool ), pool_footprint );
    1023           0 :   epoch_reward_status->inner.Active.partitioned_stake_rewards.pool_offset = (ulong)pool_mem - (ulong)&epoch_reward_status->inner.Active.partitioned_stake_rewards;
    1024             : 
    1025             :   /* Copy in the partitions */
    1026           0 :   uchar * partitions_mem       = (uchar *)fd_ulong_align_up( (ulong)pool_mem + pool_footprint, fd_partitioned_stake_rewards_dlist_align() );
    1027           0 :   ulong   partitions_footprint = fd_partitioned_stake_rewards_dlist_footprint() * partitioned_rewards->partitions_len;
    1028           0 :   fd_memcpy( partitions_mem, fd_partitioned_stake_rewards_dlist_leave( partitioned_rewards->partitions ), partitions_footprint );
    1029           0 :   epoch_reward_status->inner.Active.partitioned_stake_rewards.partitions_offset = (ulong)partitions_mem - (ulong)&epoch_reward_status->inner.Active.partitioned_stake_rewards;
    1030             : 
    1031           0 :   fd_bank_epoch_reward_status_end_locking_modify( slot_ctx->bank );
    1032           0 : }
    1033             : 
    1034             : /*  Process reward credits for a partition of rewards.
    1035             :     Store the rewards to AccountsDB, update reward history record and total capitalization
    1036             : 
    1037             :     https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/distribution.rs#L88 */
    1038             : static void
    1039             : distribute_epoch_rewards_in_partition( fd_partitioned_stake_rewards_dlist_t * partition,
    1040             :                                        fd_stake_reward_t *                    pool,
    1041             :                                        fd_exec_slot_ctx_t *                   slot_ctx,
    1042           0 :                                        fd_spad_t *                            runtime_spad ) {
    1043             : 
    1044           0 :   ulong lamports_distributed = 0UL;
    1045           0 :   ulong lamports_burned      = 0UL;
    1046             : 
    1047           0 :   for( fd_partitioned_stake_rewards_dlist_iter_t iter = fd_partitioned_stake_rewards_dlist_iter_fwd_init( partition, pool );
    1048           0 :         !fd_partitioned_stake_rewards_dlist_iter_done( iter, partition, pool );
    1049           0 :         iter = fd_partitioned_stake_rewards_dlist_iter_fwd_next( iter, partition, pool ) ) {
    1050           0 :     fd_stake_reward_t * stake_reward = fd_partitioned_stake_rewards_dlist_iter_ele( iter, partition, pool );
    1051             : 
    1052           0 :     if( distribute_epoch_reward_to_stake_acc( slot_ctx,
    1053           0 :                                               &stake_reward->stake_pubkey,
    1054           0 :                                               stake_reward->lamports,
    1055           0 :                                               stake_reward->credits_observed ) == 0 ) {
    1056           0 :       lamports_distributed += stake_reward->lamports;
    1057           0 :     } else {
    1058           0 :       lamports_burned += stake_reward->lamports;
    1059           0 :     }
    1060           0 :   }
    1061             : 
    1062             :   /* Update the epoch rewards sysvar with the amount distributed and burnt */
    1063           0 :   fd_sysvar_epoch_rewards_distribute( slot_ctx,
    1064           0 :                                       lamports_distributed + lamports_burned,
    1065           0 :                                       runtime_spad );
    1066             : 
    1067           0 :   FD_LOG_DEBUG(( "lamports burned: %lu, lamports distributed: %lu", lamports_burned, lamports_distributed ));
    1068             : 
    1069           0 :   fd_bank_capitalization_set( slot_ctx->bank, fd_bank_capitalization_get( slot_ctx->bank ) + lamports_distributed );
    1070           0 : }
    1071             : 
    1072             : /* Process reward distribution for the block if it is inside reward interval.
    1073             : 
    1074             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/distribution.rs#L42 */
    1075             : void
    1076             : fd_distribute_partitioned_epoch_rewards( fd_exec_slot_ctx_t * slot_ctx,
    1077             :                                          fd_tpool_t *         tpool,
    1078             :                                          fd_spad_t * *        exec_spads,
    1079             :                                          ulong                exec_spad_cnt,
    1080           0 :                                          fd_spad_t *          runtime_spad ) {
    1081             : 
    1082           0 :   (void)tpool;
    1083           0 :   (void)exec_spads;
    1084           0 :   (void)exec_spad_cnt;
    1085             : 
    1086           0 :   fd_epoch_reward_status_global_t const * epoch_reward_status = fd_bank_epoch_reward_status_locking_query( slot_ctx->bank );
    1087             : 
    1088           0 :   if( epoch_reward_status->discriminant == fd_epoch_reward_status_enum_Inactive ) {
    1089           0 :     fd_bank_epoch_reward_status_end_locking_query( slot_ctx->bank );
    1090           0 :     return;
    1091           0 :   }
    1092             : 
    1093           0 :   fd_start_block_height_and_rewards_global_t const * status = &epoch_reward_status->inner.Active;
    1094             : 
    1095           0 :   fd_partitioned_stake_rewards_dlist_t * partitions =
    1096           0 :     (fd_partitioned_stake_rewards_dlist_t *)((uchar *)&status->partitioned_stake_rewards + status->partitioned_stake_rewards.partitions_offset);
    1097             : 
    1098           0 :   fd_stake_reward_t * pool = fd_stake_reward_calculation_pool_join( (uchar *)&status->partitioned_stake_rewards + status->partitioned_stake_rewards.pool_offset );
    1099           0 :   if( FD_UNLIKELY( !pool ) ) {
    1100           0 :     FD_LOG_CRIT(( "Failed to join pool" ));
    1101           0 :   }
    1102             : 
    1103           0 :   ulong height                             = fd_bank_block_height_get( slot_ctx->bank );
    1104           0 :   ulong distribution_starting_block_height = status->distribution_starting_block_height;
    1105           0 :   ulong distribution_end_exclusive         = distribution_starting_block_height + status->partitioned_stake_rewards.partitions_len;
    1106             : 
    1107           0 :   fd_epoch_schedule_t const * epoch_schedule = fd_bank_epoch_schedule_query( slot_ctx->bank );
    1108           0 :   ulong                       epoch          = fd_slot_to_epoch( epoch_schedule, fd_bank_slot_get( slot_ctx->bank ), NULL );
    1109             : 
    1110           0 :   if( FD_UNLIKELY( get_slots_in_epoch( epoch, epoch_schedule ) <= status->partitioned_stake_rewards.partitions_len ) ) {
    1111           0 :     FD_LOG_ERR(( "Should not be distributing rewards" ));
    1112           0 :   }
    1113             : 
    1114           0 :   if( (height>=distribution_starting_block_height) && (height < distribution_end_exclusive) ) {
    1115           0 :     ulong partition_index = height - distribution_starting_block_height;
    1116           0 :     distribute_epoch_rewards_in_partition( &partitions[ partition_index ],
    1117           0 :                                            pool,
    1118           0 :                                            slot_ctx,
    1119           0 :                                            runtime_spad );
    1120           0 :   }
    1121             : 
    1122           0 :   fd_bank_epoch_reward_status_end_locking_query( slot_ctx->bank );
    1123             : 
    1124             :   /* If we have finished distributing rewards, set the status to inactive */
    1125           0 :   if( fd_ulong_sat_add( height, 1UL ) >= distribution_end_exclusive ) {
    1126           0 :     set_epoch_reward_status_inactive( slot_ctx );
    1127           0 :     fd_sysvar_epoch_rewards_set_inactive( slot_ctx, runtime_spad );
    1128           0 :   }
    1129           0 : }
    1130             : 
    1131             : /* Partitioned epoch rewards entry-point.
    1132             : 
    1133             :    https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L41
    1134             : */
    1135             : void
    1136             : fd_begin_partitioned_rewards( fd_exec_slot_ctx_t * slot_ctx,
    1137             :                               fd_hash_t const *    parent_blockhash,
    1138             :                               ulong                parent_epoch,
    1139             :                               fd_epoch_info_t *    temp_info,
    1140             :                               fd_tpool_t *         tpool,
    1141             :                               fd_spad_t * *        exec_spads,
    1142             :                               ulong                exec_spad_cnt,
    1143           0 :                               fd_spad_t *          runtime_spad ) {
    1144             : 
    1145             :   /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L55 */
    1146           0 :   fd_calculate_rewards_and_distribute_vote_rewards_result_t rewards_result[1] = {0};
    1147           0 :   calculate_rewards_and_distribute_vote_rewards( slot_ctx,
    1148           0 :                                                  parent_epoch,
    1149           0 :                                                  parent_blockhash,
    1150           0 :                                                  rewards_result,
    1151           0 :                                                  temp_info,
    1152           0 :                                                  tpool,
    1153           0 :                                                  exec_spads,
    1154           0 :                                                  exec_spad_cnt,
    1155           0 :                                                  runtime_spad );
    1156             : 
    1157             :   /* https://github.com/anza-xyz/agave/blob/9a7bf72940f4b3cd7fc94f54e005868ce707d53d/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L62 */
    1158           0 :   ulong distribution_starting_block_height = fd_bank_block_height_get( slot_ctx->bank ) + REWARD_CALCULATION_NUM_BLOCKS;
    1159             : 
    1160             :   /* Set the epoch reward status to be active */
    1161           0 :   set_epoch_reward_status_active( slot_ctx,
    1162           0 :                                   distribution_starting_block_height,
    1163           0 :                                   &rewards_result->stake_rewards_by_partition.partitioned_stake_rewards );
    1164             : 
    1165             :   /* Initialize the epoch rewards sysvar
    1166             :     https://github.com/anza-xyz/agave/blob/9a7bf72940f4b3cd7fc94f54e005868ce707d53d/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L78 */
    1167           0 :   fd_sysvar_epoch_rewards_init( slot_ctx,
    1168           0 :                                 rewards_result->distributed_rewards,
    1169           0 :                                 distribution_starting_block_height,
    1170           0 :                                 rewards_result->stake_rewards_by_partition.partitioned_stake_rewards.partitions_len,
    1171           0 :                                 rewards_result->point_value,
    1172           0 :                                 parent_blockhash );
    1173           0 : }
    1174             : 
    1175             : /*
    1176             :     Re-calculates partitioned stake rewards.
    1177             :     This updates the slot context's epoch reward status with the recalculated partitioned rewards.
    1178             : 
    1179             :     https://github.com/anza-xyz/agave/blob/v2.2.14/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L521 */
    1180             : void
    1181             : fd_rewards_recalculate_partitioned_rewards( fd_exec_slot_ctx_t * slot_ctx,
    1182             :                                             fd_tpool_t *         tpool,
    1183             :                                             fd_spad_t * *        exec_spads,
    1184             :                                             ulong                exec_spad_cnt,
    1185           0 :                                             fd_spad_t *          runtime_spad ) {
    1186           0 :   fd_sysvar_epoch_rewards_t * epoch_rewards = fd_sysvar_epoch_rewards_read( slot_ctx->funk, slot_ctx->funk_txn, runtime_spad );
    1187           0 :   if( FD_UNLIKELY( epoch_rewards == NULL ) ) {
    1188           0 :     FD_LOG_NOTICE(( "Failed to read or decode epoch rewards sysvar - may not have been created yet" ));
    1189           0 :     set_epoch_reward_status_inactive( slot_ctx );
    1190           0 :     return;
    1191           0 :   }
    1192             : 
    1193           0 :   FD_LOG_NOTICE(( "recalculating partitioned rewards" ));
    1194             : 
    1195           0 :   if( FD_UNLIKELY( epoch_rewards->active ) ) {
    1196             : 
    1197             :     /* If epoch rewards are active, we must calculate the rewards partitions
    1198             :        so we can start distributing. For the same reason as described in
    1199             :        fd_runtime_process_new_epoch, we must push on a spad frame at this
    1200             :        point. */
    1201           0 :     fd_spad_push( runtime_spad );
    1202             : 
    1203             :     /* If partitioned rewards are active, the rewarded epoch is always the immediately
    1204             :         preceeding epoch.
    1205             : 
    1206             :         https://github.com/anza-xyz/agave/blob/2316fea4c0852e59c071f72d72db020017ffd7d0/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L566 */
    1207           0 :     FD_LOG_NOTICE(( "epoch rewards is active" ));
    1208             : 
    1209           0 :     fd_epoch_schedule_t const * epoch_schedule = fd_bank_epoch_schedule_query( slot_ctx->bank );
    1210           0 :     ulong epoch          = fd_slot_to_epoch( epoch_schedule, fd_bank_slot_get( slot_ctx->bank ), NULL );
    1211           0 :     ulong rewarded_epoch = fd_ulong_sat_sub( epoch, 1UL );
    1212             : 
    1213           0 :     int _err[1] = {0};
    1214           0 :     ulong * new_warmup_cooldown_rate_epoch = fd_spad_alloc( runtime_spad, alignof(ulong), sizeof(ulong) );
    1215           0 :     int is_some = fd_new_warmup_cooldown_rate_epoch( fd_bank_slot_get( slot_ctx->bank ),
    1216           0 :                                                      slot_ctx->funk,
    1217           0 :                                                      slot_ctx->funk_txn,
    1218           0 :                                                      runtime_spad,
    1219           0 :                                                      fd_bank_features_query( slot_ctx->bank ),
    1220           0 :                                                      new_warmup_cooldown_rate_epoch,
    1221           0 :                                                      _err );
    1222           0 :     if( FD_UNLIKELY( !is_some ) ) {
    1223           0 :       new_warmup_cooldown_rate_epoch = NULL;
    1224           0 :     }
    1225             : 
    1226           0 :     fd_stake_history_t const * stake_history = fd_sysvar_stake_history_read( slot_ctx->funk, slot_ctx->funk_txn, runtime_spad );
    1227           0 :     if( FD_UNLIKELY( !stake_history ) ) {
    1228           0 :       FD_LOG_ERR(( "Unable to read and decode stake history sysvar" ));
    1229           0 :     }
    1230             : 
    1231           0 :     fd_point_value_t point_value = { .points  = epoch_rewards->total_points,
    1232           0 :                                      .rewards = epoch_rewards->total_rewards };
    1233             : 
    1234             :     /* Populate vote and stake state info from vote and stakes cache for the stake vote rewards calculation */
    1235           0 :     fd_stakes_global_t const *       stakes                 = fd_bank_stakes_locking_query( slot_ctx->bank );
    1236           0 :     fd_delegation_pair_t_mapnode_t * stake_delegations_pool = fd_stakes_stake_delegations_pool_join( stakes );
    1237           0 :     fd_delegation_pair_t_mapnode_t * stake_delegations_root = fd_stakes_stake_delegations_root_join( stakes );
    1238             : 
    1239           0 :     fd_epoch_info_t epoch_info = {0};
    1240           0 :     fd_epoch_info_new( &epoch_info );
    1241             : 
    1242           0 :     ulong stake_delegation_sz  = fd_delegation_pair_t_map_size( stake_delegations_pool, stake_delegations_root );
    1243           0 :     epoch_info.stake_infos_len = 0UL;
    1244           0 :     epoch_info.stake_infos     = fd_spad_alloc( runtime_spad, FD_EPOCH_INFO_PAIR_ALIGN, sizeof(fd_epoch_info_pair_t)*stake_delegation_sz );
    1245             : 
    1246           0 :     fd_stake_history_entry_t _accumulator = {
    1247           0 :         .effective = 0UL,
    1248           0 :         .activating = 0UL,
    1249           0 :         .deactivating = 0UL
    1250           0 :     };
    1251             : 
    1252           0 :     fd_accumulate_stake_infos( slot_ctx,
    1253           0 :                                stakes,
    1254           0 :                                stake_history,
    1255           0 :                                new_warmup_cooldown_rate_epoch,
    1256           0 :                                &_accumulator,
    1257           0 :                                &epoch_info,
    1258           0 :                                tpool,
    1259           0 :                                exec_spads,
    1260           0 :                                exec_spad_cnt,
    1261           0 :                                runtime_spad );
    1262             : 
    1263           0 :     fd_bank_stakes_end_locking_query( slot_ctx->bank );
    1264             : 
    1265             :     /* NOTE: this is just a workaround for now to correctly populate epoch_info. */
    1266           0 :     fd_populate_vote_accounts( slot_ctx,
    1267           0 :                                stake_history,
    1268           0 :                                new_warmup_cooldown_rate_epoch,
    1269           0 :                                &epoch_info,
    1270           0 :                                tpool,
    1271           0 :                                exec_spads,
    1272           0 :                                exec_spad_cnt,
    1273           0 :                                runtime_spad );
    1274             :     /* In future, the calculation will be cached in the snapshot, but for now we just re-calculate it
    1275             :         (as Agave does). */
    1276           0 :     fd_calculate_stake_vote_rewards_result_t calculate_stake_vote_rewards_result[1];
    1277           0 :     calculate_stake_vote_rewards( slot_ctx,
    1278           0 :                                   stake_history,
    1279           0 :                                   rewarded_epoch,
    1280           0 :                                   &point_value,
    1281           0 :                                   calculate_stake_vote_rewards_result,
    1282           0 :                                   &epoch_info,
    1283           0 :                                   tpool,
    1284           0 :                                   exec_spads,
    1285           0 :                                   exec_spad_cnt,
    1286           0 :                                   runtime_spad );
    1287             : 
    1288             :     /* The vote reward map isn't actually used in this code path and will only
    1289             :        be freed after rewards have been distributed. */
    1290             : 
    1291             : 
    1292             :     /* Use the epoch rewards sysvar parent_blockhash and num_partitions.
    1293             :        https://github.com/anza-xyz/agave/blob/v2.2.14/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L579 */
    1294           0 :     fd_stake_reward_calculation_partitioned_t stake_rewards_by_partition[1];
    1295           0 :     hash_rewards_into_partitions( &calculate_stake_vote_rewards_result->stake_reward_calculation,
    1296           0 :                                   &epoch_rewards->parent_blockhash,
    1297           0 :                                   epoch_rewards->num_partitions,
    1298           0 :                                   stake_rewards_by_partition,
    1299           0 :                                   runtime_spad );
    1300             : 
    1301             :     /* Update the epoch reward status with the newly re-calculated partitions. */
    1302           0 :     set_epoch_reward_status_active( slot_ctx,
    1303           0 :                                     epoch_rewards->distribution_starting_block_height,
    1304           0 :                                     &stake_rewards_by_partition->partitioned_stake_rewards );
    1305           0 :   } else {
    1306           0 :     set_epoch_reward_status_inactive( slot_ctx );
    1307           0 :   }
    1308           0 : }

Generated by: LCOV version 1.14