LCOV - code coverage report
Current view: top level - flamenco/rewards - fd_rewards.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 228 655 34.8 %
Date: 2026-02-13 06:06:24 Functions: 18 26 69.2 %

          Line data    Source code
       1             : #include "fd_rewards.h"
       2             : #include <math.h>
       3             : 
       4             : #include "../runtime/sysvar/fd_sysvar_epoch_rewards.h"
       5             : #include "../runtime/sysvar/fd_sysvar_epoch_schedule.h"
       6             : #include "../stakes/fd_stakes.h"
       7             : #include "../runtime/program/fd_stake_program.h"
       8             : #include "../runtime/sysvar/fd_sysvar_stake_history.h"
       9             : #include "../capture/fd_capture_ctx.h"
      10             : #include "../runtime/fd_runtime_stack.h"
      11             : #include "../runtime/fd_runtime.h"
      12             : #include "../accdb/fd_accdb_sync.h"
      13             : #include "fd_epoch_rewards.h"
      14             : 
      15             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/sdk/src/inflation.rs#L85 */
      16             : static double
      17          90 : total( fd_inflation_t const * inflation, double year ) {
      18          90 :   if ( FD_UNLIKELY( year == 0.0 ) ) {
      19           0 :     FD_LOG_ERR(( "inflation year 0" ));
      20           0 :   }
      21          90 :   double tapered = inflation->initial * pow( (1.0 - inflation->taper), year );
      22          90 :   return (tapered > inflation->terminal) ? tapered : inflation->terminal;
      23          90 : }
      24             : 
      25             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/sdk/src/inflation.rs#L102 */
      26             : static double
      27         135 : foundation( fd_inflation_t const * inflation, double year ) {
      28         135 :   return (year < inflation->foundation_term) ? inflation->foundation * total(inflation, year) : 0.0;
      29         135 : }
      30             : 
      31             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/sdk/src/inflation.rs#L97 */
      32             : static double
      33          45 : validator( fd_inflation_t const * inflation, double year) {
      34             :   /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/sdk/src/inflation.rs#L96-L99 */
      35          45 :   FD_LOG_DEBUG(("Validator Rate: %.16f %.16f %.16f %.16f %.16f", year, total( inflation, year ), foundation( inflation, year ), inflation->taper, inflation->initial));
      36          45 :   return total( inflation, year ) - foundation( inflation, year );
      37          45 : }
      38             : 
      39             : /* Calculates the starting slot for inflation from the activation slot. The activation slot is the earliest
      40             :     activation slot of the following features:
      41             :     - devnet_and_testnet
      42             :     - full_inflation_enable, if full_inflation_vote has been activated
      43             : 
      44             :     https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank.rs#L2095 */
      45             : static FD_FN_CONST ulong
      46          45 : get_inflation_start_slot( fd_bank_t const * bank ) {
      47          45 :   ulong devnet_and_testnet = FD_FEATURE_ACTIVE_BANK( bank, devnet_and_testnet )
      48          45 :       ? fd_bank_features_query( bank )->devnet_and_testnet
      49          45 :       : ULONG_MAX;
      50             : 
      51          45 :   ulong enable = fd_bank_features_query( bank )->full_inflation_enable;
      52             : 
      53          45 :   ulong min_slot = fd_ulong_min( enable, devnet_and_testnet );
      54          45 :   if( min_slot == ULONG_MAX ) {
      55          18 :     if( FD_FEATURE_ACTIVE_BANK( bank, pico_inflation ) ) {
      56           0 :       min_slot = fd_bank_features_query( bank )->pico_inflation;
      57          18 :     } else {
      58          18 :       min_slot = 0;
      59          18 :     }
      60          18 :   }
      61          45 :   return min_slot;
      62          45 : }
      63             : 
      64             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank.rs#L2110 */
      65             : static ulong
      66             : get_inflation_num_slots( fd_bank_t const *           bank,
      67             :                          fd_epoch_schedule_t const * epoch_schedule,
      68          45 :                          ulong                       slot ) {
      69          45 :   ulong inflation_activation_slot = get_inflation_start_slot( bank );
      70          45 :   ulong inflation_start_slot      = fd_epoch_slot0( epoch_schedule,
      71          45 :                                                     fd_ulong_sat_sub( fd_slot_to_epoch( epoch_schedule,
      72          45 :                                                                                         inflation_activation_slot, NULL ),
      73          45 :                                                                       1UL ) );
      74             : 
      75          45 :   ulong epoch = fd_slot_to_epoch( epoch_schedule, slot, NULL );
      76             : 
      77          45 :   return fd_epoch_slot0( epoch_schedule, epoch ) - inflation_start_slot;
      78          45 : }
      79             : 
      80             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank.rs#L2121 */
      81             : static double
      82          45 : slot_in_year_for_inflation( fd_bank_t const * bank ) {
      83          45 :   fd_epoch_schedule_t const * epoch_schedule = fd_bank_epoch_schedule_query( bank );
      84          45 :   ulong num_slots = get_inflation_num_slots( bank, epoch_schedule, fd_bank_slot_get( bank ) );
      85          45 :   return (double)num_slots / (double)fd_bank_slots_per_year_get( bank );
      86          45 : }
      87             : 
      88             : static void
      89             : get_vote_credits( uchar const *               account_data,
      90             :                   ulong                       account_data_len,
      91             :                   uchar *                     buf,
      92           0 :                   fd_vote_epoch_credits_t * * credits ) {
      93             : 
      94           0 :   fd_bincode_decode_ctx_t ctx = {
      95           0 :     .data    = account_data,
      96           0 :     .dataend = account_data + account_data_len,
      97           0 :   };
      98             : 
      99           0 :   fd_vote_state_versioned_t * vsv = fd_vote_state_versioned_decode( buf, &ctx );
     100           0 :   if( FD_UNLIKELY( vsv==NULL ) ) {
     101           0 :     FD_LOG_CRIT(( "unable to decode vote state versioned" ));
     102           0 :   }
     103             : 
     104           0 :   switch( vsv->discriminant ) {
     105           0 :   case fd_vote_state_versioned_enum_v0_23_5:
     106           0 :     *credits = vsv->inner.v0_23_5.epoch_credits;
     107           0 :     break;
     108           0 :   case fd_vote_state_versioned_enum_v1_14_11:
     109           0 :     *credits = vsv->inner.v1_14_11.epoch_credits;
     110           0 :     break;
     111           0 :   case fd_vote_state_versioned_enum_v3:
     112           0 :     *credits = vsv->inner.v3.epoch_credits;
     113           0 :     break;
     114           0 :   case fd_vote_state_versioned_enum_v4:
     115           0 :     *credits = vsv->inner.v4.epoch_credits;
     116           0 :     break;
     117           0 :   default:
     118           0 :     __builtin_unreachable();
     119           0 :   }
     120           0 : }
     121             : 
     122             : static void
     123             : calculate_stake_points_and_credits_recalculation( fd_stake_history_t const *     stake_history,
     124             :                                                   fd_stake_delegation_t const *  stake,
     125             :                                                   ulong *                        new_rate_activation_epoch,
     126             :                                                   fd_vote_state_credits_t *      recalc_vote_state_credits,
     127           0 :                                                   fd_calculated_stake_points_t * result ) {
     128           0 :   ulong credits_in_stake = stake->credits_observed;
     129           0 :   ulong credits_in_vote  = recalc_vote_state_credits->credits[ recalc_vote_state_credits->credits_cnt-1UL ];
     130             : 
     131             :   /* If the Vote account has less credits observed than the Stake account,
     132             :       something is wrong and we need to force an update.
     133             : 
     134             :       https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/points.rs#L142 */
     135           0 :   if( FD_UNLIKELY( credits_in_vote < credits_in_stake ) ) {
     136           0 :     result->points.ud = 0;
     137           0 :     result->new_credits_observed = credits_in_vote;
     138           0 :     result->force_credits_update_with_skipped_reward = 1;
     139           0 :     return;
     140           0 :   }
     141             : 
     142             :   /* If the Vote account has the same amount of credits observed as the
     143             :      Stake account, then the Vote account hasn't earned any credits and
     144             :      so there is nothing to update.
     145             : 
     146             :       https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/points.rs#L148 */
     147           0 :   if( FD_UNLIKELY( credits_in_vote == credits_in_stake ) ) {
     148           0 :     result->points.ud = 0;
     149           0 :     result->new_credits_observed = credits_in_vote;
     150           0 :     result->force_credits_update_with_skipped_reward = 0;
     151           0 :     return;
     152           0 :   }
     153             : 
     154             :   /* Calculate the points for each epoch credit */
     155           0 :   uint128 points               = 0;
     156           0 :   ulong   new_credits_observed = credits_in_stake;
     157           0 :   for( ulong i=0UL; i<recalc_vote_state_credits->credits_cnt; i++ ) {
     158             : 
     159           0 :     ulong final_epoch_credits   = recalc_vote_state_credits->credits[ i ];
     160           0 :     ulong initial_epoch_credits = recalc_vote_state_credits->prev_credits[ i ];
     161           0 :     uint128 earned_credits = 0;
     162           0 :     if( FD_LIKELY( credits_in_stake < initial_epoch_credits ) ) {
     163           0 :       earned_credits = (uint128)(final_epoch_credits - initial_epoch_credits);
     164           0 :     } else if( FD_UNLIKELY( credits_in_stake < final_epoch_credits ) ) {
     165           0 :       earned_credits = (uint128)(final_epoch_credits - new_credits_observed);
     166           0 :     }
     167             : 
     168           0 :     new_credits_observed = fd_ulong_max( new_credits_observed, final_epoch_credits );
     169             : 
     170           0 :     ulong stake_amount = fd_stake_activating_and_deactivating(
     171           0 :         stake,
     172           0 :         recalc_vote_state_credits->epoch[ i ],
     173           0 :         stake_history,
     174           0 :         new_rate_activation_epoch ).effective;
     175             : 
     176           0 :     points += (uint128)stake_amount * earned_credits;
     177             : 
     178           0 :   }
     179             : 
     180           0 :   result->points.ud = points;
     181           0 :   result->new_credits_observed = new_credits_observed;
     182           0 :   result->force_credits_update_with_skipped_reward = 0;
     183           0 : }
     184             : 
     185             : /* For a given stake and vote_state, calculate how many points were earned (credits * stake) and new value
     186             :    for credits_observed were the points paid
     187             : 
     188             :     https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/points.rs#L109 */
     189             : static void
     190             : calculate_stake_points_and_credits( fd_accdb_user_t *              accdb,
     191             :                                     fd_funk_txn_xid_t const *      xid,
     192             :                                     fd_stake_history_t const *     stake_history,
     193             :                                     fd_stake_delegation_t const *  stake,
     194             :                                     fd_vote_state_ele_t const *    vote_state,
     195             :                                     ulong *                        new_rate_activation_epoch,
     196           0 :                                     fd_calculated_stake_points_t * result ) {
     197             : 
     198           0 :   fd_accdb_ro_t vote_ro[1];
     199           0 :   if( FD_UNLIKELY( !fd_accdb_open_ro( accdb, vote_ro, xid, &vote_state->vote_account ) ) ) {
     200           0 :     FD_LOG_ERR(( "Unable to read vote account" ));
     201           0 :   }
     202             : 
     203           0 :   fd_vote_epoch_credits_t * epoch_credits = NULL;
     204             : 
     205           0 :   uchar __attribute__((aligned(FD_VOTE_STATE_VERSIONED_ALIGN))) buf[ FD_VOTE_STATE_VERSIONED_FOOTPRINT ];
     206             : 
     207           0 :   get_vote_credits( fd_accdb_ref_data_const( vote_ro ), fd_accdb_ref_data_sz( vote_ro ), buf, &epoch_credits );
     208           0 :   fd_accdb_close_ro( accdb, vote_ro );
     209             : 
     210           0 :   ulong credits_in_stake = stake->credits_observed;
     211           0 :   ulong credits_cnt      = deq_fd_vote_epoch_credits_t_cnt( epoch_credits );
     212           0 :   ulong credits_in_vote  = credits_cnt > 0UL ? deq_fd_vote_epoch_credits_t_peek_tail( epoch_credits )->credits : 0UL;
     213             : 
     214             :   /* If the Vote account has less credits observed than the Stake account,
     215             :       something is wrong and we need to force an update.
     216             : 
     217             :       https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/points.rs#L142 */
     218           0 :   if( FD_UNLIKELY( credits_in_vote < credits_in_stake ) ) {
     219           0 :     result->points.ud = 0;
     220           0 :     result->new_credits_observed = credits_in_vote;
     221           0 :     result->force_credits_update_with_skipped_reward = 1;
     222           0 :     return;
     223           0 :   }
     224             : 
     225             :   /* If the Vote account has the same amount of credits observed as the Stake account,
     226             :       then the Vote account hasn't earnt any credits and so there is nothing to update.
     227             : 
     228             :       https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/points.rs#L148 */
     229           0 :   if( FD_UNLIKELY( credits_in_vote == credits_in_stake ) ) {
     230           0 :     result->points.ud = 0;
     231           0 :     result->new_credits_observed = credits_in_vote;
     232           0 :     result->force_credits_update_with_skipped_reward = 0;
     233           0 :     return;
     234           0 :   }
     235             : 
     236             :   /* Calculate the points for each epoch credit */
     237           0 :   uint128 points               = 0;
     238           0 :   ulong   new_credits_observed = credits_in_stake;
     239           0 :   for( deq_fd_vote_epoch_credits_t_iter_t iter = deq_fd_vote_epoch_credits_t_iter_init( epoch_credits );
     240           0 :        !deq_fd_vote_epoch_credits_t_iter_done( epoch_credits, iter );
     241           0 :        iter = deq_fd_vote_epoch_credits_t_iter_next( epoch_credits, iter ) ) {
     242             : 
     243           0 :     fd_vote_epoch_credits_t * ele = deq_fd_vote_epoch_credits_t_iter_ele( epoch_credits, iter );
     244             : 
     245           0 :     ulong final_epoch_credits   = ele->credits;
     246           0 :     ulong initial_epoch_credits = ele->prev_credits;
     247           0 :     uint128 earned_credits = 0;
     248           0 :     if( FD_LIKELY( credits_in_stake < initial_epoch_credits ) ) {
     249           0 :       earned_credits = (uint128)(final_epoch_credits - initial_epoch_credits);
     250           0 :     } else if( FD_UNLIKELY( credits_in_stake < final_epoch_credits ) ) {
     251           0 :       earned_credits = (uint128)(final_epoch_credits - new_credits_observed);
     252           0 :     }
     253             : 
     254           0 :     new_credits_observed = fd_ulong_max( new_credits_observed, final_epoch_credits );
     255             : 
     256           0 :     ulong stake_amount = fd_stake_activating_and_deactivating(
     257           0 :         stake,
     258           0 :         ele->epoch,
     259           0 :         stake_history,
     260           0 :         new_rate_activation_epoch ).effective;
     261             : 
     262           0 :     points += (uint128)stake_amount * earned_credits;
     263             : 
     264           0 :   }
     265             : 
     266           0 :   result->points.ud = points;
     267           0 :   result->new_credits_observed = new_credits_observed;
     268           0 :   result->force_credits_update_with_skipped_reward = 0;
     269           0 : }
     270             : 
     271             : struct fd_commission_split {
     272             :   ulong voter_portion;
     273             :   ulong staker_portion;
     274             :   uint  is_split;
     275             : };
     276             : typedef struct fd_commission_split fd_commission_split_t;
     277             : 
     278             : /// returns commission split as (voter_portion, staker_portion, was_split) tuple
     279             : ///
     280             : /// if commission calculation is 100% one way or other, indicate with false for was_split
     281             : 
     282             : // https://github.com/anza-xyz/agave/blob/v2.0.1/sdk/program/src/vote/state/mod.rs#L543
     283             : void
     284             : fd_vote_commission_split( uchar                   commission,
     285             :                           ulong                   on,
     286           0 :                           fd_commission_split_t * result ) {
     287           0 :   uint commission_split = fd_uint_min( (uint)commission, 100 );
     288           0 :   result->is_split      = (commission_split != 0 && commission_split != 100);
     289             :   // https://github.com/anza-xyz/agave/blob/v2.0.1/sdk/program/src/vote/state/mod.rs#L545
     290           0 :   if( commission_split==0U ) {
     291           0 :     result->voter_portion  = 0;
     292           0 :     result->staker_portion = on;
     293           0 :     return;
     294           0 :   }
     295             :   // https://github.com/anza-xyz/agave/blob/v2.0.1/sdk/program/src/vote/state/mod.rs#L546
     296           0 :   if( commission_split==100U ) {
     297           0 :     result->voter_portion  = on;
     298           0 :     result->staker_portion = 0;
     299           0 :     return;
     300           0 :   }
     301             :   /* Note: order of operations may matter for int division. That's why I didn't make the
     302             :    * optimization of getting out the common calculations */
     303             : 
     304             :   // ... This is copied from the solana comments...
     305             :   //
     306             :   // Calculate mine and theirs independently and symmetrically instead
     307             :   // of using the remainder of the other to treat them strictly
     308             :   // equally. This is also to cancel the rewarding if either of the
     309             :   // parties should receive only fractional lamports, resulting in not
     310             :   // being rewarded at all. Thus, note that we intentionally discard
     311             :   // any residual fractional lamports.
     312             : 
     313             :   // https://github.com/anza-xyz/agave/blob/v2.0.1/sdk/program/src/vote/state/mod.rs#L548
     314           0 :   result->voter_portion =
     315           0 :       (ulong)((uint128)on * (uint128)commission_split / (uint128)100);
     316           0 :   result->staker_portion =
     317           0 :       (ulong)((uint128)on * (uint128)( 100 - commission_split ) / (uint128)100);
     318           0 : }
     319             : 
     320             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/rewards.rs#L33 */
     321             : static int
     322             : redeem_rewards( fd_accdb_user_t *               accdb,
     323             :                 fd_funk_txn_xid_t const *       xid,
     324             :                 fd_stake_history_t const *      stake_history,
     325             :                 fd_stake_delegation_t const *   stake,
     326             :                 fd_vote_state_ele_t const *     vote_state,
     327             :                 ulong                           rewarded_epoch,
     328             :                 ulong                           total_rewards,
     329             :                 uint128                         total_points,
     330             :                 ulong *                         new_rate_activation_epoch,
     331             :                 fd_vote_state_credits_t *       recalc_vote_state_credits,
     332           0 :                 fd_calculated_stake_rewards_t * result ) {
     333             : 
     334             :   /* The firedancer implementation of redeem_rewards inlines a lot of
     335             :      the helper functions that the Agave implementation uses.
     336             :      In Agave: redeem_rewards calls redeem_stake_rewards which calls
     337             :      calculate_stake_rewards. */
     338             : 
     339           0 :   fd_calculated_stake_points_t stake_points_result = {0};
     340           0 :   if( FD_LIKELY( !recalc_vote_state_credits ) ) {
     341           0 :     calculate_stake_points_and_credits(
     342           0 :       accdb,
     343           0 :       xid,
     344           0 :       stake_history,
     345           0 :       stake,
     346           0 :       vote_state,
     347           0 :       new_rate_activation_epoch,
     348           0 :       &stake_points_result );
     349           0 :   } else {
     350           0 :     calculate_stake_points_and_credits_recalculation(
     351           0 :       stake_history,
     352           0 :       stake,
     353           0 :       new_rate_activation_epoch,
     354           0 :       recalc_vote_state_credits,
     355           0 :       &stake_points_result );
     356           0 :   }
     357             : 
     358             :   // Drive credits_observed forward unconditionally when rewards are disabled
     359             :   // or when this is the stake's activation epoch
     360           0 :   if( total_rewards==0UL || stake->activation_epoch==rewarded_epoch ) {
     361           0 :       stake_points_result.force_credits_update_with_skipped_reward = 1;
     362           0 :   }
     363             : 
     364           0 :   if( stake_points_result.force_credits_update_with_skipped_reward ) {
     365           0 :     result->staker_rewards       = 0;
     366           0 :     result->voter_rewards        = 0;
     367           0 :     result->new_credits_observed = stake_points_result.new_credits_observed;
     368           0 :     return 0;
     369           0 :   }
     370           0 :   if( stake_points_result.points.ud==0 || total_points==0 ) {
     371           0 :     return 1;
     372           0 :   }
     373             : 
     374           0 :   uint128 rewards_u128;
     375           0 :   if( FD_UNLIKELY( __builtin_mul_overflow( stake_points_result.points.ud, (uint128)(total_rewards), &rewards_u128 ) ) )
     376           0 :     FD_LOG_ERR(( "Rewards intermediate calculation should fit within u128" ));
     377             : 
     378           0 :   FD_TEST( total_points );
     379           0 :   rewards_u128 /=  (uint128) total_points;
     380             : 
     381           0 :   if( FD_UNLIKELY( rewards_u128 > (uint128)ULONG_MAX ) )
     382           0 :     FD_LOG_ERR(( "Rewards should fit within u64" ));
     383             : 
     384           0 :   ulong rewards = (ulong)rewards_u128;
     385           0 :   if( rewards == 0 ) {
     386           0 :     return 1;
     387           0 :   }
     388             : 
     389           0 :   uchar commission = recalc_vote_state_credits ? recalc_vote_state_credits->commission : vote_state->commission;
     390           0 :   fd_commission_split_t split_result;
     391           0 :   fd_vote_commission_split( commission, rewards, &split_result );
     392           0 :   if( split_result.is_split && (split_result.voter_portion == 0 || split_result.staker_portion == 0) ) {
     393           0 :     return 1;
     394           0 :   }
     395             : 
     396           0 :   result->staker_rewards       = split_result.staker_portion;
     397           0 :   result->voter_rewards        = split_result.voter_portion;
     398           0 :   result->new_credits_observed = stake_points_result.new_credits_observed;
     399           0 :   return 0;
     400           0 : }
     401             : 
     402             : /* Returns the length of the given epoch in slots
     403             : 
     404             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/sdk/program/src/epoch_schedule.rs#L103 */
     405             : static ulong
     406             : get_slots_in_epoch( ulong                       epoch,
     407         102 :                     fd_epoch_schedule_t const * epoch_schedule ) {
     408         102 :   return epoch < epoch_schedule->first_normal_epoch ?
     409           0 :          1UL << fd_ulong_sat_add( epoch, FD_EPOCH_LEN_MIN_TRAILING_ZERO ) :
     410         102 :          epoch_schedule->slots_per_epoch;
     411         102 : }
     412             : 
     413             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank.rs#L2082 */
     414             : static double
     415             : epoch_duration_in_years( fd_bank_t const * bank,
     416          45 :                          ulong             prev_epoch ) {
     417          45 :   ulong slots_in_epoch = get_slots_in_epoch( prev_epoch, fd_bank_epoch_schedule_query( bank ) );
     418          45 :   return (double)slots_in_epoch / (double)fd_bank_slots_per_year_get( bank );
     419          45 : }
     420             : 
     421             : /* https://github.com/anza-xyz/agave/blob/7117ed9653ce19e8b2dea108eff1f3eb6a3378a7/runtime/src/bank.rs#L2128 */
     422             : static void
     423             : calculate_previous_epoch_inflation_rewards( fd_bank_t const *                   bank,
     424             :                                             ulong                               prev_epoch_capitalization,
     425             :                                             ulong                               prev_epoch,
     426          45 :                                             fd_prev_epoch_inflation_rewards_t * rewards ) {
     427          45 :   double slot_in_year = slot_in_year_for_inflation( bank );
     428             : 
     429          45 :   rewards->validator_rate               = validator( fd_bank_inflation_query( bank ), slot_in_year );
     430          45 :   rewards->foundation_rate              = foundation( fd_bank_inflation_query( bank ), slot_in_year );
     431          45 :   rewards->prev_epoch_duration_in_years = epoch_duration_in_years( bank, prev_epoch );
     432          45 :   rewards->validator_rewards            = (ulong)(rewards->validator_rate * (double)prev_epoch_capitalization * rewards->prev_epoch_duration_in_years);
     433          45 :   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 ));
     434          45 : }
     435             : 
     436             : /* https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/programs/stake/src/lib.rs#L29 */
     437             : static ulong
     438          90 : get_minimum_stake_delegation( fd_bank_t * bank ) {
     439          90 :   if( !FD_FEATURE_ACTIVE_BANK( bank, stake_minimum_delegation_for_rewards ) ) {
     440          36 :     return 0UL;
     441          36 :   }
     442             : 
     443          54 :   if( FD_FEATURE_ACTIVE_BANK( bank, stake_raise_minimum_delegation_to_1_sol ) ) {
     444          54 :     return LAMPORTS_PER_SOL;
     445          54 :   }
     446             : 
     447           0 :   return 1;
     448          54 : }
     449             : 
     450             : /* Calculates epoch reward points from stake/vote accounts.
     451             :    https://github.com/anza-xyz/agave/blob/v2.3.1/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L445 */
     452             : static uint128
     453             : calculate_reward_points_partitioned( fd_bank_t *                    bank,
     454             :                                      fd_accdb_user_t *              accdb,
     455             :                                      fd_funk_txn_xid_t const *      xid,
     456             :                                      fd_stake_delegations_t const * stake_delegations,
     457          45 :                                      fd_stake_history_t const *     stake_history ) {
     458          45 :   ulong minimum_stake_delegation = get_minimum_stake_delegation( bank );
     459             : 
     460             :   /* Calculate the points for each stake delegation */
     461          45 :   int _err[1];
     462          45 :   ulong   new_warmup_cooldown_rate_epoch_val = 0UL;
     463          45 :   ulong * new_warmup_cooldown_rate_epoch     = &new_warmup_cooldown_rate_epoch_val;
     464          45 :   int is_some = fd_new_warmup_cooldown_rate_epoch(
     465          45 :       fd_bank_epoch_schedule_query( bank ),
     466          45 :       fd_bank_features_query( bank ),
     467          45 :       new_warmup_cooldown_rate_epoch,
     468          45 :       _err );
     469          45 :   if( FD_UNLIKELY( !is_some ) ) {
     470           0 :     new_warmup_cooldown_rate_epoch = NULL;
     471           0 :   }
     472             : 
     473          45 :   uint128 total_points = 0;
     474             : 
     475          45 :   fd_vote_states_t const * vote_states = fd_bank_vote_states_locking_query( bank );
     476             : 
     477          45 :   fd_stake_delegations_iter_t iter_[1];
     478          45 :   for( fd_stake_delegations_iter_t * iter = fd_stake_delegations_iter_init( iter_, stake_delegations );
     479          45 :        !fd_stake_delegations_iter_done( iter );
     480          45 :        fd_stake_delegations_iter_next( iter ) ) {
     481           0 :     fd_stake_delegation_t const * stake_delegation = fd_stake_delegations_iter_ele( iter );
     482             : 
     483           0 :     if( FD_UNLIKELY( stake_delegation->stake<minimum_stake_delegation ) ) {
     484           0 :       continue;
     485           0 :     }
     486             : 
     487           0 :     fd_vote_state_ele_t * vote_state_ele = fd_vote_states_query( vote_states, &stake_delegation->vote_account );
     488           0 :     if( FD_UNLIKELY( !vote_state_ele ) ) {
     489           0 :       continue;
     490           0 :     }
     491             : 
     492           0 :     fd_calculated_stake_points_t stake_point_result;
     493           0 :     calculate_stake_points_and_credits( accdb,
     494           0 :                                         xid,
     495           0 :                                         stake_history,
     496           0 :                                         stake_delegation,
     497           0 :                                         vote_state_ele,
     498           0 :                                         new_warmup_cooldown_rate_epoch,
     499           0 :                                         &stake_point_result );
     500           0 :     total_points += stake_point_result.points.ud;
     501           0 :   }
     502             : 
     503          45 :   fd_bank_vote_states_end_locking_query( bank );
     504             : 
     505          45 :   return total_points;
     506          45 : }
     507             : 
     508             : /* Calculates epoch rewards for stake/vote accounts.
     509             :    Returns vote rewards, stake rewards, and the sum of all stake rewards
     510             :    in lamports.
     511             : 
     512             :    In the future, the calculation will be cached in the snapshot, but
     513             :    for now we just re-calculate it (as Agave does).
     514             :    calculate_stake_vote_rewards is responsible for calculating
     515             :    stake account rewards based off of a combination of the
     516             :    stake delegation state as well as the vote account. If this
     517             :    calculation is done at the end of an epoch, we can just use the
     518             :    vote states at the end of the current epoch. However, because we
     519             :    are presumably booting up a node in the middle of rewards
     520             :    distribution, we need to make sure that we are using the vote
     521             :    states from the end of the previous epoch.
     522             : 
     523             :    https://github.com/anza-xyz/agave/blob/v2.3.1/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L323 */
     524             : static void
     525             : calculate_stake_vote_rewards( fd_bank_t *                    bank,
     526             :                               fd_accdb_user_t *              accdb,
     527             :                               fd_funk_txn_xid_t const *      xid,
     528             :                               fd_stake_delegations_t const * stake_delegations,
     529             :                               fd_capture_ctx_t *             capture_ctx FD_PARAM_UNUSED,
     530             :                               fd_stake_history_t const *     stake_history,
     531             :                               ulong                          rewarded_epoch,
     532             :                               ulong                          total_rewards,
     533             :                               uint128                        total_points,
     534          45 :                               fd_runtime_stack_t *           runtime_stack ) {
     535             : 
     536          45 :   int _err[1];
     537          45 :   ulong   new_warmup_cooldown_rate_epoch_val = 0UL;
     538          45 :   ulong * new_warmup_cooldown_rate_epoch     = &new_warmup_cooldown_rate_epoch_val;
     539          45 :   int is_some = fd_new_warmup_cooldown_rate_epoch(
     540          45 :       fd_bank_epoch_schedule_query( bank ),
     541          45 :       fd_bank_features_query( bank ),
     542          45 :       new_warmup_cooldown_rate_epoch,
     543          45 :       _err );
     544          45 :   if( FD_UNLIKELY( !is_some ) ) {
     545           0 :     new_warmup_cooldown_rate_epoch = NULL;
     546           0 :   }
     547             : 
     548          45 :   ulong minimum_stake_delegation = get_minimum_stake_delegation( bank );
     549             : 
     550          45 :   fd_vote_states_t * vote_states = fd_bank_vote_states_locking_modify( bank );
     551             : 
     552          45 :   fd_epoch_rewards_t * epoch_rewards = fd_bank_epoch_rewards_modify( bank );
     553          45 :   fd_epoch_rewards_init( epoch_rewards );
     554             : 
     555             :   /* Reset the vote rewards for each vote account. */
     556          45 :   fd_memset( runtime_stack->stakes.vote_rewards, 0UL, sizeof(runtime_stack->stakes.vote_rewards) );
     557             : 
     558          45 :   fd_stake_delegations_iter_t iter_[1];
     559          45 :   for( fd_stake_delegations_iter_t * iter = fd_stake_delegations_iter_init( iter_, stake_delegations );
     560          45 :        !fd_stake_delegations_iter_done( iter );
     561          45 :        fd_stake_delegations_iter_next( iter ) ) {
     562           0 :     fd_stake_delegation_t const * stake_delegation = fd_stake_delegations_iter_ele( iter );
     563             : 
     564           0 :     if( FD_FEATURE_ACTIVE_BANK( bank, stake_minimum_delegation_for_rewards ) ) {
     565           0 :       if( stake_delegation->stake<minimum_stake_delegation ) {
     566           0 :         continue;
     567           0 :       }
     568           0 :     }
     569             : 
     570           0 :     fd_pubkey_t const *   voter_acc      = &stake_delegation->vote_account;
     571           0 :     fd_vote_state_ele_t * vote_state_ele = fd_vote_states_query( vote_states, voter_acc );
     572           0 :     if( FD_UNLIKELY( !vote_state_ele ) ) continue;
     573             : 
     574           0 :     fd_vote_state_credits_t * recalc_credit = !!runtime_stack->stakes.prev_vote_credits_used ?
     575           0 :                                               &runtime_stack->stakes.vote_credits[ vote_state_ele->idx ] : NULL;
     576           0 :     if( recalc_credit && runtime_stack->stakes.vote_credits[ vote_state_ele->idx ].credits_cnt==0UL ) continue;
     577             : 
     578             :     /* redeem_rewards is actually just responsible for calculating the
     579             :        vote and stake rewards for each stake account.  It does not do
     580             :        rewards redemption: it is a misnomer. */
     581           0 :     fd_calculated_stake_rewards_t calculated_stake_rewards[1] = {0};
     582           0 :     int err = redeem_rewards(
     583           0 :         accdb,
     584           0 :         xid,
     585           0 :         stake_history,
     586           0 :         stake_delegation,
     587           0 :         vote_state_ele,
     588           0 :         rewarded_epoch,
     589           0 :         total_rewards,
     590           0 :         total_points,
     591           0 :         new_warmup_cooldown_rate_epoch,
     592           0 :         recalc_credit,
     593           0 :         calculated_stake_rewards );
     594             : 
     595           0 :     if( FD_UNLIKELY( err!=0 ) ) {
     596           0 :       continue;
     597           0 :     }
     598             : 
     599           0 :     if ( capture_ctx && capture_ctx->capture_solcap ) {
     600           0 :       uchar commission = runtime_stack->stakes.prev_vote_credits_used ? recalc_credit->commission : vote_state_ele->commission;
     601           0 :       fd_capture_link_write_stake_reward_event( capture_ctx,
     602           0 :                                                 fd_bank_slot_get( bank ),
     603           0 :                                                 stake_delegation->stake_account,
     604           0 :                                                 *voter_acc,
     605           0 :                                                 commission,
     606           0 :                                                 (long)calculated_stake_rewards->voter_rewards,
     607           0 :                                                 (long)calculated_stake_rewards->staker_rewards,
     608           0 :                                                 (long)calculated_stake_rewards->new_credits_observed );
     609           0 :     }
     610             : 
     611           0 :     runtime_stack->stakes.vote_rewards[ vote_state_ele->idx ] += calculated_stake_rewards->voter_rewards;
     612             : 
     613           0 :     fd_epoch_rewards_insert( epoch_rewards, &stake_delegation->stake_account, calculated_stake_rewards->new_credits_observed, calculated_stake_rewards->staker_rewards );
     614           0 :   }
     615             : 
     616          45 :   fd_bank_vote_states_end_locking_modify( bank );
     617          45 : }
     618             : 
     619             : /* Calculate epoch reward and return vote and stake rewards.
     620             : 
     621             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L273 */
     622             : static uint128
     623             : calculate_validator_rewards( fd_bank_t *                    bank,
     624             :                              fd_accdb_user_t *              accdb,
     625             :                              fd_funk_txn_xid_t const *      xid,
     626             :                              fd_runtime_stack_t *           runtime_stack,
     627             :                              fd_stake_delegations_t const * stake_delegations,
     628             :                              fd_capture_ctx_t *             capture_ctx,
     629             :                              ulong                          rewarded_epoch,
     630          45 :                              ulong *                        rewards_out ) {
     631             : 
     632          45 :   fd_stake_history_t stake_history[1];
     633          45 :   if( FD_UNLIKELY( !fd_sysvar_stake_history_read( accdb, xid, stake_history ) ) ) {
     634           0 :     FD_LOG_ERR(( "Unable to read and decode stake history sysvar" ));
     635           0 :   }
     636             : 
     637             :   /* Calculate the epoch reward points from stake/vote accounts */
     638          45 :   uint128 points = calculate_reward_points_partitioned(
     639          45 :       bank,
     640          45 :       accdb,
     641          45 :       xid,
     642          45 :       stake_delegations,
     643          45 :       stake_history );
     644             : 
     645             :   /* If there are no points, then we set the rewards to 0. */
     646          45 :   *rewards_out = points>0UL ? *rewards_out: 0UL;
     647             : 
     648          45 :   if( capture_ctx && capture_ctx->capture_solcap ) {
     649           0 :     ulong epoch = fd_bank_epoch_get( bank );
     650           0 :     ulong slot  = fd_bank_slot_get( bank );
     651           0 :     fd_capture_link_write_stake_rewards_begin( capture_ctx,
     652           0 :                                                slot,
     653           0 :                                                epoch,
     654           0 :                                                epoch-1UL, /* FIXME: this is not strictly correct */
     655           0 :                                                *rewards_out,
     656           0 :                                                (ulong)points );
     657           0 :   }
     658             : 
     659             :   /* Calculate the stake and vote rewards for each account. We want to
     660             :      use the vote states from the end of the current_epoch. */
     661          45 :   calculate_stake_vote_rewards(
     662          45 :       bank,
     663          45 :       accdb,
     664          45 :       xid,
     665          45 :       stake_delegations,
     666          45 :       capture_ctx,
     667          45 :       stake_history,
     668          45 :       rewarded_epoch,
     669          45 :       *rewards_out,
     670          45 :       points,
     671          45 :       runtime_stack );
     672             : 
     673          45 :   return points;
     674          45 : }
     675             : 
     676             : /* Calculate the number of blocks required to distribute rewards to all stake accounts.
     677             : 
     678             :     https://github.com/anza-xyz/agave/blob/9a7bf72940f4b3cd7fc94f54e005868ce707d53d/runtime/src/bank/partitioned_epoch_rewards/mod.rs#L214
     679             :  */
     680             : static ulong
     681             : get_reward_distribution_num_blocks( fd_epoch_schedule_t const * epoch_schedule,
     682             :                                     ulong                       slot,
     683          45 :                                     ulong                       total_stake_accounts ) {
     684             :   /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L1250-L1267 */
     685          45 :   if( epoch_schedule->warmup &&
     686          45 :       fd_slot_to_epoch( epoch_schedule, slot, NULL ) < epoch_schedule->first_normal_epoch ) {
     687           0 :     return 1UL;
     688           0 :   }
     689             : 
     690          45 :   ulong num_chunks = total_stake_accounts / (ulong)STAKE_ACCOUNT_STORES_PER_BLOCK + (total_stake_accounts % STAKE_ACCOUNT_STORES_PER_BLOCK != 0);
     691          45 :   num_chunks       = fd_ulong_max( num_chunks, 1UL );
     692          45 :   num_chunks       = fd_ulong_min( num_chunks,
     693          45 :                                    fd_ulong_max( epoch_schedule->slots_per_epoch / (ulong)MAX_FACTOR_OF_REWARD_BLOCKS_IN_EPOCH, 1UL ) );
     694          45 :   return num_chunks;
     695          45 : }
     696             : 
     697             : /* Calculate rewards from previous epoch to prepare for partitioned distribution.
     698             : 
     699             :    https://github.com/anza-xyz/agave/blob/v3.0.4/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L277 */
     700             : static void
     701             : calculate_rewards_for_partitioning( fd_bank_t *                            bank,
     702             :                                     fd_accdb_user_t *                      accdb,
     703             :                                     fd_funk_txn_xid_t const *              xid,
     704             :                                     fd_runtime_stack_t *                   runtime_stack,
     705             :                                     fd_stake_delegations_t const *         stake_delegations,
     706             :                                     fd_capture_ctx_t *                     capture_ctx,
     707             :                                     ulong                                  prev_epoch,
     708          45 :                                     fd_partitioned_rewards_calculation_t * result ) {
     709          45 :   fd_prev_epoch_inflation_rewards_t rewards;
     710             : 
     711          45 :   calculate_previous_epoch_inflation_rewards( bank,
     712          45 :                                               fd_bank_capitalization_get( bank ),
     713          45 :                                               prev_epoch,
     714          45 :                                               &rewards );
     715             : 
     716          45 :   ulong total_rewards = rewards.validator_rewards;
     717             : 
     718          45 :   uint128 points = calculate_validator_rewards( bank,
     719          45 :                                                 accdb,
     720          45 :                                                 xid,
     721          45 :                                                 runtime_stack,
     722          45 :                                                 stake_delegations,
     723          45 :                                                 capture_ctx,
     724          45 :                                                 prev_epoch,
     725          45 :                                                 &total_rewards );
     726             : 
     727             :   /* The agave client does not partition the stake rewards until the
     728             :      first distribution block.  We calculate the partitions during the
     729             :      boundary. */
     730          45 :   result->validator_points             = points;
     731          45 :   result->validator_rewards            = total_rewards;
     732          45 :   result->validator_rate               = rewards.validator_rate;
     733          45 :   result->foundation_rate              = rewards.foundation_rate;
     734          45 :   result->prev_epoch_duration_in_years = rewards.prev_epoch_duration_in_years;
     735          45 :   result->capitalization               = fd_bank_capitalization_get( bank );
     736          45 : }
     737             : 
     738             : /* Calculate rewards from previous epoch and distribute vote rewards
     739             :    https://github.com/anza-xyz/agave/blob/v3.0.4/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L148 */
     740             : static void
     741             : calculate_rewards_and_distribute_vote_rewards( fd_bank_t *                    bank,
     742             :                                                fd_accdb_user_t *              accdb,
     743             :                                                fd_funk_txn_xid_t const *      xid,
     744             :                                                fd_runtime_stack_t *           runtime_stack,
     745             :                                                fd_stake_delegations_t const * stake_delegations,
     746             :                                                fd_capture_ctx_t *             capture_ctx,
     747          45 :                                                ulong                          prev_epoch ) {
     748             : 
     749             :   /* First we must compute the stake and vote rewards for the just
     750             :      completed epoch.  We store the stake account rewards and vote
     751             :      states rewards in the bank */
     752             : 
     753          45 :   fd_partitioned_rewards_calculation_t rewards_calc_result[1] = {0};
     754          45 :   calculate_rewards_for_partitioning( bank,
     755          45 :                                       accdb,
     756          45 :                                       xid,
     757          45 :                                       runtime_stack,
     758          45 :                                       stake_delegations,
     759          45 :                                       capture_ctx,
     760          45 :                                       prev_epoch,
     761          45 :                                       rewards_calc_result );
     762             : 
     763          45 :   fd_vote_states_t const * vote_states = fd_bank_vote_states_locking_query( bank );
     764             : 
     765             :   /* Iterate over all the vote reward nodes and distribute the rewards
     766             :      to the vote accounts.  After each reward has been paid out,
     767             :      calcualte the lthash for each vote account. */
     768          45 :   ulong distributed_rewards = 0UL;
     769          45 :   fd_vote_states_iter_t iter_[1];
     770          45 :   for( fd_vote_states_iter_t * iter = fd_vote_states_iter_init( iter_, vote_states );
     771          45 :        !fd_vote_states_iter_done( iter );
     772          45 :        fd_vote_states_iter_next( iter ) ) {
     773           0 :     fd_vote_state_ele_t * vote_state = fd_vote_states_iter_ele( iter );
     774             : 
     775           0 :     ulong rewards = runtime_stack->stakes.vote_rewards[ vote_state->idx ];
     776           0 :     if( rewards==0UL ) {
     777           0 :       continue;
     778           0 :     }
     779             : 
     780             :     /* Credit rewards to vote account (creating a new system account if
     781             :        it does not exist) */
     782           0 :     fd_pubkey_t const * vote_pubkey = &vote_state->vote_account;
     783           0 :     fd_accdb_rw_t rw[1];
     784           0 :     fd_accdb_open_rw( accdb, rw, xid, vote_pubkey, 0UL, FD_ACCDB_FLAG_CREATE );
     785           0 :     fd_lthash_value_t prev_hash[1];
     786           0 :     fd_hashes_account_lthash( vote_pubkey, rw->meta, fd_accdb_ref_data_const( rw->ro ), prev_hash );
     787           0 :     ulong acc_lamports = fd_accdb_ref_lamports( rw->ro );
     788           0 :     if( FD_UNLIKELY( __builtin_uaddl_overflow( acc_lamports, rewards, &acc_lamports ) ) ) {
     789           0 :       FD_BASE58_ENCODE_32_BYTES( vote_pubkey->key, addr_b58 );
     790           0 :       FD_LOG_EMERG(( "integer overflow while crediting %lu vote reward lamports to %s (previous balance %lu)",
     791           0 :                      rewards, addr_b58, fd_accdb_ref_lamports( rw->ro ) ));
     792           0 :     }
     793           0 :     fd_accdb_ref_lamports_set( rw, acc_lamports );
     794           0 :     fd_hashes_update_lthash( vote_pubkey, rw->meta, prev_hash,bank, capture_ctx );
     795           0 :     fd_accdb_close_rw( accdb, rw );
     796             : 
     797           0 :     distributed_rewards = fd_ulong_sat_add( distributed_rewards, rewards );
     798           0 :   }
     799             : 
     800          45 :   fd_bank_vote_states_end_locking_query( bank );
     801             : 
     802             :   /* Verify that we didn't pay any more than we expected to */
     803          45 :   fd_epoch_rewards_t * epoch_rewards = fd_bank_epoch_rewards_modify( bank );
     804             : 
     805          45 :   ulong total_rewards = fd_ulong_sat_add( distributed_rewards, epoch_rewards->total_stake_rewards );
     806          45 :   if( FD_UNLIKELY( rewards_calc_result->validator_rewards<total_rewards ) ) {
     807           0 :     FD_LOG_CRIT(( "Unexpected rewards calculation result" ));
     808           0 :   }
     809             : 
     810          45 :   fd_bank_capitalization_set( bank, fd_bank_capitalization_get( bank ) + distributed_rewards );
     811             : 
     812          45 :   epoch_rewards->distributed_rewards = distributed_rewards;
     813          45 :   epoch_rewards->total_rewards       = rewards_calc_result->validator_rewards;
     814          45 :   epoch_rewards->total_points.ud     = rewards_calc_result->validator_points;
     815          45 : }
     816             : 
     817             : /* Distributes a single partitioned reward to a single stake account */
     818             : static int
     819             : distribute_epoch_reward_to_stake_acc( fd_bank_t *               bank,
     820             :                                       fd_accdb_user_t *         accdb,
     821             :                                       fd_funk_txn_xid_t const * xid,
     822             :                                       fd_capture_ctx_t *        capture_ctx,
     823             :                                       fd_pubkey_t *             stake_pubkey,
     824             :                                       ulong                     reward_lamports,
     825           0 :                                       ulong                     new_credits_observed ) {
     826             : 
     827           0 :   fd_accdb_rw_t rw[1];
     828           0 :   if( FD_UNLIKELY( !fd_accdb_open_rw( accdb, rw, xid, stake_pubkey, 0UL, 0 ) ) ) {
     829           0 :     return 1;  /* account does not exist */
     830           0 :   }
     831             : 
     832           0 :   fd_lthash_value_t prev_hash[1];
     833           0 :   fd_hashes_account_lthash( stake_pubkey, rw->meta, fd_accdb_ref_data_const( rw->ro ), prev_hash );
     834           0 :   fd_stake_state_v2_t stake_state[1] = {0};
     835           0 :   if( 0!=fd_stake_get_state( rw->meta, stake_state ) ||
     836           0 :       !fd_stake_state_v2_is_stake( stake_state ) ) {
     837           0 :     fd_accdb_close_rw( accdb, rw );
     838           0 :     return 1;  /* not a valid stake account */
     839           0 :   }
     840             : 
     841             :   /* Credit rewards to stake account */
     842           0 :   ulong acc_lamports = fd_accdb_ref_lamports( rw->ro );
     843           0 :   if( FD_UNLIKELY( __builtin_uaddl_overflow( acc_lamports, reward_lamports, &acc_lamports ) ) ) {
     844           0 :     FD_BASE58_ENCODE_32_BYTES( stake_pubkey->key, addr_b58 );
     845           0 :     FD_LOG_EMERG(( "integer overflow while crediting %lu stake reward lamports to %s (previous balance %lu)",
     846           0 :                     reward_lamports, addr_b58, fd_accdb_ref_lamports( rw->ro ) ));
     847           0 :   }
     848           0 :   fd_accdb_ref_lamports_set( rw, acc_lamports );
     849             : 
     850           0 :   ulong old_credits_observed                      = stake_state->inner.stake.stake.credits_observed;
     851           0 :   stake_state->inner.stake.stake.credits_observed = new_credits_observed;
     852           0 :   stake_state->inner.stake.stake.delegation.stake = fd_ulong_sat_add( stake_state->inner.stake.stake.delegation.stake,
     853           0 :                                                                       reward_lamports );
     854             : 
     855             :   /* The stake account has just been updated, so we need to update the
     856             :      stake delegations stored in the bank. */
     857           0 :   fd_stake_delegations_t * stake_delegations = fd_bank_stake_delegations_delta_locking_modify( bank );
     858           0 :   fd_stake_delegations_update(
     859           0 :       stake_delegations,
     860           0 :       stake_pubkey,
     861           0 :       &stake_state->inner.stake.stake.delegation.voter_pubkey,
     862           0 :       stake_state->inner.stake.stake.delegation.stake,
     863           0 :       stake_state->inner.stake.stake.delegation.activation_epoch,
     864           0 :       stake_state->inner.stake.stake.delegation.deactivation_epoch,
     865           0 :       stake_state->inner.stake.stake.credits_observed,
     866           0 :       stake_state->inner.stake.stake.delegation.warmup_cooldown_rate );
     867           0 :   fd_bank_stake_delegations_delta_end_locking_modify( bank );
     868             : 
     869           0 :   if( capture_ctx && capture_ctx->capture_solcap ) {
     870           0 :     fd_capture_link_write_stake_account_payout( capture_ctx,
     871           0 :                                                 fd_bank_slot_get( bank ),
     872           0 :                                                 *stake_pubkey,
     873           0 :                                                 fd_bank_slot_get( bank ),
     874           0 :                                                 acc_lamports,
     875           0 :                                                 (long)reward_lamports,
     876           0 :                                                 new_credits_observed,
     877           0 :                                                 (long)( new_credits_observed - old_credits_observed ),
     878           0 :                                                 stake_state->inner.stake.stake.delegation.stake,
     879           0 :                                                 (long)reward_lamports );
     880           0 :   }
     881             : 
     882           0 :   fd_bincode_encode_ctx_t ctx = { .data=fd_accdb_ref_data( rw ), .dataend=(uchar *)fd_accdb_ref_data( rw )+fd_accdb_ref_data_sz( rw->ro ) };
     883           0 :   if( FD_UNLIKELY( fd_stake_state_v2_encode( stake_state, &ctx )!=FD_BINCODE_SUCCESS ) ) {
     884           0 :     FD_LOG_ERR(( "fd_stake_state_encode failed" ));
     885           0 :   }
     886             : 
     887           0 :   fd_hashes_update_lthash( stake_pubkey, rw->meta, prev_hash, bank, capture_ctx );
     888           0 :   fd_accdb_close_rw( accdb, rw );
     889             : 
     890           0 :   return 0;
     891           0 : }
     892             : 
     893             : /* Process reward credits for a partition of rewards.  Store the rewards
     894             :    to AccountsDB, update reward history record and total capitalization
     895             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/distribution.rs#L88 */
     896             : static void
     897             : distribute_epoch_rewards_in_partition( fd_epoch_rewards_t const * epoch_rewards,
     898             :                                        ulong                      partition_idx,
     899             :                                        fd_bank_t *                bank,
     900             :                                        fd_accdb_user_t *          accdb,
     901             :                                        fd_funk_txn_xid_t const *  xid,
     902           0 :                                        fd_capture_ctx_t *         capture_ctx ) {
     903             : 
     904           0 :   ulong lamports_distributed = 0UL;
     905           0 :   ulong lamports_burned      = 0UL;
     906             : 
     907           0 :   fd_epoch_rewards_iter_t iter_[1];
     908           0 :   for( fd_epoch_rewards_iter_t * iter = fd_epoch_rewards_iter_init( iter_, epoch_rewards, partition_idx );
     909           0 :        !fd_epoch_rewards_iter_done( iter );
     910           0 :        fd_epoch_rewards_iter_next( iter ) ) {
     911           0 :     fd_epoch_stake_reward_t * stake_reward = fd_epoch_rewards_iter_ele( iter );
     912             : 
     913           0 :     if( FD_LIKELY( !distribute_epoch_reward_to_stake_acc( bank,
     914           0 :                                                           accdb,
     915           0 :                                                           xid,
     916           0 :                                                           capture_ctx,
     917           0 :                                                           &stake_reward->stake_pubkey,
     918           0 :                                                           stake_reward->lamports,
     919           0 :                                                           stake_reward->credits_observed ) )  ) {
     920           0 :       lamports_distributed += stake_reward->lamports;
     921           0 :     } else {
     922           0 :       lamports_burned += stake_reward->lamports;
     923           0 :     }
     924           0 :   }
     925             : 
     926             :   /* Update the epoch rewards sysvar with the amount distributed and burnt */
     927           0 :   fd_sysvar_epoch_rewards_distribute( bank, accdb, xid, capture_ctx, lamports_distributed + lamports_burned );
     928             : 
     929           0 :   FD_LOG_DEBUG(( "lamports burned: %lu, lamports distributed: %lu", lamports_burned, lamports_distributed ));
     930             : 
     931           0 :   fd_bank_capitalization_set( bank, fd_bank_capitalization_get( bank ) + lamports_distributed );
     932           0 : }
     933             : 
     934             : /* Process reward distribution for the block if it is inside reward interval.
     935             : 
     936             :    https://github.com/anza-xyz/agave/blob/cbc8320d35358da14d79ebcada4dfb6756ffac79/runtime/src/bank/partitioned_epoch_rewards/distribution.rs#L42 */
     937             : void
     938             : fd_distribute_partitioned_epoch_rewards( fd_bank_t *               bank,
     939             :                                          fd_accdb_user_t *         accdb,
     940             :                                          fd_funk_txn_xid_t const * xid,
     941          63 :                                          fd_capture_ctx_t *        capture_ctx ) {
     942             : 
     943          63 :   fd_epoch_rewards_t const * epoch_rewards = fd_bank_epoch_rewards_query( bank );
     944          63 :   if( FD_LIKELY( !epoch_rewards ) ) {
     945           6 :     return;
     946           6 :   }
     947             : 
     948          57 :   ulong block_height = fd_bank_block_height_get( bank );
     949          57 :   ulong distribution_starting_block_height = epoch_rewards->starting_block_height;
     950          57 :   ulong distribution_end_exclusive         = fd_epoch_rewards_get_exclusive_ending_block_height( epoch_rewards );
     951             : 
     952          57 :   fd_epoch_schedule_t const * epoch_schedule = fd_bank_epoch_schedule_query( bank );
     953          57 :   ulong                       epoch          = fd_bank_epoch_get( bank );
     954             : 
     955          57 :   if( FD_UNLIKELY( get_slots_in_epoch( epoch, epoch_schedule ) <= epoch_rewards->num_partitions ) ) {
     956           0 :     FD_LOG_CRIT(( "Should not be distributing rewards" ));
     957           0 :   }
     958             : 
     959          57 :   if( FD_UNLIKELY( block_height>=distribution_starting_block_height && block_height<distribution_end_exclusive ) ) {
     960             : 
     961           0 :     ulong partition_idx = block_height-distribution_starting_block_height;
     962           0 :     distribute_epoch_rewards_in_partition( epoch_rewards, partition_idx, bank, accdb, xid, capture_ctx );
     963             : 
     964             :     /* If we have finished distributing rewards, set the status to inactive */
     965           0 :     if( fd_ulong_sat_add( block_height, 1UL )>=distribution_end_exclusive ) {
     966           0 :       fd_sysvar_epoch_rewards_set_inactive( bank, accdb, xid, capture_ctx );
     967           0 :     }
     968           0 :   }
     969          57 : }
     970             : 
     971             : /* Partitioned epoch rewards entry-point.
     972             : 
     973             :    https://github.com/anza-xyz/agave/blob/v3.0.4/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L102
     974             : */
     975             : void
     976             : fd_begin_partitioned_rewards( fd_bank_t *                    bank,
     977             :                               fd_accdb_user_t *              accdb,
     978             :                               fd_funk_txn_xid_t const *      xid,
     979             :                               fd_runtime_stack_t *           runtime_stack,
     980             :                               fd_capture_ctx_t *             capture_ctx,
     981             :                               fd_stake_delegations_t const * stake_delegations,
     982             :                               fd_hash_t const *              parent_blockhash,
     983          45 :                               ulong                          parent_epoch ) {
     984             : 
     985          45 :   calculate_rewards_and_distribute_vote_rewards(
     986          45 :       bank,
     987          45 :       accdb,
     988          45 :       xid,
     989          45 :       runtime_stack,
     990          45 :       stake_delegations,
     991          45 :       capture_ctx,
     992          45 :       parent_epoch );
     993             : 
     994             :   /* Once the rewards for vote accounts have been distributed and stake
     995             :      account rewards have been calculated, we can now set our epoch
     996             :      reward status to be active and we can initialize the epoch rewards
     997             :      sysvar.  This sysvar is then deleted once all of the partitioned
     998             :      stake rewards have been distributed.
     999             : 
    1000             :      The Agave client calculates the partitions for each stake reward
    1001             :      when the first distribution block is reached.  The Firedancer
    1002             :      client differs here since we hash the partitions during the epoch
    1003             :      boundary. */
    1004             : 
    1005          45 :   fd_epoch_schedule_t const * epoch_schedule = fd_bank_epoch_schedule_query( bank );
    1006          45 :   fd_epoch_rewards_t *        epoch_rewards  = fd_epoch_rewards_join( fd_bank_epoch_rewards_modify( bank ) );
    1007             : 
    1008          45 :   ulong num_partitions = get_reward_distribution_num_blocks(
    1009          45 :       epoch_schedule,
    1010          45 :       fd_bank_slot_get( bank ),
    1011          45 :       epoch_rewards->stake_rewards_cnt );
    1012             : 
    1013          45 :   fd_epoch_rewards_hash_into_partitions( epoch_rewards, parent_blockhash, num_partitions );
    1014             : 
    1015          45 :   ulong distribution_starting_block_height = fd_bank_block_height_get( bank ) + REWARD_CALCULATION_NUM_BLOCKS;
    1016             : 
    1017          45 :   epoch_rewards->starting_block_height = distribution_starting_block_height;
    1018             : 
    1019          45 :   fd_sysvar_epoch_rewards_init(
    1020          45 :       bank,
    1021          45 :       accdb,
    1022          45 :       xid,
    1023          45 :       capture_ctx,
    1024          45 :       epoch_rewards->distributed_rewards,
    1025          45 :       distribution_starting_block_height,
    1026          45 :       epoch_rewards->num_partitions,
    1027          45 :       epoch_rewards->total_rewards,
    1028          45 :       epoch_rewards->total_points.ud,
    1029          45 :       parent_blockhash );
    1030          45 : }
    1031             : 
    1032             : /*
    1033             :     Re-calculates partitioned stake rewards.
    1034             :     This updates the slot context's epoch reward status with the recalculated partitioned rewards.
    1035             : 
    1036             :     https://github.com/anza-xyz/agave/blob/v2.2.14/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L521 */
    1037             : void
    1038             : fd_rewards_recalculate_partitioned_rewards( fd_banks_t *              banks,
    1039             :                                             fd_bank_t *               bank,
    1040             :                                             fd_accdb_user_t *         accdb,
    1041             :                                             fd_funk_txn_xid_t const * xid,
    1042             :                                             fd_runtime_stack_t *      runtime_stack,
    1043           0 :                                             fd_capture_ctx_t *        capture_ctx ) {
    1044             : 
    1045           0 :   fd_sysvar_epoch_rewards_t epoch_rewards_sysvar[1];
    1046           0 :   if( FD_UNLIKELY( !fd_sysvar_epoch_rewards_read( accdb, xid, epoch_rewards_sysvar ) ) ) {
    1047           0 :     FD_LOG_DEBUG(( "Failed to read or decode epoch rewards sysvar - may not have been created yet" ));
    1048           0 :     return;
    1049           0 :   }
    1050             : 
    1051           0 :   FD_LOG_DEBUG(( "recalculating partitioned rewards" ));
    1052             : 
    1053           0 :   if( FD_UNLIKELY( !epoch_rewards_sysvar->active ) ) {
    1054           0 :     FD_LOG_DEBUG(( "epoch rewards is inactive" ));
    1055           0 :     return;
    1056           0 :   }
    1057             : 
    1058             :   /* If partitioned rewards are active, the rewarded epoch is always the immediately
    1059             :       preceeding epoch.
    1060             : 
    1061             :       https://github.com/anza-xyz/agave/blob/2316fea4c0852e59c071f72d72db020017ffd7d0/runtime/src/bank/partitioned_epoch_rewards/calculation.rs#L566 */
    1062           0 :   FD_LOG_DEBUG(( "epoch rewards is active" ));
    1063           0 :   runtime_stack->stakes.prev_vote_credits_used = 1;
    1064             : 
    1065           0 :   ulong const epoch          = fd_bank_epoch_get( bank );
    1066           0 :   ulong const rewarded_epoch = fd_ulong_sat_sub( epoch, 1UL );
    1067             : 
    1068           0 :   int _err[1] = {0};
    1069           0 :   ulong new_warmup_cooldown_rate_epoch_;
    1070           0 :   ulong * new_warmup_cooldown_rate_epoch = &new_warmup_cooldown_rate_epoch_;
    1071           0 :   int is_some = fd_new_warmup_cooldown_rate_epoch(
    1072           0 :       fd_bank_epoch_schedule_query( bank ),
    1073           0 :       fd_bank_features_query( bank ),
    1074           0 :       new_warmup_cooldown_rate_epoch,
    1075           0 :       _err );
    1076           0 :   if( FD_UNLIKELY( !is_some ) ) {
    1077           0 :     new_warmup_cooldown_rate_epoch = NULL;
    1078           0 :   }
    1079             : 
    1080           0 :   fd_stake_history_t stake_history[1];
    1081           0 :   if( FD_UNLIKELY( !fd_sysvar_stake_history_read( accdb, xid, stake_history ) ) ) {
    1082           0 :     FD_LOG_ERR(( "Unable to read and decode stake history sysvar" ));
    1083           0 :   }
    1084             : 
    1085           0 :   fd_stake_delegations_t const * stake_delegations = fd_bank_stake_delegations_frontier_query( banks, bank );
    1086           0 :   if( FD_UNLIKELY( !stake_delegations ) ) {
    1087           0 :     FD_LOG_CRIT(( "stake_delegations is NULL" ));
    1088           0 :   }
    1089             : 
    1090             :   /* Make sure is_recalculation is ==1 since we are booting up in the
    1091             :       middle of rewards distribution (so we should use the epoch
    1092             :       stakes for the end of epoch E-1 since we are still distributing
    1093             :       rewards for the previous epoch). */
    1094           0 :   calculate_stake_vote_rewards(
    1095           0 :       bank,
    1096           0 :       accdb,
    1097           0 :       xid,
    1098           0 :       stake_delegations,
    1099           0 :       capture_ctx,
    1100           0 :       stake_history,
    1101           0 :       rewarded_epoch,
    1102           0 :       epoch_rewards_sysvar->total_rewards,
    1103           0 :       epoch_rewards_sysvar->total_points.ud,
    1104           0 :       runtime_stack );
    1105             : 
    1106           0 :   fd_epoch_rewards_t * epoch_rewards = fd_epoch_rewards_join( fd_bank_epoch_rewards_modify( bank ) );
    1107           0 :   fd_epoch_rewards_hash_into_partitions( epoch_rewards, &epoch_rewards_sysvar->parent_blockhash, epoch_rewards_sysvar->num_partitions );
    1108             : 
    1109             :   /* Update the epoch reward status with the newly re-calculated partitions. */
    1110           0 :   epoch_rewards->starting_block_height = epoch_rewards_sysvar->distribution_starting_block_height;
    1111             : 
    1112           0 :   runtime_stack->stakes.prev_vote_credits_used = 0;
    1113           0 : }

Generated by: LCOV version 1.14