LCOV - code coverage report
Current view: top level - flamenco/runtime - fd_runtime.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 985 1300 75.8 %
Date: 2026-11-07 04:26:39 Functions: 52 59 88.1 %

          Line data    Source code
       1             : #include "fd_runtime.h"
       2             : #include "fd_bank.h"
       3             : #include "../events/fd_event_runtime.h"
       4             : 
       5             : #include "../types/fd_cast.h"
       6             : #include "fd_alut.h"
       7             : #include "fd_executor.h"
       8             : #include "fd_hashes.h"
       9             : #include "fd_runtime_stack.h"
      10             : #include "fd_accdb_svm.h"
      11             : #include "../genesis/fd_genesis_parse.h"
      12             : #include "fd_txncache.h"
      13             : #include "fd_compute_budget_details.h"
      14             : #include "program/fd_compute_budget_program.h"
      15             : #include "tests/fd_dump_pb.h"
      16             : 
      17             : #include "fd_system_ids.h"
      18             : #include "sysvar/fd_sysvar.h"
      19             : #include "sysvar/fd_sysvar_clock.h"
      20             : #include "sysvar/fd_sysvar_epoch_schedule.h"
      21             : #include "sysvar/fd_sysvar_recent_hashes.h"
      22             : #include "sysvar/fd_sysvar_stake_history.h"
      23             : #include "sysvar/fd_sysvar_last_restart_slot.h"
      24             : #include "sysvar/fd_sysvar_slot_hashes.h"
      25             : #include "sysvar/fd_sysvar_slot_history.h"
      26             : 
      27             : #include "../stakes/fd_stakes.h"
      28             : #include "../rewards/fd_rewards.h"
      29             : 
      30             : #include "program/fd_precompiles.h"
      31             : #include "program/vote/fd_vote_state_versioned.h"
      32             : 
      33             : FD_STATIC_ASSERT( MAX_STAKE_WEIGHTS==FD_RUNTIME_MAX_VAT_VOTE_ACCOUNTS, vat_stake_weights );
      34             : 
      35             : /*
      36             :    https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/bank.rs#L1254-L1258
      37             :    https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/bank.rs#L1749
      38             :  */
      39             : int
      40             : fd_runtime_compute_max_tick_height( ulong   ticks_per_slot,
      41             :                                     ulong   slot,
      42           0 :                                     ulong * out_max_tick_height /* out */ ) {
      43           0 :   ulong max_tick_height = 0UL;
      44           0 :   if( FD_LIKELY( ticks_per_slot > 0UL ) ) {
      45           0 :     ulong next_slot = fd_ulong_sat_add( slot, 1UL );
      46           0 :     if( FD_UNLIKELY( next_slot == slot ) ) {
      47           0 :       FD_LOG_WARNING(( "max tick height addition overflowed slot %lu ticks_per_slot %lu", slot, ticks_per_slot ));
      48           0 :       return -1;
      49           0 :     }
      50           0 :     if( FD_UNLIKELY( ULONG_MAX / ticks_per_slot < next_slot ) ) {
      51           0 :       FD_LOG_WARNING(( "max tick height multiplication overflowed slot %lu ticks_per_slot %lu", slot, ticks_per_slot ));
      52           0 :       return -1;
      53           0 :     }
      54           0 :     max_tick_height = fd_ulong_sat_mul( next_slot, ticks_per_slot );
      55           0 :   }
      56           0 :   *out_max_tick_height = max_tick_height;
      57           0 :   return FD_RUNTIME_EXECUTE_SUCCESS;
      58           0 : }
      59             : 
      60             : void
      61             : fd_runtime_update_next_leaders( fd_bank_t *          bank,
      62           0 :                                 fd_runtime_stack_t * runtime_stack ) {
      63             : 
      64           0 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
      65             : 
      66           0 :   ulong epoch    = fd_slot_to_epoch ( epoch_schedule, bank->f.slot, NULL ) + 1UL;
      67           0 :   ulong slot0    = fd_epoch_slot0   ( epoch_schedule, epoch );
      68           0 :   ulong slot_cnt = fd_epoch_slot_cnt( epoch_schedule, epoch );
      69           0 :   if( FD_UNLIKELY( slot_cnt>FD_RUNTIME_SLOTS_PER_EPOCH ) ) {
      70           0 :     FD_LOG_ERR(( "epoch %lu has %lu slots, but the maximum supported is %lu", epoch, slot_cnt, FD_RUNTIME_SLOTS_PER_EPOCH ));
      71           0 :   }
      72             : 
      73           0 :   fd_vote_stakes_t *       vote_stakes      = fd_bank_vote_stakes( bank );
      74           0 :   fd_vote_stake_weight_t * epoch_weights    = runtime_stack->stakes.stake_weights;
      75           0 :   ulong                    stake_weight_cnt = fd_stake_weights_by_node( vote_stakes, bank->vote_stakes_fork_id, FD_VOTE_STAKES_ITER_T_1, epoch_weights );
      76           0 :   FD_TEST( stake_weight_cnt<=MAX_STAKE_WEIGHTS );
      77             : 
      78           0 :   void * epoch_leaders_mem = fd_bank_epoch_leaders_modify( bank, epoch );
      79           0 :   fd_epoch_leaders_t * leaders = fd_epoch_leaders_join( fd_epoch_leaders_new(
      80           0 :       epoch_leaders_mem,
      81           0 :       epoch,
      82           0 :       slot0,
      83           0 :       slot_cnt,
      84           0 :       stake_weight_cnt,
      85           0 :       epoch_weights,
      86           0 :       fd_epoch_leaders_use_geo_aware( &bank->f.features, &bank->f.epoch_schedule, epoch ) ) );
      87           0 :   if( FD_UNLIKELY( !leaders ) ) {
      88           0 :     FD_LOG_ERR(( "Unable to init and join fd_epoch_leaders" ));
      89           0 :   }
      90             : 
      91           0 :   memcpy( runtime_stack->epoch_weights.next_stake_weights, epoch_weights, stake_weight_cnt*sizeof(fd_vote_stake_weight_t) );
      92           0 :   runtime_stack->epoch_weights.next_stake_weights_cnt = stake_weight_cnt;
      93             : 
      94           0 :   ulong staked_cnt = compute_id_weights_from_vote_weights( runtime_stack->stakes.id_weights, epoch_weights, stake_weight_cnt );
      95           0 :   FD_TEST( staked_cnt<=MAX_STAKE_WEIGHTS );
      96           0 :   memcpy( runtime_stack->epoch_weights.next_id_weights, runtime_stack->stakes.id_weights, staked_cnt * sizeof(fd_stake_weight_t) );
      97           0 :   runtime_stack->epoch_weights.next_id_weights_cnt = staked_cnt;
      98           0 : }
      99             : 
     100             : void
     101             : fd_runtime_update_leaders( fd_bank_t *          bank,
     102         318 :                            fd_runtime_stack_t * runtime_stack ) {
     103             : 
     104         318 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     105             : 
     106         318 :   ulong epoch    = fd_slot_to_epoch ( epoch_schedule, bank->f.slot, NULL );
     107         318 :   ulong slot0    = fd_epoch_slot0   ( epoch_schedule, epoch );
     108         318 :   ulong slot_cnt = fd_epoch_slot_cnt( epoch_schedule, epoch );
     109         318 :   if( FD_UNLIKELY( slot_cnt>FD_RUNTIME_SLOTS_PER_EPOCH ) ) {
     110           0 :     FD_LOG_ERR(( "epoch %lu has %lu slots, but the maximum supported is %lu", epoch, slot_cnt, FD_RUNTIME_SLOTS_PER_EPOCH ));
     111           0 :   }
     112             : 
     113         318 :   fd_vote_stakes_t *       vote_stakes      = fd_bank_vote_stakes( bank );
     114         318 :   fd_vote_stake_weight_t * epoch_weights    = runtime_stack->stakes.stake_weights;
     115         318 :   ulong                    stake_weight_cnt = fd_stake_weights_by_node( vote_stakes, bank->vote_stakes_fork_id, FD_VOTE_STAKES_ITER_T_2, epoch_weights );
     116         318 :   FD_TEST( stake_weight_cnt<=MAX_STAKE_WEIGHTS );
     117             : 
     118             :   /* TODO: Can optimize by avoiding recomputing if another fork has
     119             :      already computed them for this epoch. */
     120         318 :   void * epoch_leaders_mem = fd_bank_epoch_leaders_modify( bank, epoch );
     121         318 :   fd_epoch_leaders_t * leaders = fd_epoch_leaders_join( fd_epoch_leaders_new(
     122         318 :       epoch_leaders_mem,
     123         318 :       epoch,
     124         318 :       slot0,
     125         318 :       slot_cnt,
     126         318 :       stake_weight_cnt,
     127         318 :       epoch_weights,
     128         318 :       fd_epoch_leaders_use_geo_aware( &bank->f.features, &bank->f.epoch_schedule, epoch ) ) );
     129         318 :   if( FD_UNLIKELY( !leaders ) ) {
     130           0 :     FD_LOG_ERR(( "Unable to init and join fd_epoch_leaders" ));
     131           0 :   }
     132             : 
     133         318 :   memcpy( runtime_stack->epoch_weights.stake_weights, epoch_weights, stake_weight_cnt*sizeof(fd_vote_stake_weight_t) );
     134         318 :   runtime_stack->epoch_weights.stake_weights_cnt = stake_weight_cnt;
     135             : 
     136         318 :   ulong staked_cnt = compute_id_weights_from_vote_weights( runtime_stack->stakes.id_weights, epoch_weights, stake_weight_cnt );
     137         318 :   FD_TEST( staked_cnt<=MAX_STAKE_WEIGHTS );
     138         318 :   memcpy( runtime_stack->epoch_weights.id_weights, runtime_stack->stakes.id_weights, staked_cnt * sizeof(fd_stake_weight_t) );
     139         318 :   runtime_stack->epoch_weights.id_weights_cnt = staked_cnt;
     140         318 : }
     141             : 
     142             : /******************************************************************************/
     143             : /* Various Private Runtime Helpers                                            */
     144             : /******************************************************************************/
     145             : 
     146             : /* Validates the fee collector account before depositing fees.  Returns
     147             :    0 on success.  Returns 1 (fee is burned) if the fee collector is not
     148             :    owned by the system program, the deposit overflows the collector's
     149             :    balance, or the rent state transition is invalid.
     150             : 
     151             :    https://github.com/anza-xyz/agave/blob/v4.2.0-beta.2/runtime/src/bank/fee_distribution.rs#L205-L229 */
     152             : static int
     153             : fd_runtime_validate_fee_collector( fd_bank_t const * bank,
     154             :                                    fd_acc_t const *  collector,
     155          27 :                                    ulong             fee ) {
     156          27 :   FD_TEST( fee );
     157             : 
     158             :   /* https://github.com/anza-xyz/agave/blob/v4.2.0-beta.0/runtime/src/bank/fee_distribution.rs#L206-L208 */
     159          27 :   if( FD_UNLIKELY( memcmp( collector->owner, fd_solana_system_program_id.uc, sizeof(fd_pubkey_t) ) ) ) return 1;
     160             : 
     161             :   /* Lamport overflow burns the fee.
     162             :      https://github.com/anza-xyz/agave/blob/v4.2.0-beta.2/runtime/src/bank/fee_distribution.rs#L210-L214 */
     163          24 :   ulong pre_balance = collector->lamports;
     164          24 :   ulong post_balance;
     165          24 :   if( FD_UNLIKELY( __builtin_uaddl_overflow( pre_balance, fee, &post_balance ) ) ) return 1;
     166             : 
     167          21 :   return !!fd_executor_check_static_account_rent_state_transition(
     168          21 :     pre_balance,
     169          21 :     post_balance,
     170          21 :     collector->data_len,
     171          21 :     &bank->f.rent,
     172          21 :     FD_FEATURE_ACTIVE_BANK( bank, relax_post_exec_min_balance_check )
     173          21 :   );
     174          24 : }
     175             : 
     176             : /* Validates an external SIMD-0232 block revenue collector after the
     177             :    fee reward has been added.  Returns 0 to deposit, 1 to burn.  The
     178             :    vote account itself is always valid and must not be passed here.
     179             :    https://github.com/anza-xyz/agave/blob/v4.2.0-beta.1/runtime/src/bank/fee_distribution.rs#L231-L270 */
     180             : 
     181             : static int
     182             : fd_runtime_validate_block_revenue_collector( fd_bank_t const *   bank,
     183             :                                              fd_pubkey_t const * collector_id,
     184             :                                              ulong               pre_lamports,
     185         153 :                                              fd_acc_t const *    collector ) {
     186             :   /* Must be a system program owned account. */
     187         153 :   if( FD_UNLIKELY( memcmp( collector->owner, fd_solana_system_program_id.uc, sizeof(fd_pubkey_t) ) ) ) return 1;
     188             : 
     189             :   /* Must not be a reserved account. */
     190          87 :   if( FD_UNLIKELY( fd_pubkey_is_active_reserved_key( collector_id ) ||
     191          87 :                    fd_pubkey_is_pending_reserved_key( collector_id ) ) ) return 1;
     192             : 
     193             :   /* The incinerator is exempt from the rent check so the deposit
     194             :      always works.  Incinerator funds are burned at the end of the
     195             :      block. */
     196          54 :   if( FD_UNLIKELY( fd_pubkey_eq( collector_id, &fd_sysvar_incinerator_id ) ) ) return 0;
     197             : 
     198             :   /* Must be rent-exempt after the deposit.  With
     199             :      relax_post_exec_min_balance_check (SIMD-0392) a pre-existing
     200             :      account may stay rent-paying. */
     201          51 :   int is_rent_exempt = collector->lamports>=fd_rent_exempt_minimum_balance( &bank->f.rent, collector->data_len );
     202          51 :   return !is_rent_exempt &&
     203          51 :          ( !FD_FEATURE_ACTIVE_BANK( bank, relax_post_exec_min_balance_check ) || !pre_lamports );
     204          54 : }
     205             : 
     206             : /* Deposits fees into the collector account.
     207             :    Returns 0 on deposit, 1 to burn.
     208             :    https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L248 */
     209             : 
     210             : static int
     211             : fd_runtime_deposit_fees( fd_bank_t *         bank,
     212             :                          fd_accdb_t *        accdb,
     213             :                          fd_capture_ctx_t *  capture_ctx,
     214             :                          fd_pubkey_t const * collector_id,
     215             :                          fd_pubkey_t const * leader_vote,
     216         192 :                          ulong               fees ) {
     217         192 :   uchar                      stake_history_data[ FD_SYSVAR_STAKE_HISTORY_BINCODE_SZ ];
     218         192 :   fd_stake_history_t         stake_history_[1];
     219         192 :   fd_stake_history_t const * stake_history = fd_sysvar_stake_history_read( accdb, bank->accdb_fork_id, stake_history_data, stake_history_ );
     220             : 
     221         192 :   fd_accdb_svm_update_t update[1];
     222         192 :   fd_acc_t acc = fd_accdb_svm_open_rw( bank, accdb, update, collector_id, 1 );
     223         192 :   int burn;
     224         192 :   if( FD_FEATURE_ACTIVE_BANK( bank, custom_commission_collector ) ) {
     225             :     /* https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L254-L267 */
     226         165 :     ulong pre_lamports = acc.lamports;
     227         165 :     burn = __builtin_uaddl_overflow( pre_lamports, fees, &acc.lamports );
     228             :     /* The vote account itself is always a valid collector. */
     229         165 :     if( !burn && !fd_pubkey_eq( collector_id, leader_vote ) ) {
     230         153 :       burn = fd_runtime_validate_block_revenue_collector( bank, collector_id, pre_lamports, &acc );
     231         153 :     }
     232         165 :     if( FD_UNLIKELY( burn ) ) acc.lamports = pre_lamports;
     233         165 :   } else {
     234             :     /* https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L269-L291 */
     235          27 :     burn = fd_runtime_validate_fee_collector( bank, &acc, fees );
     236          27 :     if( FD_LIKELY( !burn ) ) {
     237           9 :       acc.lamports += fees; /* guaranteed to not overflow, checked above */
     238           9 :     }
     239          27 :   }
     240         192 :   if( FD_LIKELY( !burn ) ) fd_stakes_update_stake_delegation( collector_id, &acc, bank, stake_history, NULL );
     241         192 :   fd_accdb_svm_close_rw( bank, accdb, capture_ctx, &acc, update );
     242         192 :   return burn;
     243         192 : }
     244             : 
     245             : /* Deposits delegator fees into the leader's vote account and increments
     246             :    pending delegator rewards (SIMD-0123).
     247             :    Returns 0 on deposit, 1 to burn.
     248             :    https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L303 */
     249             : 
     250             : static int
     251             : fd_runtime_deposit_delegator_fees( fd_bank_t *         bank,
     252             :                                    fd_accdb_t *        accdb,
     253             :                                    fd_capture_ctx_t *  capture_ctx,
     254             :                                    fd_pubkey_t const * vote_address,
     255          27 :                                    ulong               fees ) {
     256          27 :   fd_accdb_svm_update_t update[1];
     257          27 :   fd_acc_t acc = fd_accdb_svm_open_rw( bank, accdb, update, vote_address, 0 );
     258          27 :   if( FD_UNLIKELY( !acc.lamports ) ) return 1; /* open_rw released the handle */
     259             : 
     260          27 :   int burn = 0;
     261             : 
     262             :   /* Must be a vote account.
     263             :      https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L312-L314 */
     264          27 :   if( memcmp( acc.owner, fd_solana_vote_program_id.uc, sizeof(fd_pubkey_t) ) ) burn = 1;
     265             : 
     266             :   /* Lamports must not overflow.  Checked before the field update: the
     267             :      account is written back as is when the deposit burns.
     268             :      https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L324-L326 */
     269          27 :   ulong pre_lamports = acc.lamports;
     270          27 :   if( !burn && __builtin_uaddl_overflow( pre_lamports, fees, &acc.lamports ) ) burn = 1;
     271             : 
     272             :   /* Must be a v4 state and pending_delegator_rewards must not overflow.
     273             :      https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L316-L322 */
     274          27 :   if( !burn && fd_vote_account_add_pending_delegator_rewards( acc.data, acc.data_len, fees ) ) burn = 1;
     275             : 
     276          27 :   if( burn ) acc.lamports = pre_lamports;
     277          27 :   fd_accdb_svm_close_rw( bank, accdb, capture_ctx, &acc, update );
     278          27 :   return burn;
     279          27 : }
     280             : 
     281             : /* Deposits the fee reward with the leader's collector and, under
     282             :    SIMD-0123, the delegator share with the leader's vote account.
     283             :    Returns the lamports to burn.
     284             :    https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L146 */
     285             : 
     286             : static ulong
     287             : fd_runtime_deposit_or_burn_fee( fd_bank_t *        bank,
     288             :                                 fd_accdb_t *       accdb,
     289             :                                 fd_capture_ctx_t * capture_ctx,
     290         402 :                                 ulong              deposit ) {
     291         402 :   if( FD_UNLIKELY( !deposit ) ) return 0UL;
     292             : 
     293         195 :   fd_epoch_leaders_t const * leaders = fd_bank_epoch_leaders_query( bank, bank->f.epoch );
     294         195 :   fd_pubkey_t const *        leader  = fd_epoch_leaders_get( leaders, bank->f.slot );
     295         195 :   if( FD_UNLIKELY( !leader ) ) FD_LOG_CRIT(( "fd_epoch_leaders_get(%lu) returned NULL", bank->f.slot ));
     296             : 
     297             :   /* Per SIMD-0232, the fee reward goes to the leader's block revenue
     298             :      collector from the vote account state the leader schedule was
     299             :      derived from (the t-2 vote stakes set); default is the leader
     300             :      identity.
     301             :      https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L151-L181 */
     302         195 :   int custom_commission_collector = FD_FEATURE_ACTIVE_BANK( bank, custom_commission_collector );
     303             : 
     304         195 :   fd_pubkey_t const *  collector_id   = leader;
     305         195 :   fd_pubkey_t const *  leader_vote    = NULL;
     306         195 :   ushort               commission_bps = FD_VOTE_DEFAULT_BLOCK_REVENUE_COMMISSION_BPS;
     307         195 :   fd_vote_stakes_ele_t leader_ele[1];
     308         195 :   if( custom_commission_collector ) {
     309         168 :     leader_vote = fd_epoch_leaders_get_vote( leaders, bank->f.slot );
     310         168 :     if( FD_UNLIKELY( !leader_vote ) ) FD_LOG_CRIT(( "fd_epoch_leaders_get_vote(%lu) returned NULL", bank->f.slot ));
     311         168 :     if( FD_UNLIKELY( !fd_vote_stakes_query_t_2( fd_bank_vote_stakes( bank ), bank->vote_stakes_fork_id, leader_vote, leader_ele ) ) ) {
     312           0 :       FD_BASE58_ENCODE_32_BYTES( leader_vote->uc, leader_vote_b58 );
     313             :       /* https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L167 */
     314           0 :       FD_LOG_CRIT(( "leader vote account %s is not in the epoch stakes at slot %lu", leader_vote_b58, bank->f.slot ));
     315           0 :     }
     316         168 :     commission_bps = leader_ele->block_revenue_commission_bps;
     317         168 :     collector_id   = &leader_ele->block_collector;
     318         168 :   }
     319             : 
     320             :   /* https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L183-L199 */
     321         195 :   ulong validator_fee = deposit;
     322         195 :   ulong delegator_fee = 0UL;
     323         195 :   if( FD_FEATURE_ACTIVE_BANK( bank, block_revenue_sharing ) ) {
     324          33 :     ulong clamped_commission_bps = fd_ulong_min( commission_bps, FD_VOTE_DEFAULT_BLOCK_REVENUE_COMMISSION_BPS );
     325          33 :     validator_fee = (ulong)( (uint128)deposit * (uint128)clamped_commission_bps / (uint128)FD_VOTE_DEFAULT_BLOCK_REVENUE_COMMISSION_BPS );
     326          33 :     delegator_fee = deposit - validator_fee;
     327          33 :   }
     328             : 
     329             :   /* https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.5/runtime/src/bank/fee_distribution.rs#L201-L212 */
     330         195 :   ulong validator_fee_to_burn = 0UL;
     331         195 :   if( validator_fee && fd_runtime_deposit_fees( bank, accdb, capture_ctx, collector_id, leader_vote, validator_fee ) ) {
     332         129 :     FD_LOG_INFO(( "slot %lu has an invalid fee collector, burning fee reward (%lu lamports)", bank->f.slot, validator_fee ));
     333         129 :     validator_fee_to_burn = validator_fee;
     334         129 :   }
     335         195 :   ulong delegator_fee_to_burn = 0UL;
     336         195 :   if( delegator_fee && fd_runtime_deposit_delegator_fees( bank, accdb, capture_ctx, leader_vote, delegator_fee ) ) {
     337           9 :     FD_LOG_INFO(( "slot %lu has an invalid leader vote account, burning delegator fee reward (%lu lamports)", bank->f.slot, delegator_fee ));
     338           9 :     delegator_fee_to_burn = delegator_fee;
     339           9 :   }
     340         195 :   return validator_fee_to_burn + delegator_fee_to_burn;
     341         195 : }
     342             : 
     343             : /* fd_runtime_settle_fees settles transaction fees accumulated during a
     344             :    slot.  A portion is burnt, another portion is credited to the fee
     345             :    collector (typically leader). */
     346             : 
     347             : void
     348             : fd_runtime_fee_split( ulong   execution_fees,
     349             :                       ulong   priority_fees,
     350             :                       ulong * burn,
     351         402 :                       ulong * reward ) {
     352         402 :   *burn   = execution_fees/2UL;
     353         402 :   *reward = fd_ulong_sat_add( priority_fees, execution_fees-*burn );
     354         402 : }
     355             : 
     356             : static void
     357             : fd_runtime_settle_fees( fd_bank_t *        bank,
     358             :                         fd_accdb_t *       accdb,
     359         402 :                         fd_capture_ctx_t * capture_ctx ) {
     360         402 :   ulong slot           = bank->f.slot;
     361         402 :   ulong execution_fees = bank->f.execution_fees;
     362         402 :   ulong priority_fees  = bank->f.priority_fees;
     363         402 :   ulong total_fees;
     364         402 :   if( FD_UNLIKELY( __builtin_uaddl_overflow( execution_fees, priority_fees, &total_fees ) ) ) {
     365           0 :     FD_LOG_EMERG(( "fee overflow detected (slot=%lu execution_fees=%lu priority_fees=%lu)",
     366           0 :                    slot, execution_fees, priority_fees ));
     367           0 :   }
     368             : 
     369         402 :   ulong fee_burn, fee_reward;
     370         402 :   fd_runtime_fee_split( execution_fees, priority_fees, &fee_burn, &fee_reward );
     371             : 
     372             :   /* Remove fee balance from bank (decreasing capitalization).
     373             :      Allow underflow (wrap) to match Agave's silent fetch_sub behavior. */
     374         402 :   bank->f.capitalization -= total_fees;
     375         402 :   bank->f.execution_fees  = 0;
     376         402 :   bank->f.priority_fees   = 0;
     377             : 
     378         402 :   ulong fee_reward_burn = fd_runtime_deposit_or_burn_fee( bank, accdb, capture_ctx, fee_reward );
     379             : 
     380         402 :   FD_LOG_INFO(( "slot=%lu priority_fees=%lu execution_fees=%lu fee_burn=%lu fee_rewards=%lu fee_reward_burn=%lu",
     381         402 :                 slot,
     382         402 :                 priority_fees, execution_fees, fee_burn, fee_reward, fee_reward_burn ));
     383         402 : }
     384             : 
     385             : void
     386             : fd_runtime_freeze_sysvars( fd_bank_t *        bank,
     387             :                            fd_accdb_t *       accdb,
     388         402 :                            fd_capture_ctx_t * capture_ctx ) {
     389         402 :   if( FD_LIKELY( bank->f.slot ) ) fd_sysvar_recent_hashes_update( bank, accdb, capture_ctx );
     390         402 :   fd_sysvar_slot_history_update( bank, accdb, capture_ctx );
     391         402 : }
     392             : 
     393             : void
     394             : fd_runtime_freeze_fees( fd_bank_t *        bank,
     395             :                         fd_accdb_t *       accdb,
     396         402 :                         fd_capture_ctx_t * capture_ctx ) {
     397         402 :   fd_runtime_settle_fees( bank, accdb, capture_ctx );
     398             : 
     399             :   /* jito collects a 3% fee at the end of the block + 3% fee at
     400             :      distribution time. */
     401         402 :   ulong tips_pre_comission = bank->f.tips;
     402         402 :   bank->f.tips = (tips_pre_comission - (tips_pre_comission * 6UL / 100UL));
     403             : 
     404         402 :   fd_accdb_svm_remove( bank, accdb, capture_ctx, &fd_sysvar_incinerator_id );
     405         402 : }
     406             : 
     407             : /******************************************************************************/
     408             : /* Block-Level Execution Preparation/Finalization                             */
     409             : /******************************************************************************/
     410             : void
     411             : fd_runtime_new_fee_rate_governor_derived( fd_bank_t * bank,
     412        7548 :                                           ulong       latest_signatures_per_slot ) {
     413             : 
     414        7548 :   fd_fee_rate_governor_t const * base_fee_rate_governor = &bank->f.fee_rate_governor;
     415             : 
     416        7548 :   ulong old_lamports_per_signature = bank->f.rbh_lamports_per_sig;
     417             : 
     418        7548 :   fd_fee_rate_governor_t me = {
     419        7548 :     .target_signatures_per_slot    = base_fee_rate_governor->target_signatures_per_slot,
     420        7548 :     .target_lamports_per_signature = base_fee_rate_governor->target_lamports_per_signature,
     421        7548 :     .max_lamports_per_signature    = base_fee_rate_governor->max_lamports_per_signature,
     422        7548 :     .min_lamports_per_signature    = base_fee_rate_governor->min_lamports_per_signature,
     423        7548 :     .burn_percent                  = base_fee_rate_governor->burn_percent
     424        7548 :   };
     425             : 
     426        7548 :   ulong new_lamports_per_signature = 0;
     427        7548 :   if( me.target_signatures_per_slot > 0 ) {
     428           6 :     me.min_lamports_per_signature = fd_ulong_max( 1UL, (ulong)(me.target_lamports_per_signature / 2) );
     429           6 :     me.max_lamports_per_signature = me.target_lamports_per_signature * 10;
     430           6 :     ulong desired_lamports_per_signature = fd_ulong_min(
     431           6 :       me.max_lamports_per_signature,
     432           6 :       fd_ulong_max(
     433           6 :         me.min_lamports_per_signature,
     434           6 :         me.target_lamports_per_signature
     435           6 :         * fd_ulong_min(latest_signatures_per_slot, (ulong)UINT_MAX)
     436           6 :         / me.target_signatures_per_slot
     437           6 :       )
     438           6 :     );
     439           6 :     long gap = (long)desired_lamports_per_signature - (long)old_lamports_per_signature;
     440           6 :     if ( gap == 0 ) {
     441           0 :       new_lamports_per_signature = desired_lamports_per_signature;
     442           6 :     } else {
     443           6 :       long gap_adjust = (long)(fd_ulong_max( 1UL, (ulong)(me.target_lamports_per_signature / 20) ))
     444           6 :         * (gap != 0)
     445           6 :         * (gap > 0 ? 1 : -1);
     446           6 :       new_lamports_per_signature = fd_ulong_min(
     447           6 :         me.max_lamports_per_signature,
     448           6 :         fd_ulong_max(
     449           6 :           me.min_lamports_per_signature,
     450           6 :           (ulong)((long)old_lamports_per_signature + gap_adjust)
     451           6 :         )
     452           6 :       );
     453           6 :     }
     454        7542 :   } else {
     455        7542 :     new_lamports_per_signature = base_fee_rate_governor->target_lamports_per_signature;
     456        7542 :     me.min_lamports_per_signature = me.target_lamports_per_signature;
     457        7542 :     me.max_lamports_per_signature = me.target_lamports_per_signature;
     458        7542 :   }
     459        7548 :   bank->f.fee_rate_governor = me;
     460        7548 :   bank->f.rbh_lamports_per_sig = new_lamports_per_signature;
     461        7548 : }
     462             : 
     463             : /******************************************************************************/
     464             : /* Epoch Boundary                                                             */
     465             : /******************************************************************************/
     466             : 
     467             : /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6704 */
     468             : static void
     469             : fd_apply_builtin_program_feature_transitions( fd_bank_t *          bank,
     470             :                                               fd_accdb_t *         accdb,
     471             :                                               fd_runtime_stack_t * runtime_stack,
     472         318 :                                               fd_capture_ctx_t *   capture_ctx ) {
     473             :   /* TODO: Set the upgrade authority properly from the core bpf migration config. Right now it's set to None.
     474             : 
     475             :      Migrate any necessary stateless builtins to core BPF. So far,
     476             :      the only "stateless" builtin is the Feature program. Beginning
     477             :      checks in the migrate_builtin_to_core_bpf function will fail if the
     478             :      program has already been migrated to BPF. */
     479             : 
     480         318 :   fd_builtin_program_t const * builtins = fd_builtins();
     481        3180 :   for( ulong i=0UL; i<fd_num_builtins(); i++ ) {
     482             :     /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6732-L6751 */
     483        2862 :     if( builtins[i].core_bpf_migration_config && FD_FEATURE_ACTIVE_OFFSET( bank->f.slot, &bank->f.features, builtins[i].core_bpf_migration_config->enable_feature_offset ) ) {
     484           0 :       FD_BASE58_ENCODE_32_BYTES( builtins[i].pubkey->key, pubkey_b58 );
     485           0 :       FD_LOG_DEBUG(( "Migrating builtin program %s to core BPF", pubkey_b58 ));
     486           0 :       fd_migrate_builtin_to_core_bpf( bank, accdb, runtime_stack, builtins[i].core_bpf_migration_config, capture_ctx );
     487           0 :     }
     488             :     /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6753-L6774 */
     489        2862 :     if( builtins[i].enable_feature_offset!=NO_ENABLE_FEATURE_ID && FD_FEATURE_JUST_ACTIVATED_OFFSET( bank, builtins[i].enable_feature_offset ) ) {
     490           0 :       FD_BASE58_ENCODE_32_BYTES( builtins[i].pubkey->key, pubkey_b58 );
     491           0 :       FD_LOG_DEBUG(( "Enabling builtin program %s", pubkey_b58 ));
     492           0 :       fd_write_builtin_account( bank, accdb, capture_ctx, *builtins[i].pubkey, builtins[i].data,strlen(builtins[i].data) );
     493           0 :     }
     494        2862 :   }
     495             : 
     496             :   /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6776-L6793 */
     497         318 :   fd_stateless_builtin_program_t const * stateless_builtins = fd_stateless_builtins();
     498         954 :   for( ulong i=0UL; i<fd_num_stateless_builtins(); i++ ) {
     499         636 :     if( stateless_builtins[i].core_bpf_migration_config && FD_FEATURE_ACTIVE_OFFSET( bank->f.slot, &bank->f.features, stateless_builtins[i].core_bpf_migration_config->enable_feature_offset ) ) {
     500           0 :       FD_BASE58_ENCODE_32_BYTES( stateless_builtins[i].pubkey->key, pubkey_b58 );
     501           0 :       FD_LOG_DEBUG(( "Migrating stateless builtin program %s to core BPF", pubkey_b58 ));
     502           0 :       fd_migrate_builtin_to_core_bpf( bank, accdb, runtime_stack, stateless_builtins[i].core_bpf_migration_config, capture_ctx );
     503           0 :     }
     504         636 :   }
     505             : 
     506             :   /* https://github.com/anza-xyz/agave/blob/c1080de464cfb578c301e975f498964b5d5313db/runtime/src/bank.rs#L6795-L6805 */
     507        1272 :   for( fd_precompile_program_t const * precompiles = fd_precompiles(); precompiles->verify_fn; precompiles++ ) {
     508         954 :     if( precompiles->feature_offset != NO_ENABLE_FEATURE_ID &&
     509         954 :         FD_FEATURE_JUST_ACTIVATED_OFFSET( bank, precompiles->feature_offset ) ) {
     510           0 :       fd_write_builtin_account( bank, accdb, capture_ctx, *precompiles->pubkey, "", 0 );
     511           0 :     }
     512         954 :   }
     513         318 : }
     514             : 
     515             : static void
     516             : fd_feature_activate( fd_bank_t *             bank,
     517             :                      fd_accdb_t *            accdb,
     518             :                      fd_capture_ctx_t *      capture_ctx,
     519             :                      fd_feature_id_t const * id,
     520       98580 :                      fd_pubkey_t const *     addr ) {
     521       98580 :   fd_features_set( &bank->f.features, id, FD_FEATURE_DISABLED );
     522             : 
     523       98580 :   if( FD_UNLIKELY( id->reverted==1 ) ) return;
     524             : 
     525       92856 :   fd_acc_t acc = fd_accdb_read_one( accdb, bank->accdb_fork_id, addr->uc );
     526       92856 :   if( FD_UNLIKELY( !acc.lamports || memcmp( acc.owner, fd_solana_feature_program_id.uc, 32UL ) ) ) {
     527       92562 :     fd_accdb_unread_one( accdb, &acc ); /* Feature account not yet initialized */
     528       92562 :     return;
     529       92562 :   }
     530             : 
     531         294 :   fd_feature_t feature;
     532         294 :   if( FD_UNLIKELY( !fd_feature_decode( &feature, acc.data, acc.data_len ) ) ) {
     533           3 :     FD_BASE58_ENCODE_32_BYTES( addr->uc, addr_b58 );
     534           3 :     FD_LOG_WARNING(( "cannot activate feature %s, corrupt account data", addr_b58 ));
     535           3 :     FD_LOG_HEXDUMP_NOTICE(( "corrupt feature account", acc.data, acc.data_len ));
     536           3 :     fd_accdb_unread_one( accdb, &acc );
     537           3 :     return;
     538           3 :   }
     539         291 :   fd_accdb_unread_one( accdb, &acc );
     540             : 
     541         291 :   FD_BASE58_ENCODE_32_BYTES( addr->uc, addr_b58 );
     542         291 :   if( FD_UNLIKELY( feature.is_active ) ) {
     543         246 :     FD_LOG_DEBUG(( "feature %s already activated at slot %lu", addr_b58, feature.activation_slot ));
     544         246 :     fd_features_set( &bank->f.features, id, feature.activation_slot);
     545         246 :   } else {
     546          45 :     FD_LOG_DEBUG(( "feature %s not activated at slot %lu, activating", addr_b58, bank->f.slot ));
     547          45 :     fd_accdb_svm_update_t update[1];
     548          45 :     fd_acc_t acc = fd_accdb_svm_open_rw( bank, accdb, update, addr, 0 );
     549          45 :     if( FD_UNLIKELY( !acc.lamports ) ) return;
     550          45 :     FD_TEST( acc.data_len>=sizeof(fd_feature_t) );
     551             : 
     552          45 :     feature.is_active       = 1;
     553          45 :     feature.activation_slot = bank->f.slot;
     554          45 :     FD_STORE( fd_feature_t, acc.data, feature );
     555          45 :     fd_accdb_svm_close_rw( bank, accdb, capture_ctx, &acc, update );
     556          45 :     if( FD_UNLIKELY( fd_bank_report_runtime_diffs( bank ) ) ) fd_event_runtime_epoch_feature( addr->uc );
     557          45 :   }
     558         291 : }
     559             : 
     560             : static void
     561             : fd_features_activate( fd_bank_t *        bank,
     562             :                       fd_accdb_t  *      accdb,
     563         318 :                       fd_capture_ctx_t * capture_ctx ) {
     564         318 :   for( fd_feature_id_t const * id = fd_feature_iter_init();
     565       98898 :                                    !fd_feature_iter_done( id );
     566       98580 :                                id = fd_feature_iter_next( id ) ) {
     567       98580 :     fd_feature_activate( bank, accdb, capture_ctx, id, &id->id );
     568       98580 :   }
     569         318 : }
     570             : 
     571             : /* SIMD-0194: deprecate_rent_exemption_threshold
     572             :    https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5322-L5329 */
     573             : static void
     574             : deprecate_rent_exemption_threshold( fd_bank_t *        bank,
     575             :                                     fd_accdb_t *       accdb,
     576           0 :                                     fd_capture_ctx_t * capture_ctx ) {
     577             :   /* We use the bank fields here to mirror Agave - in mainnet, devnet
     578             :      and testnet Agave's bank rent.burn_percent field is different to
     579             :      the value in the sysvar. When this feature is activated in Agave,
     580             :      the sysvar inherits the value from the bank. */
     581           0 :   fd_rent_t rent               = bank->f.rent;
     582           0 :   rent.lamports_per_uint8_year = fd_rust_cast_double_to_ulong(
     583           0 :     (double)rent.lamports_per_uint8_year * rent.exemption_threshold );
     584           0 :   rent.exemption_threshold     = FD_SIMD_0194_NEW_RENT_EXEMPTION_THRESHOLD;
     585           0 :   rent.burn_percent            = FD_SIMD_0194_NEW_BURN_PERCENT;
     586             : 
     587           0 :   bank->f.rent = rent;
     588           0 :   fd_sysvar_rent_write( bank, accdb, capture_ctx, &rent );
     589           0 : }
     590             : 
     591             : static void
     592             : set_lamports_per_byte( fd_bank_t *        bank,
     593             :                        fd_accdb_t *       accdb,
     594             :                        fd_capture_ctx_t * capture_ctx,
     595          36 :                        ulong              lamports_per_byte ) {
     596          36 :   fd_rent_t rent = bank->f.rent;
     597          36 :   rent.lamports_per_uint8_year = lamports_per_byte;
     598             : 
     599          36 :   bank->f.rent = rent;
     600          36 :   fd_sysvar_rent_write( bank, accdb, capture_ctx, &rent );
     601          36 : }
     602             : 
     603             : // https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5296-L5391
     604             : static void
     605             : fd_compute_and_apply_new_feature_activations( fd_bank_t *          bank,
     606             :                                               fd_accdb_t *         accdb,
     607             :                                               fd_runtime_stack_t * runtime_stack,
     608         318 :                                               fd_capture_ctx_t *   capture_ctx ) {
     609             :   /* Activate new features
     610             :       https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5296-L5391 */
     611         318 :   fd_features_activate( bank, accdb, capture_ctx );
     612         318 :   fd_features_restore( &bank->f.features, accdb, bank->accdb_fork_id, bank->f.slot, &bank->f.epoch_schedule );
     613             : 
     614             :   /* SIMD-0194: deprecate_rent_exemption_threshold
     615             :       https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5322-L5329 */
     616         318 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, deprecate_rent_exemption_threshold ) ) ) {
     617           0 :     deprecate_rent_exemption_threshold( bank, accdb, capture_ctx );
     618           0 :   }
     619             : 
     620             :   /* SIMD-0437 rent reduction gates.
     621             :      https://github.com/anza-xyz/agave/blob/v4.1.0-beta.1/runtime/src/bank.rs#L5612-L5639 */
     622         318 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, set_lamports_per_byte_to_6333 ) ) ) {
     623           6 :     set_lamports_per_byte( bank, accdb, capture_ctx, 6333UL );
     624           6 :   }
     625         318 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, set_lamports_per_byte_to_5080 ) ) ) {
     626           6 :     set_lamports_per_byte( bank, accdb, capture_ctx, 5080UL );
     627           6 :   }
     628         318 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, set_lamports_per_byte_to_2575 ) ) ) {
     629           6 :     set_lamports_per_byte( bank, accdb, capture_ctx, 2575UL );
     630           6 :   }
     631         318 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, set_lamports_per_byte_to_1322 ) ) ) {
     632           6 :     set_lamports_per_byte( bank, accdb, capture_ctx, 1322UL );
     633           6 :   }
     634         318 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, set_lamports_per_byte_to_696 ) ) ) {
     635           6 :     set_lamports_per_byte( bank, accdb, capture_ctx, 696UL );
     636           6 :   }
     637             : 
     638             :   /* SIMD-0438 resets rent to the legacy value (in case something goes
     639             :      wrong with the above).
     640             :      https://github.com/anza-xyz/agave/blob/v4.1.0-beta.1/runtime/src/bank.rs#L5641-L5644 */
     641         318 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, set_lamports_per_byte_to_6960 ) ) ) {
     642           6 :     set_lamports_per_byte( bank, accdb, capture_ctx, 6960UL );
     643           6 :   }
     644             : 
     645             :   /* https://github.com/anza-xyz/agave/blob/9bcf93e368b5fb52c21677ed8c7f0360eb93b5b7/runtime/src/bank.rs#L6366-L6368 */
     646         318 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, remove_runtime_float_ops ) ) ) {
     647           0 :     fd_apply_integer_inflation_initial_rate( bank );
     648           0 :   }
     649             : 
     650             :   /* SIMD-0550: double_disinflation_rate
     651             :      https://github.com/anza-xyz/agave/blob/v4.3.0-beta.0/runtime/src/bank.rs#L6232-L6234 */
     652         318 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, double_disinflation_rate ) ) ) {
     653           0 :     fd_apply_double_disinflation_rate( bank );
     654           0 :   }
     655             : 
     656             :   /* Apply builtin program feature transitions
     657             :       https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6621-L6624 */
     658         318 :   fd_apply_builtin_program_feature_transitions( bank, accdb, runtime_stack, capture_ctx );
     659             : 
     660         318 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, validator_location_registration ) ) ) {
     661             :     /* TODO: upgrade the stake program to support vote state v5 */
     662           0 :   }
     663             : 
     664             :   /* https://github.com/anza-xyz/agave/blob/8da849e919e0762f6bfc9ca17ac2339c7a003a0e/runtime/src/bank.rs#L6389-L6402 */
     665         318 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, replace_ata_with_p_ata ) ) ) {
     666           0 :     fd_upgrade_loader_v2_program_with_loader_v3_program(
     667           0 :       bank,
     668           0 :       accdb,
     669           0 :       runtime_stack,
     670           0 :       &fd_solana_spl_associated_token_account_id,
     671           0 :       &fd_solana_pata_program_buffer_address,
     672           0 :       &fd_solana_pata_program_verified_build_hash,
     673           0 :       1,
     674           0 :       capture_ctx );
     675           0 :   }
     676         318 : }
     677             : 
     678             : /* Starting a new epoch.
     679             :   New epoch:        T
     680             :   Just ended epoch: T-1
     681             :   Epoch before:     T-2
     682             : 
     683             :   In this function:
     684             :   - stakes in T-2 (vote_states_prev_prev) should be replaced by T-1 (vote_states_prev)
     685             :   - stakes at T-1 (vote_states_prev) should be replaced by updated stakes at T (vote_states)
     686             :   - leader schedule should be calculated using new T-2 stakes (vote_states_prev_prev)
     687             : 
     688             :   Invariant during an epoch T:
     689             :   vote_states_prev holds the stakes at T-1
     690             :   vote_states_prev_prev holds the stakes at T-2
     691             :  */
     692             : /* process for the start of a new epoch
     693             :    https://github.com/anza-xyz/agave/blob/v4.3.0-beta.0/runtime/src/bank.rs#L1811-L1899 */
     694             : static void
     695             : fd_runtime_process_new_epoch( fd_bank_t *          bank,
     696             :                               fd_accdb_t *         accdb,
     697             :                               fd_capture_ctx_t *   capture_ctx,
     698             :                               ulong                parent_epoch,
     699         318 :                               fd_runtime_stack_t * runtime_stack ) {
     700         318 :   long  start                      = fd_log_wallclock();
     701         318 :   ulong epoch_start_capitalization = bank->f.capitalization;
     702             : 
     703         318 :   fd_compute_and_apply_new_feature_activations( bank, accdb, runtime_stack, capture_ctx );
     704             : 
     705         318 :   bank->f.slot_params = fd_slot_params_at_slot( bank, bank->f.slot );
     706             : 
     707             :   /* Update the cached warmup/cooldown rate epoch now that features may
     708             :      have changed (reduce_stake_warmup_cooldown may have just activated). */
     709         318 :   bank->f.warmup_cooldown_rate_epoch = fd_slot_to_epoch( &bank->f.epoch_schedule,
     710         318 :                                                          bank->f.features.reduce_stake_warmup_cooldown,
     711         318 :                                                          NULL );
     712             : 
     713             :   /* Updates stake history sysvar accumulated values and recomputes
     714             :      stake delegations for vote accounts. */
     715             : 
     716         318 :   uchar                stake_delegations_history_data[ FD_SYSVAR_STAKE_HISTORY_BINCODE_SZ ];
     717         318 :   fd_stake_history_t   stake_delegations_history_[1];
     718         318 :   fd_stake_history_t * stake_delegations_history = fd_sysvar_stake_history_read( accdb, bank->accdb_fork_id, stake_delegations_history_data, stake_delegations_history_ );
     719             : 
     720         318 :   fd_stake_delegations_t * stake_delegations = fd_bank_stake_delegations_modify( bank );
     721         318 :   if( FD_UNLIKELY( !stake_delegations ) ) {
     722           0 :     FD_LOG_CRIT(( "stake_delegations is NULL" ));
     723           0 :   }
     724         318 :   fd_stake_delegations_view_begin( stake_delegations,
     725         318 :                                    bank->f.epoch,
     726         318 :                                    stake_delegations_history,
     727         318 :                                    &bank->f.warmup_cooldown_rate_epoch,
     728         318 :                                    FD_FEATURE_ACTIVE_BANK( bank, upgrade_bpf_stake_program_to_v5_1 ),
     729         318 :                                    bank->stake_delegations_fork_id );
     730             : 
     731             :   /* Wipe WARMED tags awarded under the old floating point math when the
     732             :      fixed point math activates.  This will force all the effective
     733             :      stakes to be re-computed using the post-activation math.
     734             :      Unfortunately, one wipe at the activation boundary is not enough.
     735             :      The consensus root lags the replay frontier.  So
     736             :      post-activation/post-boundary, when the unrooted pre-activation
     737             :      blocks root and their deltas are applied into the root, their
     738             :      pre-activation tags will also leak into the root pool.  So the
     739             :      award sites record whether any live WARMED tag might have been
     740             :      computed with the pre-activation floating point math, and we wipe
     741             :      whenever that is the case.  We expect the invalidation to fire
     742             :      exactly twice: at the activation boundary and at the first boundary
     743             :      after it, unless some extremely sparse epochs happen after
     744             :      activation.  Tags are only used at boundaries for now, and this
     745             :      runs before any use. */
     746         318 :   if( FD_UNLIKELY( FD_FEATURE_ACTIVE_BANK( bank, upgrade_bpf_stake_program_to_v5_1 ) ) ) {
     747         318 :     fd_stake_delegations_invalidate_warmed( stake_delegations );
     748         318 :   }
     749             : 
     750         318 :   fd_stakes_activate_epoch( bank, runtime_stack, accdb, capture_ctx, stake_delegations,
     751         318 :                             &bank->f.warmup_cooldown_rate_epoch );
     752             : 
     753             :   /* Distribute rewards.  This involves calculating the rewards for
     754             :      every vote and stake account. */
     755             : 
     756         318 :   fd_hash_t const * parent_blockhash = fd_blockhashes_peek_last_hash( &bank->f.block_hash_queue );
     757         318 :   fd_begin_partitioned_rewards( bank,
     758         318 :                                 accdb,
     759         318 :                                 runtime_stack,
     760         318 :                                 capture_ctx,
     761         318 :                                 stake_delegations,
     762         318 :                                 parent_blockhash,
     763         318 :                                 parent_epoch,
     764         318 :                                 epoch_start_capitalization );
     765             : 
     766             :   /* Update stake history balance and capitalization only after epoch
     767             :      reward partitions have been calculated. */
     768         318 :   fd_stake_history_ensure_rent_exempt( bank, accdb, capture_ctx );
     769             : 
     770         318 :   fd_stake_delegations_view_end( stake_delegations,
     771         318 :                                  stake_delegations_history,
     772         318 :                                  &bank->f.warmup_cooldown_rate_epoch,
     773         318 :                                  FD_FEATURE_ACTIVE_BANK( bank, upgrade_bpf_stake_program_to_v5_1 ) );
     774             : 
     775             :   /* The Agave client handles updating their stakes cache with a call to
     776             :      update_epoch_stakes() which keys stakes by the leader schedule
     777             :      epochs and retains up to 6 epochs of stakes.  However, to correctly
     778             :      calculate the leader schedule, we just need to maintain the vote
     779             :      states for the current epoch, the previous epoch, and the one
     780             :      before that.
     781             :      https://github.com/anza-xyz/agave/blob/v3.0.4/runtime/src/bank.rs#L2175
     782             :   */
     783             : 
     784             :   /* Now that our stakes caches have been updated, we can calculate the
     785             :      leader schedule for the upcoming epoch epoch using our new
     786             :      vote_states_prev_prev (stakes for T-2). */
     787             : 
     788         318 :   fd_runtime_update_leaders( bank, runtime_stack );
     789             : 
     790         318 :   if( FD_UNLIKELY( fd_bank_report_runtime_diffs( bank ) ) ) fd_event_runtime_epoch_emit( bank );
     791             : 
     792         318 :   long end = fd_log_wallclock();
     793         318 :   FD_LOG_NOTICE(( "starting epoch %s%lu%s at slot %lu %s(took %.6f seconds)%s", fd_log_style_bold(), bank->f.epoch, fd_log_style_normal(), bank->f.slot, fd_log_style_dim(), (double)(end - start) / 1e9, fd_log_style_normal() ));
     794         318 : }
     795             : 
     796             : static void
     797             : fd_runtime_block_pre_execute_process_new_epoch( fd_bank_t *          bank,
     798             :                                                 fd_accdb_t *         accdb,
     799             :                                                 fd_capture_ctx_t *   capture_ctx,
     800             :                                                 fd_runtime_stack_t * runtime_stack,
     801        7548 :                                                 int *                is_epoch_boundary ) {
     802             : 
     803        7548 :   ulong const slot = bank->f.slot;
     804        7548 :   if( FD_LIKELY( slot != 0UL ) ) {
     805        7548 :     fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     806             : 
     807        7548 :     ulong prev_epoch = fd_slot_to_epoch( epoch_schedule, bank->f.parent_slot, NULL );
     808        7548 :     ulong slot_idx;
     809        7548 :     ulong new_epoch  = fd_slot_to_epoch( epoch_schedule, slot, &slot_idx );
     810        7548 :     if( FD_UNLIKELY( slot_idx==1UL && new_epoch==0UL ) ) {
     811             :       /* The block after genesis has a height of 1. */
     812           0 :       bank->f.block_height = 1UL;
     813           0 :     }
     814             : 
     815        7548 :     if( FD_UNLIKELY( prev_epoch<new_epoch || !slot_idx ) ) {
     816         318 :       FD_LOG_DEBUG(( "Epoch boundary starting" ));
     817         318 :       fd_runtime_process_new_epoch( bank, accdb, capture_ctx, prev_epoch, runtime_stack );
     818         318 :       *is_epoch_boundary = 1;
     819        7230 :     } else {
     820        7230 :       *is_epoch_boundary = 0;
     821        7230 :     }
     822             : 
     823        7548 :     fd_distribute_partitioned_epoch_rewards( bank, accdb, runtime_stack, capture_ctx );
     824        7548 :   } else {
     825           0 :     *is_epoch_boundary = 0;
     826           0 :   }
     827        7548 : }
     828             : 
     829             : 
     830             : static void
     831             : fd_runtime_block_sysvar_update_pre_execute( fd_bank_t *        bank,
     832             :                                             fd_accdb_t *       accdb,
     833        7548 :                                             fd_capture_ctx_t * capture_ctx ) {
     834             :   // let (fee_rate_governor, fee_components_time_us) = measure_us!(
     835             :   //     FeeRateGovernor::new_derived(&parent.fee_rate_governor, parent.signature_count())
     836             :   // );
     837             :   /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L1312-L1314 */
     838             : 
     839        7548 :   fd_runtime_new_fee_rate_governor_derived( bank, bank->f.parent_signature_cnt );
     840             : 
     841        7548 :   fd_sysvar_clock_update_slot( bank, accdb, capture_ctx );
     842             : 
     843             :   // It has to go into the current txn previous info but is not in slot 0
     844        7548 :   if( bank->f.slot != 0 ) {
     845        7548 :     fd_sysvar_slot_hashes_update( bank, accdb, capture_ctx );
     846        7548 :   }
     847        7548 :   fd_sysvar_last_restart_slot_update( bank, accdb, capture_ctx );
     848        7548 : }
     849             : 
     850             : int
     851             : fd_runtime_load_txn_address_lookup_tables( fd_txn_t const *         txn,
     852             :                                            uchar const *            payload,
     853             :                                            fd_accdb_t *             accdb,
     854             :                                            fd_accdb_fork_id_t       fork_id,
     855             :                                            ulong                    slot,
     856             :                                            fd_slot_hashes_t const * hashes,
     857         387 :                                            fd_acct_addr_t *         out_accts_alt ) {
     858             : 
     859         387 :   if( FD_LIKELY( txn->transaction_version!=FD_TXN_V0 ) ) return FD_RUNTIME_EXECUTE_SUCCESS;
     860             : 
     861         384 :   fd_alut_interp_t interp[1];
     862         384 :   fd_alut_interp_new( interp, out_accts_alt, txn, payload, hashes, slot );
     863             : 
     864         384 :   fd_txn_acct_addr_lut_t const * addr_luts = fd_txn_get_address_tables_const( txn );
     865         486 :   for( ulong i=0UL; i<txn->addr_table_lookup_cnt; i++ ) {
     866         153 :     fd_txn_acct_addr_lut_t const * addr_lut = &addr_luts[i];
     867         153 :     fd_pubkey_t addr_lut_acc = FD_LOAD( fd_pubkey_t, payload+addr_lut->addr_off );
     868             : 
     869             :     /* Preserve not-found and owner error precedence without acquiring
     870             :        or reading an oversized account's data. */
     871         153 :     uchar owner[32];
     872         153 :     ulong data_len;
     873         153 :     if( FD_UNLIKELY( !fd_accdb_read_one_meta( accdb, fork_id, addr_lut_acc.uc, owner, &data_len ) ) ) {
     874           6 :       return FD_RUNTIME_TXN_ERR_ADDRESS_LOOKUP_TABLE_NOT_FOUND;
     875           6 :     }
     876         147 :     if( FD_UNLIKELY( !fd_memeq( owner, fd_solana_address_lookup_table_program_id.key, sizeof(fd_pubkey_t) ) ) ) {
     877           9 :       return FD_RUNTIME_TXN_ERR_INVALID_ADDRESS_LOOKUP_TABLE_OWNER;
     878           9 :     }
     879         138 :     if( FD_UNLIKELY( data_len>FD_LOOKUP_TABLE_SZ_MAX ) ) {
     880           3 :       return FD_RUNTIME_TXN_ERR_INVALID_ADDRESS_LOOKUP_TABLE_DATA;
     881           3 :     }
     882             : 
     883         135 :     fd_acc_t acc = fd_accdb_read_one( accdb, fork_id, addr_lut_acc.uc );
     884         135 :     if( FD_UNLIKELY( !acc.lamports ) ) {
     885           0 :       fd_accdb_unread_one( accdb, &acc );
     886           0 :       return FD_RUNTIME_TXN_ERR_ADDRESS_LOOKUP_TABLE_NOT_FOUND;
     887           0 :     }
     888         135 :     int err = fd_alut_interp_next( interp, &addr_lut_acc, acc.owner, acc.data, acc.data_len );
     889         135 :     fd_accdb_unread_one( accdb, &acc );
     890         135 :     if( FD_UNLIKELY( err ) ) return err;
     891         135 :   }
     892             : 
     893         333 :   return FD_RUNTIME_EXECUTE_SUCCESS;
     894         384 : }
     895             : 
     896             : /* Pre-populate the bank's in-memory feature set with upcoming feature
     897             :    activations.  If the current slot is the last slot before an epoch
     898             :    boundary, scan all known feature accounts. Otherwise, returns early.
     899             : 
     900             :    For any feature that is pending (not yet activated on-chain) but has
     901             :    an account owned by the feature program, set the in-memory activation
     902             :    slot within the bank's featureset to the first slot of the next
     903             :    epoch.  This is needed so that deployment verification (which uses
     904             :    slot+1) can detect features that will activate at the next epoch
     905             :    boundary.
     906             : 
     907             :    In Agave, program deployments use the feature set from the next
     908             :    slot via DELAY_VISIBILITY_SLOT_OFFSET.  The runtime environments
     909             :    for deployment are selected based on epoch_of(slot+1):
     910             :    https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/bank.rs#L3280-L3295
     911             :    https://github.com/anza-xyz/agave/blob/v3.1.8/svm/src/transaction_processor.rs#L339-L345
     912             : 
     913             :    This function does NOT write to feature accounts or update the
     914             :    lthash.  It only modifies the bank's in-memory feature set. */
     915             : static void
     916             : fd_features_prepopulate_upcoming( fd_bank_t *  bank,
     917        7548 :                                   fd_accdb_t * accdb ) {
     918        7548 :   ulong slot = bank->f.slot;
     919        7548 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     920        7548 :   ulong curr_epoch = fd_slot_to_epoch( epoch_schedule, slot,     NULL );
     921        7548 :   ulong next_epoch = fd_slot_to_epoch( epoch_schedule, slot+1UL, NULL );
     922        7548 :   if( FD_LIKELY( curr_epoch==next_epoch ) ) return;
     923             : 
     924         279 :   fd_features_restore( &bank->f.features, accdb, bank->accdb_fork_id, slot, epoch_schedule );
     925         279 : }
     926             : 
     927             : void
     928             : fd_runtime_block_execute_prepare( fd_banks_t *         banks,
     929             :                                   fd_bank_t *          bank,
     930             :                                   fd_accdb_t *         accdb,
     931             :                                   fd_runtime_stack_t * runtime_stack,
     932             :                                   fd_capture_ctx_t *   capture_ctx,
     933        7548 :                                   int *                is_epoch_boundary ) {
     934             :   /* Cache the Alpenglow migration slot inside the bank so that we can
     935             :      read it inside transaction execution. */
     936        7548 :   bank->f.alpenglow_migration_slot = fd_alpenglow_migration_slot( bank, accdb );
     937             : 
     938        7548 :   if( FD_LIKELY( bank->f.slot ) ) {
     939        7548 :     fd_bank_t * parent = fd_banks_bank_query( banks, bank->parent_idx );
     940        7548 :     FD_TEST( parent );
     941        7548 :     ulong child_epoch = fd_slot_to_epoch( &bank->f.epoch_schedule, bank->f.slot, NULL );
     942        7548 :     fd_vote_stakes_t * vote_stakes = fd_bank_vote_stakes( bank );
     943        7548 :     if( FD_UNLIKELY( child_epoch!=fd_vote_stakes_fork_epoch( vote_stakes, bank->vote_stakes_fork_id ) ) ) {
     944         525 :       fd_vote_stakes_purge_fork( vote_stakes, bank->vote_stakes_fork_id );
     945         525 :       bank->vote_stakes_fork_id = fd_vote_stakes_new_fork( vote_stakes, parent->vote_stakes_fork_id, child_epoch );
     946         525 :     }
     947        7548 :   }
     948             : 
     949        7548 :   fd_runtime_block_pre_execute_process_new_epoch( bank, accdb, capture_ctx, runtime_stack, is_epoch_boundary );
     950             : 
     951        7548 :   if( FD_LIKELY( bank->f.slot ) ) {
     952        7548 :     fd_cost_tracker_store_t * cost_tracker_store = fd_bank_cost_tracker( bank );
     953        7548 :     fd_cost_tracker_t *       cost_tracker       = fd_cost_tracker_store_pin( cost_tracker_store, bank->cost_tracker_fork_id );
     954        7548 :     fd_cost_tracker_init( cost_tracker, &bank->f.features, &bank->f.slot_params, bank->f.slot );
     955        7548 :     fd_cost_tracker_store_unpin( cost_tracker_store, bank->cost_tracker_fork_id );
     956        7548 :   }
     957             : 
     958        7548 :   fd_features_prepopulate_upcoming( bank, accdb );
     959        7548 :   fd_runtime_block_sysvar_update_pre_execute( bank, accdb, capture_ctx );
     960        7548 :   FD_TEST( fd_sysvar_cache_validate( bank, accdb ) );
     961        7548 : }
     962             : 
     963             : static void
     964             : fd_runtime_update_bank_hash( fd_bank_t *        bank,
     965         402 :                              fd_capture_ctx_t * capture_ctx ) {
     966             :   /* Compute the new bank hash */
     967         402 :   fd_lthash_value_t const * lthash = fd_bank_lthash_locking_query( bank );
     968         402 :   fd_hash_t new_bank_hash[1] = { 0 };
     969         402 :   fd_hashes_hash_bank(
     970         402 :       lthash,
     971         402 :       &bank->f.prev_bank_hash,
     972         402 :       (fd_hash_t *)bank->f.poh.hash,
     973         402 :       bank->f.signature_count,
     974         402 :       new_bank_hash );
     975             : 
     976         402 :   fd_hashes_apply_hard_forks(
     977         402 :     new_bank_hash,
     978         402 :     bank->f.slot,
     979         402 :     bank->f.parent_slot,
     980         402 :     bank->f.hard_forks,
     981         402 :     bank->f.hard_fork_cnt );
     982             : 
     983             :   /* Update the bank hash */
     984         402 :   bank->f.bank_hash = *new_bank_hash;
     985             : 
     986         402 :   if( capture_ctx && capture_ctx->capture_solcap &&
     987         402 :       bank->f.slot>=capture_ctx->solcap_start_slot ) {
     988             : 
     989           0 :     uchar lthash_hash[FD_HASH_FOOTPRINT];
     990           0 :     fd_blake3_hash(lthash->bytes, FD_LTHASH_LEN_BYTES, lthash_hash );
     991           0 :     fd_capture_link_write_bank_preimage(
     992           0 :       capture_ctx,
     993           0 :       bank->f.slot,
     994           0 :       (fd_hash_t *)new_bank_hash->hash,
     995           0 :       (fd_hash_t *)&bank->f.prev_bank_hash,
     996           0 :       (fd_hash_t *)lthash_hash,
     997           0 :       (fd_hash_t *)bank->f.poh.hash,
     998           0 :       bank->f.signature_count );
     999           0 :   }
    1000             : 
    1001         402 :   fd_bank_lthash_end_locking_query( bank );
    1002         402 : }
    1003             : 
    1004             : /******************************************************************************/
    1005             : /* Transaction Level Execution Management                                     */
    1006             : /******************************************************************************/
    1007             : 
    1008             : /* fd_runtime_pre_execute_check is responsible for conducting many of
    1009             :    the transaction sanitization checks.  This is a combination of some
    1010             :    of the work done in Agave's load_and_execute_transactions(), and some
    1011             :    of the work done in Agave's transaction ingestion stage, before the
    1012             :    transaction even hits the scheduler.  We do some of the checks also
    1013             :    in our transaction ingestion stage.  For example, the duplicate
    1014             :    account check is performed in both the leader and the replay
    1015             :    scheduler.  As a result, the duplicate account check below is
    1016             :    essentially redundant, except that our fuzzing harness expects a
    1017             :    single entry point to cover all of these checks.  So we keep all of
    1018             :    the checks below for fuzzing purposes.  We could in theory hoist some
    1019             :    of the pre-scheduler checks into a public function that is only
    1020             :    invoked by the fuzzer to avoid duplication in the leader and the
    1021             :    replay pipeline.  But all the duplicate checks are pretty cheap, and
    1022             :    the order and placement of the checks are also in motion on Agave's
    1023             :    side, and performing all the checks faithfully would require access
    1024             :    to the bank in the scheduler which is kind of gross.  So that's all
    1025             :    probably more hassle than worth. */
    1026             : 
    1027             : static inline int
    1028             : fd_runtime_pre_execute_check( fd_runtime_t *      runtime,
    1029             :                               fd_bank_t *         bank,
    1030             :                               fd_txn_in_t const * txn_in,
    1031         738 :                               fd_txn_out_t *      txn_out ) {
    1032             : 
    1033             :   /* Check the transaction version and compute budget configuration. */
    1034         738 :   int err = fd_executor_verify_transaction( bank, txn_in, txn_out );
    1035         738 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
    1036           6 :     txn_out->err.is_committable = 0;
    1037           6 :     return err;
    1038           6 :   }
    1039             : 
    1040             :   /* Setup needs the fee to skip loading accounts for transactions with
    1041             :      an invalid fee payer, so compute unit limits are sanitized here.
    1042             :      Any sanitization error is reported as part of check_transactions.
    1043             :      https://github.com/anza-xyz/agave/blob/v4.4.0-beta.0/runtime/src/bank/check_transactions.rs#L148-L184 */
    1044         732 :   int sanitize_err = fd_sanitize_compute_unit_limits( txn_out );
    1045         732 :   fd_executor_calculate_fee( txn_out, TXN( txn_in->txn ), txn_in->txn->payload, &txn_out->details.execution_fee, &txn_out->details.priority_fee );
    1046             : 
    1047             :   /* Set up the transaction accounts and other txn ctx metadata. This
    1048             :      also resolves ALUT-referenced account keys and validates account
    1049             :      locks before accounts are acquired.  Bundle transactions bind to
    1050             :      the pool acquired and validated once for the whole bundle by
    1051             :      fd_runtime_prepare_bundle_accounts() and never acquire on a
    1052             :      per-transaction basis.  However, the implicit programdata state
    1053             :      must be re-derived here per-transaction, and not once up front.  An
    1054             :      earlier bundle transaction can deploy a program, which changes
    1055             :      whether a pool account parses as a program account, and therefore
    1056             :      which PD account is being implicitly accounted for. */
    1057         732 :   if( FD_UNLIKELY( txn_in->bundle.is_bundle ) ) {
    1058         159 :     fd_executor_setup_accounts_for_txn_bundle( runtime, txn_in, txn_out );
    1059         159 :     err = fd_runtime_setup_bundle_executables( runtime, bank, txn_out );
    1060         573 :   } else {
    1061         573 :     err = fd_executor_setup_accounts_for_txn( runtime, bank, txn_in, txn_out );
    1062         573 :   }
    1063         732 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
    1064           3 :     txn_out->err.is_committable = 0;
    1065           3 :     return err;
    1066           3 :   }
    1067             : 
    1068         729 :   txn_out->details.check_start_ticks = fd_tickcount();
    1069             : 
    1070             :   /* load_and_execute_transactions() -> check_transactions()
    1071             :      https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/runtime/src/bank.rs#L3667-L3672 */
    1072         729 :   err = sanitize_err;
    1073         729 :   if( FD_LIKELY( !err ) ) err = fd_executor_check_transactions( runtime, bank, txn_in, txn_out );
    1074         729 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
    1075          12 :     txn_out->err.is_committable = 0;
    1076          12 :     return err;
    1077          12 :   }
    1078             : 
    1079             :   /* load_and_execute_sanitized_transactions() -> validate_fees() ->
    1080             :      validate_transaction_fee_payer()
    1081             :      https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/svm/src/transaction_processor.rs#L236-L249 */
    1082         717 :   err = fd_executor_validate_transaction_fee_payer( bank, txn_in, txn_out );
    1083         717 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
    1084             :     /* As of the relax_fee_payer_constraint feature, a transaction with
    1085             :        an invalid fee payer can be included in the block. The
    1086             :        transaction has no effect on account state and charges no fees.
    1087             :        These are called "no-op" transactions. They consume block space
    1088             :        (charging the requested CUs) and their loaded accounts data size
    1089             :        is charged at their loaded accounts data size limit.
    1090             : 
    1091             :        Firedancer does not produce blocks containing no-op transactions
    1092             :        but we need to be able to replay blocks containing these.
    1093             : 
    1094             :        The exception is durable nonce transactions - durable nonce
    1095             :        transactions with invalid fee payers are not allowed in a block,
    1096             :        and if a block contains any such transactions it is invalid.
    1097             : 
    1098             :        https://github.com/anza-xyz/agave/blob/v4.3.0-beta.0/svm/src/transaction_processor.rs#L741-L770 */
    1099         111 :     if( FD_FEATURE_ACTIVE_BANK( bank, relax_fee_payer_constraint ) &&
    1100         111 :         txn_out->accounts.nonce_idx_in_txn==ULONG_MAX ) {
    1101           6 :       txn_out->err.is_committable = 1;
    1102           6 :       txn_out->err.is_noop        = 1;
    1103           6 :       txn_out->err.is_fees_only   = 0;
    1104         105 :     } else {
    1105         105 :       txn_out->err.is_committable = 0;
    1106         105 :       txn_out->err.is_noop        = 0;
    1107         105 :     }
    1108         111 :     return err;
    1109         111 :   }
    1110             : 
    1111             :   /* With a valid fee payer, setup only skips acquiring accounts if they
    1112             :      are known to exceed the loaded accounts data size limit.
    1113             :      https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/svm/src/transaction_processor.rs#L284-L296 */
    1114         606 :   if( FD_UNLIKELY( runtime->accounts.account_cnt<txn_out->accounts.cnt ) ) {
    1115           9 :     txn_out->details.loaded_accounts_data_size = txn_out->details.compute_budget.loaded_accounts_data_size_limit;
    1116           9 :     err = FD_RUNTIME_TXN_ERR_MAX_LOADED_ACCOUNTS_DATA_SIZE_EXCEEDED;
    1117         597 :   } else {
    1118         597 :     err = fd_executor_load_transaction_accounts( bank, txn_in, txn_out );
    1119         597 :   }
    1120         606 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
    1121             :     /* Regardless of whether transaction accounts were loaded successfully, the transaction is
    1122             :        included in the block and transaction fees are collected.
    1123             :        https://github.com/anza-xyz/agave/blob/v2.1.6/svm/src/transaction_processor.rs#L341-L357 */
    1124          30 :     txn_out->err.is_fees_only = 1;
    1125             : 
    1126             :     /* If the transaction fails to load, the "rollback" accounts will include one of the following:
    1127             :         1. Nonce account only
    1128             :         2. Fee payer only
    1129             :         3. Nonce account + fee payer
    1130             : 
    1131             :         Because the cost tracker uses the loaded account data size in block cost calculations, we need to
    1132             :         make sure our calculated loaded accounts data size is conformant with Agave's.
    1133             :         https://github.com/anza-xyz/agave/blob/v4.1.0-beta.1/svm/src/account_loader.rs#L437-L449
    1134             : 
    1135             :         These are different depending on if define_ltds_fee_only_semantics is enabled or not.
    1136             : 
    1137             :         If define_ltds_fee_only_semantics is enabled, we use the accumulated load size so far,
    1138             :         clamped to the compute budget requested loaded_accounts_data_size_limit. */
    1139          30 :     if( FD_FEATURE_ACTIVE_BANK( bank, define_ltds_fee_only_semantics ) ) {
    1140             :       /* https://github.com/anza-xyz/agave/blob/v4.1.0-beta.1/svm/src/account_loader.rs#L495-L501 */
    1141          12 :       txn_out->details.loaded_accounts_data_size = fd_ulong_min(
    1142          12 :         txn_out->details.loaded_accounts_data_size,
    1143          12 :         txn_out->details.compute_budget.loaded_accounts_data_size_limit );
    1144          18 :     } else {
    1145             :       /* If define_ltds_fee_only_semantics is not enabled, initialize
    1146             :          loaded_accounts_data_size with the dlen of the fee payer. */
    1147          18 :       txn_out->details.loaded_accounts_data_size = txn_out->accounts.account[ FD_FEE_PAYER_TXN_IDX ]->data_len;
    1148             : 
    1149             :       /* Special case handling for if a nonce account is present in the transaction. */
    1150          18 :       if( txn_out->accounts.nonce_idx_in_txn!=ULONG_MAX ) {
    1151             :         /* If the nonce account is not the fee payer, then we separately add the dlen of the nonce account. Otherwise, we would
    1152             :             be double counting the dlen of the fee payer. */
    1153           6 :         if( txn_out->accounts.nonce_idx_in_txn!=FD_FEE_PAYER_TXN_IDX ) {
    1154           3 :           txn_out->details.loaded_accounts_data_size += txn_out->accounts.account[ txn_out->accounts.nonce_idx_in_txn ]->data_len;
    1155           3 :         }
    1156           6 :       }
    1157          18 :     }
    1158          30 :   }
    1159             : 
    1160             :   /*
    1161             :      The fee payer and the nonce account will be stored and hashed so
    1162             :      long as the transaction landed on chain, or, in Agave terminology,
    1163             :      the transaction was processed.
    1164             :      https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/account_saver.rs#L72
    1165             : 
    1166             :      A transaction lands on chain in one of two ways:
    1167             :      (1) Passed fee validation and loaded accounts.
    1168             :      (2) Passed fee validation and failed to load accounts and the enable_transaction_loading_failure_fees feature is enabled as per
    1169             :          SIMD-0082 https://github.com/anza-xyz/feature-gate-tracker/issues/52
    1170             : 
    1171             :      So, at this point, the transaction is committable.
    1172             :    */
    1173             : 
    1174         606 :   return err;
    1175         717 : }
    1176             : 
    1177             : /* fd_runtime_lthash_account updates the running lthash of the bank
    1178             :    given an account that might have been updated. */
    1179             : 
    1180             : static void
    1181             : fd_runtime_lthash_account( fd_runtime_t *      runtime,
    1182             :                            fd_bank_t *         bank,
    1183             :                            fd_pubkey_t const * pubkey,
    1184             :                            fd_acc_t *          acc,
    1185         597 :                            fd_capture_ctx_t *  capture_ctx ) {
    1186         597 :   if( FD_UNLIKELY( !acc->lamports ) ) {
    1187          24 :     acc->data_len   = 0UL;
    1188          24 :     acc->executable = 0;
    1189          24 :     memset( acc->owner, 0, sizeof(acc->owner) );
    1190          24 :   }
    1191             : 
    1192             :   /* Outside INBAND mode the account is not hashed here.  The in-band
    1193             :      path captures an account iff prior_lamports or lamports is
    1194             :      non-zero, and so does this. */
    1195         597 :   if( FD_UNLIKELY( bank->lthash_mode!=FD_BANK_LTHASH_MODE_INBAND ) ) {
    1196           0 :     if( FD_LIKELY( acc->prior_lamports || acc->lamports ) ) fd_hashes_capture_account( pubkey->uc, acc->owner, acc->lamports, acc->executable, acc->data, acc->data_len, bank, capture_ctx );
    1197           0 :     return;
    1198           0 :   }
    1199             : 
    1200         597 :   if( FD_UNLIKELY( acc->prior_data &&
    1201         597 :                    acc->lamports==acc->prior_lamports &&
    1202         597 :                    acc->data_len==acc->prior_data_len &&
    1203         597 :                    (!!acc->executable)==(!!acc->prior_executable) &&
    1204         597 :                    !memcmp( acc->owner, acc->prior_owner, sizeof(acc->owner) ) &&
    1205         597 :                    !memcmp( acc->data,  acc->prior_data,  acc->data_len ) ) ) {
    1206           6 :     runtime->metrics.lthash_unchanged_cnt++;
    1207           6 :     if( FD_LIKELY( acc->lamports ) ) fd_hashes_capture_account( pubkey->uc, acc->owner, acc->lamports, acc->executable, acc->data, acc->data_len, bank, capture_ctx );
    1208           6 :     return;
    1209           6 :   }
    1210             : 
    1211         591 :   if( FD_LIKELY( acc->prior_lamports || acc->lamports ) ) {
    1212         591 :     ulong prior_lamports = acc->prior_data ? acc->prior_lamports : 0UL;
    1213         591 :     fd_hashes_update_pair( pubkey->uc, acc->prior_owner, prior_lamports, acc->prior_executable, acc->prior_data, acc->prior_data_len,
    1214         591 :                                        acc->owner,       acc->lamports,  acc->executable,       acc->data,       acc->data_len,
    1215         591 :                            bank, capture_ctx );
    1216         591 :   }
    1217         591 : }
    1218             : 
    1219             : /* fd_runtime_commit_txn is a helper used by the transaction executor to
    1220             :    finalize account changes back into the database.  It also handles
    1221             :    txncache insertion and updates to the vote/stake cache.  TODO: This
    1222             :    function should probably be moved to fd_executor.c. */
    1223             : 
    1224             : void
    1225             : fd_runtime_commit_txn( fd_runtime_t *      runtime,
    1226             :                        fd_bank_t *         bank,
    1227             :                        fd_txn_in_t const * txn_in,
    1228         426 :                        fd_txn_out_t *      txn_out ) {
    1229         426 :   FD_TEST( txn_out->err.is_committable );
    1230             : 
    1231         426 :   txn_out->details.commit_start_ticks = fd_tickcount();
    1232             : 
    1233         426 :   if( FD_UNLIKELY( !txn_out->err.txn_err ) ) {
    1234         243 :     fd_vote_stakes_t * vote_stakes = fd_bank_vote_stakes( bank );
    1235        1578 :     for( ushort i=0; i<txn_out->accounts.cnt; i++ ) {
    1236             :       /* We are only interested in saving writable accounts and the fee
    1237             :          payer account. */
    1238        1335 :       if( FD_UNLIKELY( !txn_out->accounts.is_writable[ i ] ) ) continue;
    1239             : 
    1240             :       /* https://github.com/anza-xyz/agave/blob/v4.2.0-beta.1/runtime/src/account_saver.rs#L120-L122 */
    1241         540 :       if( FD_UNLIKELY( !txn_out->accounts.touched[ i ] ) ) continue;
    1242             : 
    1243         477 :       fd_pubkey_t const * pubkey = &txn_out->accounts.keys[ i ];
    1244             : 
    1245             :       /* Only the txn that owns the accdb reference commits the account
    1246             :          state.  In a bundle, an account is owned by its last writable
    1247             :          user (account_acquired==1); every other txn referencing it has
    1248             :          account_acquired==0 and skips here, so the final shared state is
    1249             :          lthashed exactly once and not double-counted.  stake_update/
    1250             :          vote_update are recomputed from the final state and were moved
    1251             :          onto this owner, so they also fire here exactly once. */
    1252         477 :       if( FD_UNLIKELY( !txn_out->accounts.account_acquired[ i ] ) ) continue;
    1253             : 
    1254         414 :       fd_acc_t * account = txn_out->accounts.account[ i ];
    1255         414 :       account->commit = 1;
    1256             : 
    1257         414 :       if( FD_UNLIKELY( txn_out->accounts.stake_update[ i ] ) ) {
    1258           6 :         fd_stake_history_t stake_history[1];
    1259           6 :         fd_stakes_update_stake_delegation( pubkey, account, bank,
    1260           6 :             fd_sysvar_cache_stake_history_view( runtime->sysvar_cache, stake_history ), txn_in );
    1261           6 :       }
    1262             : 
    1263         414 :       if( txn_out->accounts.vote_update[i] ) {
    1264          93 :         int is_valid = account->lamports &&
    1265          93 :                        fd_vsv_is_correct_size_owner_and_init( account->owner, account->data, account->data_len );
    1266          93 :         fd_vote_stakes_update_state( vote_stakes, bank->vote_stakes_fork_id, pubkey, is_valid );
    1267          93 :       }
    1268             : 
    1269         414 :       fd_runtime_lthash_account( runtime, bank, pubkey, account, runtime->log.capture_ctx );
    1270         414 :     }
    1271             : 
    1272             :     /* Atomically add all accumulated tips to the bank once after
    1273             :        processing all accounts. */
    1274         243 :     if( FD_UNLIKELY( txn_out->details.tips ) ) FD_ATOMIC_FETCH_AND_ADD( &bank->f.tips, txn_out->details.tips );
    1275         243 :   }
    1276             : 
    1277         426 :   txn_out->details.commit_index_in_slot = FD_ATOMIC_FETCH_AND_ADD( &bank->f.txn_count, 1UL );
    1278         426 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.execution_fees,  txn_out->details.execution_fee );
    1279         426 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.priority_fees,   txn_out->details.priority_fee );
    1280         426 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.signature_count, txn_out->details.signature_count );
    1281         426 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.nonvote_txn_count, 1 );
    1282         426 :   if( FD_UNLIKELY( txn_out->err.txn_err ) ) FD_ATOMIC_FETCH_AND_ADD( &bank->f.nonvote_failed_txn_count, 1 );
    1283             : 
    1284         426 :   if( FD_UNLIKELY( txn_out->err.txn_err ) ) FD_ATOMIC_FETCH_AND_ADD( &bank->f.failed_txn_count, 1 ); /* fees-only failures too, not just instruction errors */
    1285         426 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.total_compute_units_used, txn_out->details.compute_budget.compute_unit_limit-txn_out->details.compute_budget.compute_meter );
    1286             : 
    1287         426 :   fd_cost_tracker_t * cost_tracker = fd_cost_tracker_store_peek( fd_bank_cost_tracker( bank ), bank->cost_tracker_fork_id );
    1288         426 :   int res = fd_cost_tracker_try_add_cost( cost_tracker, txn_out );
    1289         426 :   if( FD_UNLIKELY( res!=FD_COST_TRACKER_SUCCESS ) ) {
    1290           3 :     FD_LOG_DEBUG(( "fd_runtime_commit_txn: transaction failed to fit into block %d", res ));
    1291           3 :     txn_out->err.is_committable = 0;
    1292           3 :     txn_out->err.txn_err        = fd_cost_tracker_err_to_runtime_err( res );
    1293           3 :   }
    1294             : 
    1295         426 :   if( FD_LIKELY( runtime->status_cache && txn_out->accounts.nonce_idx_in_txn==ULONG_MAX && txn_out->err.is_committable ) ) {
    1296             :     /* In Agave, durable nonce transactions are inserted to the status
    1297             :        cache the same as any others, but this is only to serve RPC
    1298             :        requests, they do not need to be in there for correctness as the
    1299             :        nonce mechanism itself prevents double spend.  We skip this logic
    1300             :        entirely to simplify and improve performance of the txn cache.
    1301             : 
    1302             :        Cost tracker rejected transactions are also skipped: the block
    1303             :        is already dead, and skipping keeps the per slot insert count
    1304             :        bounded by the cost model, which sizes the txn cache. */
    1305         417 :     fd_txncache_insert( runtime->status_cache, bank->txncache_fork_id, txn_out->details.blockhash.uc, txn_out->details.blake_txn_msg_hash.uc );
    1306         417 :   }
    1307             : 
    1308             :   /* No-op transactions have no effect on the state so we should skip
    1309             :      these rollbacks. */
    1310         426 :   if( FD_UNLIKELY( txn_out->err.txn_err && !txn_out->err.is_noop ) ) {
    1311             :     /* With nonce account rollbacks, there are three cases:
    1312             : 
    1313             :        1. No nonce account in the transaction
    1314             :        2. Nonce account is the fee payer
    1315             :        3. Nonce account is not the fee payer
    1316             : 
    1317             :        We should always rollback the nonce account first.  Note that the
    1318             :        nonce account may be the fee payer (case 2). */
    1319         183 :     if( FD_UNLIKELY( txn_out->accounts.nonce_idx_in_txn!=ULONG_MAX ) ) {
    1320           0 :       fd_acc_t * nonce_account = txn_out->accounts.account[ txn_out->accounts.nonce_idx_in_txn ];
    1321           0 :       fd_memcpy( nonce_account->data, txn_out->accounts.nonce_rollback_data, txn_out->accounts.nonce_rollback_data_len );
    1322           0 :       nonce_account->data_len = txn_out->accounts.nonce_rollback_data_len;
    1323           0 :       fd_memcpy( nonce_account->owner, nonce_account->prior_owner, 32UL );
    1324           0 :       if( FD_UNLIKELY( txn_out->accounts.nonce_idx_in_txn==FD_FEE_PAYER_TXN_IDX ) ) {
    1325           0 :         nonce_account->lamports = txn_out->accounts.fee_payer_rollback_lamports;
    1326           0 :       } else {
    1327           0 :         nonce_account->lamports = nonce_account->prior_lamports;
    1328           0 :       }
    1329           0 :       nonce_account->executable = nonce_account->prior_executable;
    1330           0 :       nonce_account->commit = 1;
    1331           0 :       fd_runtime_lthash_account( runtime, bank, &txn_out->accounts.keys[ txn_out->accounts.nonce_idx_in_txn ], nonce_account, runtime->log.capture_ctx );
    1332           0 :     }
    1333             : 
    1334             :     /* Now, we must only save the fee payer if the nonce account was not
    1335             :        the fee payer (because that was already saved above). */
    1336         183 :     if( FD_LIKELY( txn_out->accounts.nonce_idx_in_txn!=FD_FEE_PAYER_TXN_IDX ) ) {
    1337         183 :       fd_acc_t * fee_payer_account = txn_out->accounts.account[ FD_FEE_PAYER_TXN_IDX ];
    1338         183 :       fd_memcpy( fee_payer_account->data, fee_payer_account->prior_data, fee_payer_account->prior_data_len );
    1339         183 :       fee_payer_account->data_len = fee_payer_account->prior_data_len;
    1340         183 :       fd_memcpy( fee_payer_account->owner, fee_payer_account->prior_owner, 32UL );
    1341         183 :       fee_payer_account->lamports = txn_out->accounts.fee_payer_rollback_lamports;
    1342         183 :       fee_payer_account->executable = fee_payer_account->prior_executable;
    1343             : 
    1344         183 :       fee_payer_account->commit = 1;
    1345         183 :       fd_runtime_lthash_account( runtime, bank, &txn_out->accounts.keys[ FD_FEE_PAYER_TXN_IDX ], fee_payer_account, runtime->log.capture_ctx );
    1346         183 :     }
    1347         183 :   }
    1348             : 
    1349         426 :   if( FD_UNLIKELY( fd_bank_report_runtime_diffs( bank ) ) ) fd_event_runtime_txn_emit( txn_in, txn_out, bank );
    1350             : 
    1351         426 :   if( FD_LIKELY( !txn_out->accounts.is_bundle ) ) {
    1352         330 :     fd_accdb_release_ab( runtime->accdb,
    1353         330 :                          runtime->accounts.account_cnt, runtime->accounts.account,
    1354         330 :                          runtime->accounts.executable_cnt, runtime->accounts.executable );
    1355         330 :     runtime->accounts.executable_cnt = 0UL;
    1356         330 :   }
    1357         426 : }
    1358             : 
    1359             : void
    1360             : fd_runtime_cancel_txn( fd_runtime_t *      runtime,
    1361             :                        fd_bank_t *         bank,
    1362             :                        fd_txn_in_t const * txn_in,
    1363         126 :                        fd_txn_out_t *      txn_out ) {
    1364         126 :   FD_TEST( !txn_out->err.is_committable );
    1365             : 
    1366         126 :   if( FD_UNLIKELY( bank && fd_bank_report_runtime_diffs( bank ) ) ) fd_event_runtime_txn_emit( txn_in, txn_out, bank );
    1367             : 
    1368         126 :   if( FD_UNLIKELY( !txn_out->accounts.is_setup ) ) return;
    1369             : 
    1370         120 :   fd_accdb_release_ab( runtime->accdb,
    1371         120 :                        runtime->accounts.account_cnt, runtime->accounts.account,
    1372         120 :                        runtime->accounts.executable_cnt, runtime->accounts.executable );
    1373         120 :   runtime->accounts.executable_cnt = 0UL;
    1374         120 : }
    1375             : 
    1376             : void
    1377          84 : fd_runtime_fini_bundle( fd_runtime_t * runtime ) {
    1378          84 :   fd_accdb_release_ab( runtime->accdb,
    1379          84 :     runtime->accounts.account_cnt, runtime->accounts.account,
    1380          84 :     runtime->accounts.executable_cnt, runtime->accounts.executable );
    1381          84 :   runtime->accounts.account_cnt    = 0UL;
    1382          84 :   runtime->accounts.executable_cnt = 0UL;
    1383          84 : }
    1384             : 
    1385             : static inline void
    1386         738 : fd_runtime_reset_runtime( fd_runtime_t * runtime ) {
    1387         738 :   runtime->instr.stack_sz     = 0;
    1388         738 :   runtime->instr.trace_length = 0UL;
    1389         738 : }
    1390             : 
    1391             : static inline void
    1392             : fd_runtime_new_txn_out( fd_txn_in_t const * txn_in,
    1393         738 :                         fd_txn_out_t *      txn_out ) {
    1394         738 :   txn_out->details.load_start_ticks   = fd_tickcount();
    1395         738 :   txn_out->details.check_start_ticks  = LONG_MAX;
    1396         738 :   txn_out->details.exec_start_ticks   = LONG_MAX;
    1397         738 :   txn_out->details.commit_start_ticks = LONG_MAX;
    1398             : 
    1399         738 :   fd_compute_budget_details_new( &txn_out->details.compute_budget );
    1400         738 :   fd_memset( &txn_out->details.txn_cost, 0, sizeof(txn_out->details.txn_cost) );
    1401             : 
    1402         738 :   txn_out->details.loaded_accounts_data_size = 0UL;
    1403         738 :   txn_out->details.accounts_resize_delta     = 0L;
    1404             : 
    1405         738 :   txn_out->details.return_data.len = 0UL;
    1406         738 :   memset( txn_out->details.return_data.program_id.key, 0, sizeof(fd_pubkey_t) );
    1407             : 
    1408         738 :   txn_out->details.tips            = 0UL;
    1409         738 :   txn_out->details.execution_fee   = 0UL;
    1410         738 :   txn_out->details.priority_fee    = 0UL;
    1411         738 :   txn_out->details.signature_count = TXN( txn_in->txn )->signature_cnt;
    1412         738 :   if( FD_LIKELY( txn_out->details.signature_count ) ) {
    1413         735 :     fd_memcpy( txn_out->details.signature.uc,
    1414         735 :                (uchar const *)txn_in->txn->payload + TXN( txn_in->txn )->signature_off,
    1415         735 :                sizeof(fd_signature_t) );
    1416         735 :   } else {
    1417           3 :     fd_memset( txn_out->details.signature.uc, 0, sizeof(fd_signature_t) );
    1418           3 :   }
    1419             : 
    1420         738 :   fd_hash_t * blockhash = (fd_hash_t *)((uchar *)txn_in->txn->payload + TXN( txn_in->txn )->recent_blockhash_off);
    1421         738 :   memcpy( txn_out->details.blockhash.uc, blockhash->hash, sizeof(fd_hash_t) );
    1422         738 :   memset( txn_out->details.blake_txn_msg_hash.uc, 0, sizeof(fd_hash_t) );
    1423             : 
    1424         738 :   txn_out->accounts.is_setup           = 0;
    1425         738 :   txn_out->accounts.is_bundle          = txn_in->bundle.is_bundle;
    1426         738 :   if( FD_LIKELY( !txn_in->bundle.is_bundle ) ) txn_out->accounts.cnt= 0UL;
    1427             : 
    1428         738 :   FD_STATIC_ASSERT( offsetof(fd_txn_out_t, accounts.touched)-offsetof(fd_txn_out_t, accounts.stake_update)==4UL*MAX_TX_ACCOUNT_LOCKS, txn_out_flags_contiguous );
    1429         738 :   memset( txn_out->accounts.is_writable,  0, sizeof(txn_out->accounts.is_writable) );
    1430         738 :   memset( txn_out->accounts.stake_update, 0, 5UL*MAX_TX_ACCOUNT_LOCKS );
    1431         738 :   txn_out->accounts.nonce_idx_in_txn            = ULONG_MAX;
    1432             : 
    1433             :   /* For bundle transactions the resolved key list is bound once up
    1434             :      front by fd_runtime_prepare_bundle_accounts() before this runs per
    1435             :      transaction, so preserve it here.  For a non-bundle transaction the
    1436             :      executable list is built in fd_executor_setup_accounts_for_txn(),
    1437             :      so reset it here. */
    1438         738 :   if( FD_LIKELY( !txn_in->bundle.is_bundle ) ) {
    1439         579 :     txn_out->accounts.executable_cnt         = 0UL;
    1440         579 :     txn_out->accounts.executable_skipped_cnt = 0;
    1441         579 :   }
    1442         738 :   txn_out->accounts.nonce_rollback_data_len     = 0UL;
    1443         738 :   txn_out->accounts.fee_payer_rollback_lamports = 0UL;
    1444             : 
    1445         738 :   txn_out->err.is_committable = 1;
    1446         738 :   txn_out->err.is_fees_only   = 0;
    1447         738 :   txn_out->err.is_noop        = 0;
    1448         738 :   txn_out->err.txn_err        = FD_RUNTIME_EXECUTE_SUCCESS;
    1449         738 :   txn_out->err.exec_err       = FD_EXECUTOR_INSTR_SUCCESS;
    1450         738 :   txn_out->err.exec_err_kind  = FD_EXECUTOR_ERR_KIND_NONE;
    1451         738 :   txn_out->err.exec_err_idx   = UINT_MAX;
    1452         738 :   txn_out->err.custom_err     = 0;
    1453         738 : }
    1454             : 
    1455             : void
    1456             : fd_runtime_sysvar_cache_refresh( fd_runtime_t *    runtime,
    1457         882 :                                  fd_bank_t const * bank ) {
    1458         882 :   if( FD_LIKELY( runtime->sysvar_bank_seq==bank->bank_seq ) ) return;
    1459         417 :   fd_sysvar_cache_restore( runtime->sysvar_cache, runtime->accdb, bank->accdb_fork_id );
    1460         417 :   runtime->sysvar_bank_seq = bank->bank_seq;
    1461         417 :   runtime->metrics.bank_switch_cnt++;
    1462         417 : }
    1463             : 
    1464             : void
    1465             : fd_runtime_prepare_and_execute_txn( fd_runtime_t *      runtime,
    1466             :                                     fd_bank_t *         bank,
    1467             :                                     fd_txn_in_t const * txn_in,
    1468         738 :                                     fd_txn_out_t *      txn_out ) {
    1469         738 :   fd_runtime_reset_runtime( runtime );
    1470         738 :   fd_runtime_sysvar_cache_refresh( runtime, bank );
    1471             : 
    1472         738 :   fd_runtime_new_txn_out( txn_in, txn_out );
    1473             : 
    1474         738 :   uchar dump_txn = !!(runtime->log.dump_proto_ctx &&
    1475         738 :                       bank->f.slot >= runtime->log.dump_proto_ctx->dump_proto_start_slot &&
    1476         738 :                       runtime->log.dump_proto_ctx->dump_txn_to_pb);
    1477             : 
    1478             :   /* Phase 1: Capture TxnContext before execution. */
    1479         738 :   if( FD_UNLIKELY( dump_txn ) ) {
    1480           0 :     if( runtime->log.txn_dump_ctx ) {
    1481           0 :       fd_dump_txn_context_to_protobuf( runtime->log.txn_dump_ctx, runtime, bank, txn_in, txn_out );
    1482           0 :     } else {
    1483           0 :       fd_dump_txn_to_protobuf( runtime, bank, txn_in, txn_out );
    1484           0 :     }
    1485           0 :   }
    1486             : 
    1487             :   /* Transaction sanitization.  If a transaction can't be committed, is
    1488             :      fees-only, or a no-op, we return early. */
    1489         738 :   txn_out->err.txn_err = fd_runtime_pre_execute_check( runtime, bank, txn_in, txn_out );
    1490         738 :   if( FD_UNLIKELY( !txn_out->err.is_committable || txn_out->err.is_noop ) ) {
    1491             :     /* No fees are collected from these transactions. */
    1492         132 :     txn_out->details.execution_fee = 0UL;
    1493         132 :     txn_out->details.priority_fee  = 0UL;
    1494         132 :   }
    1495         738 :   ulong cu_before = txn_out->details.compute_budget.compute_meter;
    1496             : 
    1497             :   /* Execute the transaction if eligible to do so. */
    1498         738 :   if( FD_LIKELY( txn_out->err.is_committable ) ) {
    1499         612 :     if( FD_UNLIKELY( txn_out->err.is_noop ) ) {
    1500             :       /* No-op transactions charge the requested CUs and loaded
    1501             :          account data size limit.
    1502             :          https://github.com/anza-xyz/agave/blob/v4.3.0-beta.0/svm/src/transaction_processor.rs#L757-L767
    1503             :          https://github.com/anza-xyz/agave/blob/v4.3.0-beta.0/svm/src/transaction_processing_result.rs#L92-L106 */
    1504           6 :       txn_out->details.compute_budget.compute_meter = 0UL;
    1505           6 :       txn_out->details.loaded_accounts_data_size    = txn_out->details.compute_budget.loaded_accounts_data_size_limit;
    1506         606 :     } else if( FD_LIKELY( !txn_out->err.is_fees_only ) ) {
    1507         576 :       txn_out->details.exec_start_ticks = fd_tickcount();
    1508         576 :       txn_out->err.txn_err = fd_execute_txn( runtime, bank, txn_in, txn_out );
    1509         576 :     }
    1510         612 :     fd_cost_tracker_calculate_cost( bank, txn_in, txn_out );
    1511         612 :   }
    1512         738 :   ulong cu_after = txn_out->details.compute_budget.compute_meter;
    1513         738 :   runtime->metrics.cu_cum += fd_ulong_sat_sub( cu_before, cu_after );
    1514             : 
    1515             :   /* Phase 2: Capture TxnResult after execution and write to disk. */
    1516         738 :   if( FD_UNLIKELY( dump_txn && runtime->log.txn_dump_ctx ) ) {
    1517           0 :     fd_dump_txn_result_to_protobuf( runtime->log.txn_dump_ctx, txn_in, txn_out, txn_out->err.txn_err );
    1518           0 :     fd_dump_txn_fixture_to_file( runtime->log.txn_dump_ctx, runtime->log.dump_proto_ctx, txn_in );
    1519           0 :   }
    1520         738 : }
    1521             : 
    1522             : /* fd_executor_txn_verify and fd_runtime_pre_execute_check are responsible
    1523             :    for the bulk of the pre-transaction execution checks in the runtime.
    1524             :    They aim to preserve the ordering present in the Agave client to match
    1525             :    parity in terms of error codes. Sigverify is kept separate from the rest
    1526             :    of the transaction checks for fuzzing convenience.
    1527             : 
    1528             :    fd_runtime_pre_execute_check processes compute-budget instructions
    1529             :    (or v1 configuration), sets up accounts, checks transaction age and
    1530             :    status, validates the fee payer, then loads transaction accounts.
    1531             :    See its calls to fd_executor_verify_transaction,
    1532             :    fd_executor_check_transactions, fd_executor_validate_transaction_fee_payer
    1533             :    and fd_executor_load_transaction_accounts. */
    1534             : 
    1535             : 
    1536             : /******************************************************************************/
    1537             : /* Genesis                                                                    */
    1538             : /*******************************************************************************/
    1539             : 
    1540             : static void
    1541             : fd_runtime_genesis_init_program( fd_bank_t *        bank,
    1542             :                                  fd_accdb_t *       accdb,
    1543           0 :                                  fd_capture_ctx_t * capture_ctx ) {
    1544             : 
    1545           0 :   fd_sysvar_clock_init( bank, accdb, capture_ctx );
    1546           0 :   fd_sysvar_rent_init( bank, accdb, capture_ctx );
    1547             : 
    1548           0 :   fd_sysvar_slot_history_init( bank, accdb, capture_ctx );
    1549           0 :   fd_sysvar_epoch_schedule_init( bank, accdb, capture_ctx );
    1550           0 :   fd_sysvar_recent_hashes_init( bank, accdb, capture_ctx );
    1551           0 :   fd_sysvar_stake_history_init( bank, accdb, capture_ctx );
    1552           0 :   fd_sysvar_last_restart_slot_init( bank, accdb, capture_ctx );
    1553             : 
    1554           0 :   fd_builtin_programs_init( bank, accdb, capture_ctx );
    1555           0 : }
    1556             : 
    1557             : static void
    1558             : fd_runtime_init_bank_from_genesis( fd_banks_t *         banks,
    1559             :                                    fd_bank_t *          bank,
    1560             :                                    fd_runtime_stack_t * runtime_stack,
    1561             :                                    fd_accdb_t *         accdb,
    1562             :                                    fd_genesis_t const * genesis,
    1563             :                                    uchar const *        genesis_blob,
    1564           0 :                                    fd_hash_t const *    genesis_hash ) {
    1565             : 
    1566           0 :   bank->f.parent_slot = ULONG_MAX;
    1567           0 :   bank->f.poh = *genesis_hash;
    1568             : 
    1569           0 :   fd_hash_t * bank_hash = &bank->f.bank_hash;
    1570           0 :   memset( bank_hash->hash, 0, FD_SHA256_HASH_SZ );
    1571             : 
    1572           0 :   uint128 target_tick_duration = (uint128)genesis->poh.tick_duration_secs * 1000000000UL + (uint128)genesis->poh.tick_duration_ns;
    1573             : 
    1574           0 :   fd_epoch_schedule_t * epoch_schedule = &bank->f.epoch_schedule;
    1575           0 :   epoch_schedule->leader_schedule_slot_offset = genesis->epoch_schedule.leader_schedule_slot_offset;
    1576           0 :   epoch_schedule->warmup                      = genesis->epoch_schedule.warmup;
    1577           0 :   epoch_schedule->first_normal_epoch          = genesis->epoch_schedule.first_normal_epoch;
    1578           0 :   epoch_schedule->first_normal_slot           = genesis->epoch_schedule.first_normal_slot;
    1579           0 :   epoch_schedule->slots_per_epoch             = genesis->epoch_schedule.slots_per_epoch;
    1580             : 
    1581           0 :   fd_rent_t * rent = &bank->f.rent;
    1582           0 :   rent->lamports_per_uint8_year = genesis->rent.lamports_per_uint8_year;
    1583           0 :   rent->exemption_threshold     = genesis->rent.exemption_threshold;
    1584           0 :   rent->burn_percent            = genesis->rent.burn_percent;
    1585             : 
    1586           0 :   fd_inflation_t * inflation = &bank->f.inflation;
    1587           0 :   inflation->initial         = genesis->inflation.initial;
    1588           0 :   inflation->terminal        = genesis->inflation.terminal;
    1589           0 :   inflation->taper           = genesis->inflation.taper;
    1590           0 :   inflation->foundation      = genesis->inflation.foundation;
    1591           0 :   inflation->foundation_term = genesis->inflation.foundation_term;
    1592           0 :   inflation->unused          = 0.0;
    1593             : 
    1594           0 :   bank->f.block_height = 0UL;
    1595             : 
    1596           0 :   {
    1597             :     /* FIXME Why is there a previous blockhash at genesis?  Why is the
    1598             :              last_hash field an option type in Agave, if even the first
    1599             :              real block has a previous blockhash? */
    1600           0 :     fd_blockhashes_t *    bhq  = fd_blockhashes_init( &bank->f.block_hash_queue, 0UL );
    1601           0 :     fd_blockhash_info_t * info = fd_blockhashes_push_new( bhq, genesis_hash );
    1602           0 :     info->lamports_per_signature = 0UL;
    1603           0 :   }
    1604             : 
    1605           0 :   fd_fee_rate_governor_t * fee_rate_governor = &bank->f.fee_rate_governor;
    1606           0 :   fee_rate_governor->target_lamports_per_signature = genesis->fee_rate_governor.target_lamports_per_signature;
    1607           0 :   fee_rate_governor->target_signatures_per_slot    = genesis->fee_rate_governor.target_signatures_per_slot;
    1608           0 :   fee_rate_governor->min_lamports_per_signature    = genesis->fee_rate_governor.min_lamports_per_signature;
    1609           0 :   fee_rate_governor->max_lamports_per_signature    = genesis->fee_rate_governor.max_lamports_per_signature;
    1610           0 :   fee_rate_governor->burn_percent                  = genesis->fee_rate_governor.burn_percent;
    1611             : 
    1612           0 :   bank->f.max_tick_height                  = genesis->poh.ticks_per_slot * (bank->f.slot + 1);
    1613           0 :   bank->f.slot_params                      = FD_SLOT_PARAMS_400MS;
    1614           0 :   bank->f.slot_params.ns_per_slot          = (ulong)( target_tick_duration * genesis->poh.ticks_per_slot );
    1615           0 :   bank->f.slot_params.ns_per_slot_adjusted = fd_ulong_sat_sub( bank->f.slot_params.ns_per_slot, FD_TARGET_SLOT_ADJUSTMENT_NS );
    1616           0 :   bank->f.slot_params.slots_per_year       = SECONDS_PER_YEAR * (1000000000.0 / (double)target_tick_duration) / (double)genesis->poh.ticks_per_slot;
    1617           0 :   bank->f.slot_params.hashes_per_tick      = genesis->poh.hashes_per_tick;
    1618           0 :   bank->f.slot_params_default              = bank->f.slot_params;
    1619             : 
    1620           0 :   bank->f.ticks_per_slot = genesis->poh.ticks_per_slot;
    1621           0 :   bank->f.genesis_creation_time = genesis->creation_time;
    1622             : 
    1623           0 :   bank->f.signature_count = 0UL;
    1624             : 
    1625             :   /* Derive epoch stakes */
    1626             : 
    1627           0 :   fd_stake_delegations_t * stake_delegations = fd_banks_stake_delegations_root_query( banks );
    1628           0 :   if( FD_UNLIKELY( !stake_delegations ) ) {
    1629           0 :     FD_LOG_CRIT(( "Failed to join and new a stake delegations" ));
    1630           0 :   }
    1631             : 
    1632           0 :   ulong capitalization = 0UL;
    1633             : 
    1634           0 :   for( ulong i=0UL; i<genesis->account_cnt; i++ ) {
    1635           0 :     fd_genesis_account_t account[1];
    1636           0 :     fd_genesis_account( genesis, genesis_blob, account, i );
    1637             : 
    1638           0 :     capitalization = fd_ulong_sat_add( capitalization, account->lamports );
    1639             : 
    1640           0 :     if( !memcmp( account->owner.uc, fd_solana_stake_program_id.key, sizeof(fd_pubkey_t) ) ) {
    1641             :       /* If an account is a stake account, then it must be added to the
    1642             :          stake delegations cache.  Like Agave, membership is decided by
    1643             :          the variant alone: a delegation of zero is still a delegation. */
    1644           0 :       fd_stake_state_t const * stake_state = fd_stake_state_view( account->data, account->data_len );
    1645           0 :       if( FD_UNLIKELY( !stake_state ) ) { FD_BASE58_ENCODE_32_BYTES( account->pubkey.uc, stake_b58 ); FD_LOG_ERR(( "invalid stake account %s", stake_b58 )); }
    1646           0 :       if( stake_state->stake_type!=FD_STAKE_STATE_STAKE ) continue;
    1647             : 
    1648           0 :       fd_stake_delegations_root_update(
    1649           0 :           stake_delegations,
    1650           0 :           &account->pubkey,
    1651           0 :           &stake_state->stake.stake.delegation.voter_pubkey,
    1652           0 :           stake_state->stake.stake.delegation.stake,
    1653           0 :           stake_state->stake.stake.delegation.activation_epoch,
    1654           0 :           stake_state->stake.stake.delegation.deactivation_epoch,
    1655           0 :           stake_state->stake.stake.credits_observed,
    1656           0 :           account->lamports,
    1657           0 :           (uint)account->data_len );
    1658           0 :     }
    1659           0 :   }
    1660             : 
    1661           0 :   fd_features_restore( &bank->f.features, accdb, bank->accdb_fork_id, bank->f.slot, &bank->f.epoch_schedule );
    1662             : 
    1663             :   /* https://github.com/anza-xyz/agave/blob/9bcf93e368b5fb52c21677ed8c7f0360eb93b5b7/runtime/src/bank.rs#L6237-L6242 */
    1664           0 :   if( FD_UNLIKELY( FD_FEATURE_ACTIVE_BANK( bank, remove_runtime_float_ops ) ) ) {
    1665           0 :     fd_apply_integer_inflation_initial_rate( bank );
    1666           0 :   }
    1667             : 
    1668             :   /* https://github.com/anza-xyz/agave/blob/v4.3.0-beta.0/runtime/src/bank.rs#L6101-L6109 */
    1669           0 :   if( FD_UNLIKELY( FD_FEATURE_ACTIVE_BANK( bank, double_disinflation_rate ) ) ) {
    1670           0 :     fd_apply_double_disinflation_rate( bank );
    1671           0 :   }
    1672             : 
    1673             :   /* fd_refresh_vote_accounts is responsible for updating the vote
    1674             :      states with the total amount of active delegated stake.  It does
    1675             :      this by iterating over all active stake delegations and summing up
    1676             :      the amount of stake that is delegated to each vote account. */
    1677           0 :   ulong new_rate_activation_epoch = 0UL;
    1678             : 
    1679           0 :   {
    1680             :     /* Snapshot the stake history sysvar into a local buffer and release
    1681             :        the accdb bracket before calling fd_refresh_vote_accounts, which
    1682             :        performs its own accdb acquires.  fd_sysvar_stake_history_view
    1683             :        aliases the source bytes, so the bracket cannot be held open
    1684             :        across an inner acquire. */
    1685           0 :     uchar                stake_history_data[ FD_SYSVAR_STAKE_HISTORY_BINCODE_SZ ];
    1686           0 :     fd_stake_history_t   stake_history_[1];
    1687           0 :     fd_stake_history_t * stake_history = NULL;
    1688           0 :     fd_acc_t ro = fd_accdb_read_one( accdb, bank->accdb_fork_id, fd_sysvar_stake_history_id.uc );
    1689           0 :     if( FD_LIKELY( ro.lamports ) ) {
    1690           0 :       ulong copy_sz = fd_ulong_min( ro.data_len, FD_SYSVAR_STAKE_HISTORY_BINCODE_SZ );
    1691           0 :       fd_memcpy( stake_history_data, ro.data, copy_sz );
    1692           0 :       fd_accdb_unread_one( accdb, &ro );
    1693           0 :       stake_history = fd_sysvar_stake_history_view( stake_history_, stake_history_data, copy_sz );
    1694           0 :     } else {
    1695           0 :       fd_accdb_unread_one( accdb, &ro );
    1696           0 :     }
    1697             : 
    1698           0 :     fd_refresh_vote_accounts( bank, accdb, runtime_stack, stake_delegations, stake_history, ULONG_MAX, &new_rate_activation_epoch );
    1699           0 :   }
    1700             : 
    1701             :   /* At genesis (epoch 0) there is no previous epoch, so the t-2 set
    1702             :      should equal the genesis staked set. */
    1703             : 
    1704           0 :   {
    1705           0 :     fd_vote_stakes_t * vote_stakes = fd_bank_vote_stakes( bank );
    1706           0 :     ushort             fork_id     = bank->vote_stakes_fork_id;
    1707           0 :     uchar __attribute__((aligned(FD_VOTE_STAKES_ITER_ALIGN))) iter_mem[ FD_VOTE_STAKES_ITER_FOOTPRINT ];
    1708           0 :     for( fd_vote_stakes_iter_t * iter = fd_vote_stakes_iter_init( vote_stakes, fork_id, FD_VOTE_STAKES_ITER_T_1, iter_mem );
    1709           0 :          !fd_vote_stakes_iter_done( vote_stakes, fork_id, FD_VOTE_STAKES_ITER_T_1, iter );
    1710           0 :          fd_vote_stakes_iter_next( vote_stakes, fork_id, FD_VOTE_STAKES_ITER_T_1, iter ) ) {
    1711           0 :       fd_vote_stakes_ele_t ele[1];
    1712           0 :       fd_vote_stakes_iter_ele( vote_stakes, fork_id, FD_VOTE_STAKES_ITER_T_1, iter, ele );
    1713           0 :       fd_vote_stakes_snap_insert_t_2( vote_stakes, fork_id, &ele->pubkey, &ele->node_account, ele->stake, ele->commission, ele->bls_key,
    1714           0 :                                       ele->block_revenue_commission_bps, ele->pending_delegator_rewards, &ele->inflation_collector, &ele->block_collector, &ele->location );
    1715           0 :     }
    1716           0 :     fd_vote_stakes_finalize( vote_stakes, fork_id, FD_VOTE_STAKES_ITER_T_2 );
    1717           0 :     fd_vote_stakes_refresh( vote_stakes, fork_id, accdb, bank->accdb_fork_id );
    1718           0 :   }
    1719             : 
    1720           0 :   bank->f.epoch = 0UL;
    1721           0 :   bank->f.capitalization = capitalization;
    1722           0 : }
    1723             : 
    1724             : static int
    1725             : fd_runtime_process_genesis_block( fd_bank_t *          bank,
    1726             :                                   fd_accdb_t *         accdb,
    1727             :                                   fd_capture_ctx_t *   capture_ctx,
    1728           0 :                                   fd_runtime_stack_t * runtime_stack ) {
    1729           0 :   bank->f.execution_fees = 0UL;
    1730           0 :   bank->f.priority_fees = 0UL;
    1731           0 :   bank->f.signature_count = 0UL;
    1732           0 :   bank->f.txn_count = 0UL;
    1733           0 :   bank->f.failed_txn_count = 0UL;
    1734           0 :   bank->f.nonvote_failed_txn_count = 0UL;
    1735           0 :   bank->f.total_compute_units_used = 0UL;
    1736             : 
    1737           0 :   fd_runtime_genesis_init_program( bank, accdb, capture_ctx );
    1738           0 :   fd_sysvar_slot_history_update( bank, accdb, capture_ctx );
    1739           0 :   fd_runtime_update_leaders( bank, runtime_stack );
    1740           0 :   fd_runtime_freeze_sysvars( bank, accdb, capture_ctx );
    1741           0 :   fd_runtime_freeze_fees( bank, accdb, capture_ctx );
    1742             : 
    1743           0 :   fd_hash_t const * prev_bank_hash = &bank->f.bank_hash;
    1744             : 
    1745           0 :   fd_lthash_value_t const * lthash = fd_bank_lthash_locking_query( bank );
    1746             : 
    1747           0 :   fd_hash_t * bank_hash = &bank->f.bank_hash;
    1748           0 :   fd_hashes_hash_bank( lthash, prev_bank_hash, (fd_hash_t *)bank->f.poh.hash, 0UL, bank_hash );
    1749             : 
    1750           0 :   fd_bank_lthash_end_locking_query( bank );
    1751             : 
    1752           0 :   return FD_RUNTIME_EXECUTE_SUCCESS;
    1753           0 : }
    1754             : 
    1755             : void
    1756             : fd_runtime_read_genesis( fd_banks_t *              banks,
    1757             :                          fd_bank_t *               bank,
    1758             :                          fd_accdb_t *              accdb,
    1759             :                          fd_capture_ctx_t *        capture_ctx,
    1760             :                          fd_hash_t const *         genesis_hash,
    1761             :                          fd_lthash_value_t const * genesis_lthash,
    1762             :                          fd_genesis_t const *      genesis,
    1763             :                          uchar const *             genesis_blob,
    1764           0 :                          fd_runtime_stack_t *      runtime_stack ) {
    1765           0 :   if( FD_UNLIKELY( genesis->poh.hashes_per_tick ) ) {
    1766           0 :     FD_LOG_ERR(( "unsupported genesis: Firedancer only supports Alpenglow consensus" ));
    1767           0 :   }
    1768             : 
    1769           0 :   fd_lthash_value_t * lthash = fd_bank_lthash_locking_modify( bank );
    1770           0 :   *lthash = *genesis_lthash;
    1771           0 :   fd_bank_lthash_end_locking_modify( bank );
    1772             : 
    1773             :   /* Once the accounts have been loaded from the genesis config into
    1774             :      the accounts db, we can initialize the bank state. This involves
    1775             :      setting some fields, and notably setting up the vote and stake
    1776             :      caches which are used for leader scheduling/rewards. */
    1777             : 
    1778           0 :   fd_runtime_init_bank_from_genesis( banks, bank, runtime_stack, accdb, genesis, genesis_blob, genesis_hash );
    1779             : 
    1780             :   /* Write the native programs to the accounts db. */
    1781             : 
    1782           0 :   for( ulong i=0UL; i<genesis->builtin_cnt; i++ ) {
    1783           0 :     fd_genesis_builtin_t builtin[1];
    1784           0 :     fd_genesis_builtin( genesis, genesis_blob, builtin, i );
    1785           0 :     fd_write_builtin_account( bank, accdb, capture_ctx, builtin->pubkey, builtin->data, builtin->data_len );
    1786           0 :   }
    1787             : 
    1788             :   /* At this point, state related to the bank and the accounts db
    1789             :      have been initialized and we are free to finish executing the
    1790             :      block. In practice, this updates some bank fields (notably the
    1791             :      poh and bank hash). */
    1792             : 
    1793           0 :   int err = fd_runtime_process_genesis_block( bank, accdb, capture_ctx, runtime_stack );
    1794           0 :   if( FD_UNLIKELY( err ) ) FD_LOG_CRIT(( "genesis slot 0 execute failed with error %d", err ));
    1795             : 
    1796             :   /* Genesis init ran the epoch-boundary refresh paths above; discard
    1797             :      the accumulated summary so the first real boundary's runtime_epoch
    1798             :      event only reflects itself. */
    1799           0 :   if( FD_UNLIKELY( fd_bank_report_runtime_diffs( bank ) ) ) fd_event_runtime_epoch_reset();
    1800           0 : }
    1801             : 
    1802             : /* valid_producer_time returns 1 iff an Alpenglow block footer's
    1803             :    producer_time_nanos is within valid bounds relative to the parent's
    1804             :    timestamp and can be safely represented as a long, and 0 if not. */
    1805             : 
    1806             : static inline int
    1807             : valid_producer_time( fd_bank_t const * bank,
    1808             :                      fd_accdb_t *      accdb,
    1809           3 :                      ulong             producer_time_nanos ) {
    1810           3 :   long lo, hi;
    1811           3 :   fd_alpenglow_producer_time_bounds( bank, accdb, &lo, &hi );
    1812           3 :   return producer_time_nanos<=(ulong)LONG_MAX && (long)producer_time_nanos>=lo && (long)producer_time_nanos<=hi;
    1813           3 : }
    1814             : 
    1815             : /* Rewrites the clock sysvar and the alpenclock account from the
    1816             :    footer's producer timestamp (Agave Bank::update_clock_from_footer).
    1817             :    The clock must be applied before the reward certs.  Returns -1 if the
    1818             :    producer time is invalid. */
    1819             : 
    1820             : static int
    1821             : apply_footer_clock( fd_bank_t *               bank,
    1822             :                     fd_accdb_t *              accdb,
    1823             :                     fd_capture_ctx_t *        capture_ctx,
    1824           3 :                     fd_block_footer_t const * footer ) {
    1825             : 
    1826           3 :   ulong producer_time_nanos = footer->block_producer_time_nanos;
    1827           3 :   long  unix_timestamp = (long)(producer_time_nanos/1000000000UL);
    1828             : 
    1829           3 :   fd_sol_sysvar_clock_t clock_[1];
    1830           3 :   fd_sol_sysvar_clock_t * clock = fd_sysvar_clock_read( accdb, bank->accdb_fork_id, clock_ );
    1831           3 :   if( FD_UNLIKELY( !clock ) ) FD_LOG_ERR(( "fd_sysvar_clock_read failed" ));
    1832             : 
    1833           3 :   if( FD_UNLIKELY( !valid_producer_time( bank, accdb, producer_time_nanos ) ) ) return -1;
    1834             : 
    1835           3 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
    1836           3 :   ulong current_epoch = fd_slot_to_epoch( epoch_schedule, bank->f.slot,        NULL );
    1837           3 :   ulong parent_epoch  = fd_slot_to_epoch( epoch_schedule, bank->f.parent_slot, NULL );
    1838             : 
    1839           3 :   long epoch_start_timestamp = clock->epoch_start_timestamp;
    1840           3 :   if( FD_UNLIKELY( bank->f.slot && parent_epoch!=current_epoch ) ) epoch_start_timestamp = unix_timestamp;
    1841             : 
    1842           3 :   fd_sol_sysvar_clock_t new_clock = {
    1843           3 :     .slot                  = bank->f.slot,
    1844           3 :     .epoch_start_timestamp = epoch_start_timestamp,
    1845           3 :     .epoch                 = current_epoch,
    1846           3 :     .leader_schedule_epoch = fd_slot_to_leader_schedule_epoch( epoch_schedule, bank->f.slot ),
    1847           3 :     .unix_timestamp        = unix_timestamp,
    1848           3 :   };
    1849           3 :   fd_sysvar_account_update( bank, accdb, capture_ctx, &fd_sysvar_clock_id, &new_clock, sizeof(fd_sol_sysvar_clock_t) );
    1850             : 
    1851             :   /* size the alpenclock balance with exactly the default rent, any
    1852             :      excess lamports must be burned */
    1853           3 :   fd_pubkey_t alpenclock_addr;
    1854           3 :   fd_alpenglow_pda( "alpenclock", &alpenclock_addr );
    1855           3 :   uchar data[ 8UL ];
    1856           3 :   FD_STORE( ulong, data, producer_time_nanos );
    1857           3 :   fd_accdb_svm_update_t update[1];
    1858           3 :   fd_acc_t acc = fd_accdb_svm_open_rw( bank, accdb, update, &alpenclock_addr, 1 );
    1859           3 :   acc.lamports = fd_rent_exempt_minimum_balance( &FD_RENT_DEFAULT_PARAMS, sizeof(data) );
    1860           3 :   fd_memcpy( acc.owner, fd_solana_system_program_id.uc, sizeof(fd_pubkey_t) );
    1861           3 :   acc.executable = 0;
    1862           3 :   acc.data_len   = sizeof(data);
    1863           3 :   fd_memcpy( acc.data, data, sizeof(data) );
    1864           3 :   fd_accdb_svm_close_rw( bank, accdb, capture_ctx, &acc, update );
    1865             : 
    1866           3 :   return 0;
    1867           3 : }
    1868             : 
    1869             : static int
    1870             : apply_footer( fd_bank_t *               bank,
    1871             :               fd_accdb_t *              accdb,
    1872             :               fd_capture_ctx_t *        capture_ctx,
    1873             :               fd_block_footer_t const * footer,
    1874             :               int                       verify,
    1875             :               ushort                    shred_version,
    1876           3 :               fd_footer_cache_t *       cache ) {
    1877             : 
    1878             :   /* leader bank's certs were verified by votor */
    1879           3 :   if( FD_UNLIKELY( verify && !bank->is_leader && fd_alpenglow_footer_verify( bank, footer, shred_version, cache ) ) ) return -1;
    1880             : 
    1881           0 :   if( FD_UNLIKELY( apply_footer_clock( bank, accdb, capture_ctx, footer ) ) ) return -1;
    1882             : 
    1883           0 :   return fd_alpenglow_rewards_apply( bank, accdb, capture_ctx, cache, footer );
    1884           0 : }
    1885             : 
    1886             : int
    1887             : fd_runtime_block_execute_finalize( fd_bank_t *               bank,
    1888             :                                    fd_accdb_t *              accdb,
    1889             :                                    fd_capture_ctx_t *        capture_ctx,
    1890             :                                    fd_block_footer_t const * footer,
    1891             :                                    ushort                    shred_version,
    1892         402 :                                    fd_footer_cache_t *       cache ) {
    1893         402 :   if( FD_UNLIKELY( footer && apply_footer( bank, accdb, capture_ctx, footer, 1, shred_version, cache ) ) ) return -1;
    1894         399 :   fd_runtime_freeze_sysvars( bank, accdb, capture_ctx );
    1895         399 :   fd_runtime_freeze_fees( bank, accdb, capture_ctx );
    1896         399 :   fd_runtime_update_bank_hash( bank, capture_ctx );
    1897         399 :   return 0;
    1898         402 : }
    1899             : 
    1900             : int
    1901             : fd_runtime_block_footer_begin( fd_bank_t *                   bank,
    1902             :                                fd_accdb_t *                  accdb,
    1903             :                                fd_block_footer_t const *     footer,
    1904           3 :                                fd_alpenglow_rewards_plan_t * plan ) {
    1905           3 :   FD_TEST( footer && !bank->is_leader && !fd_bank_report_runtime_diffs( bank ) );
    1906           3 :   if( FD_UNLIKELY( apply_footer_clock( bank, accdb, NULL, footer ) ) ) return -1;
    1907           3 :   return fd_alpenglow_rewards_plan( bank, accdb, footer, plan );
    1908           3 : }
    1909             : 
    1910             : void
    1911             : fd_runtime_block_footer_end( fd_bank_t *                         bank,
    1912             :                              fd_accdb_t *                        accdb,
    1913             :                              fd_footer_cache_t *                 cache,
    1914             :                              fd_alpenglow_rewards_plan_t const * plan,
    1915           3 :                              ulong                               leader_credits ) {
    1916           3 :   fd_lthash_value_t delta[1];
    1917           3 :   fd_lthash_zero( delta );
    1918           3 :   fd_alpenglow_rewards_apply_leader( bank, accdb, NULL, cache, plan, leader_credits, delta );
    1919           3 :   fd_lthash_add( fd_bank_lthash_locking_modify( bank ), delta );
    1920           3 :   fd_bank_lthash_end_locking_modify( bank );
    1921           3 :   fd_runtime_freeze_fees( bank, accdb, NULL );
    1922           3 :   fd_runtime_update_bank_hash( bank, NULL );
    1923           3 : }
    1924             : 
    1925             : /* Mirrors Agave function solana_sdk::transaction_context::find_index_of_account
    1926             : 
    1927             :    Backward scan over transaction accounts. Returns ULONG_MAX if not found.
    1928             : 
    1929             :    https://github.com/anza-xyz/agave/blob/v2.1.14/sdk/src/transaction_context.rs#L233-L238 */
    1930             : 
    1931             : ulong
    1932             : fd_runtime_find_index_of_account( fd_txn_out_t const * txn_out,
    1933       13920 :                                   fd_pubkey_t const *  pubkey ) {
    1934       34284 :   for( ulong i=0UL; i<txn_out->accounts.cnt; i++ ) {
    1935       31167 :     if( FD_UNLIKELY( !memcmp( pubkey, &txn_out->accounts.keys[ txn_out->accounts.cnt-1UL-i ], sizeof(fd_pubkey_t) ) ) ) return txn_out->accounts.cnt-1UL-i;
    1936       31167 :   }
    1937        3117 :   return ULONG_MAX;
    1938       13920 : }
    1939             : 
    1940             : fd_acc_t *
    1941             : fd_runtime_get_account_at_index( fd_txn_in_t const *             txn_in,
    1942             :                                  fd_txn_out_t *                  txn_out,
    1943             :                                  ushort                          idx,
    1944       33471 :                                  fd_txn_account_condition_fn_t * condition ) {
    1945       33471 :   if( FD_UNLIKELY( idx>=txn_out->accounts.cnt ) ) return NULL;
    1946       33471 :   if( FD_LIKELY( condition && !condition( txn_in, txn_out, idx ) ) ) return NULL;
    1947       33297 :   return txn_out->accounts.account[ idx ];
    1948       33471 : }
    1949             : 
    1950             : fd_acc_t *
    1951             : fd_runtime_get_executable_account( fd_txn_out_t *      txn_out,
    1952             :                                    fd_pubkey_t const * pubkey,
    1953             :                                    int *               from_parent_copy,
    1954          72 :                                    int *               pd_write_this_slot ) {
    1955             :   /* First try to fetch the executable account from the existing
    1956             :      borrowed accounts.  If the pubkey is in the account keys, then we
    1957             :      want to re-use that borrowed account since it reflects changes from
    1958             :      prior instructions.  Referencing the read-only executable accounts
    1959             :      list is incorrect behavior when the program data account is written
    1960             :      to in a prior instruction (e.g. program upgrade + invoke within the
    1961             :      same txn) */
    1962             : 
    1963          72 :   if( FD_UNLIKELY( from_parent_copy   ) ) *from_parent_copy   = 0;
    1964          72 :   if( FD_UNLIKELY( pd_write_this_slot ) ) *pd_write_this_slot = 0;
    1965             : 
    1966          72 :   ulong account_idx = fd_runtime_find_index_of_account( txn_out, pubkey );
    1967          72 :   if( FD_LIKELY( account_idx!=ULONG_MAX && txn_out->accounts.account[ account_idx ]->lamports ) ) return txn_out->accounts.account[ account_idx ];
    1968             : 
    1969          69 :   for( ushort i=0; i<txn_out->accounts.executable_cnt; i++ ) {
    1970          36 :     fd_acc_t * ro = txn_out->accounts.executable[ i ];
    1971          36 :     if( FD_UNLIKELY( !memcmp( pubkey->uc, ro->pubkey, 32UL ) ) ) {
    1972          36 :       if( FD_UNLIKELY( !ro->lamports ) ) return NULL;
    1973          33 :       if( FD_UNLIKELY( from_parent_copy   ) ) *from_parent_copy   = txn_out->accounts.executable_from_parent[ i ];
    1974          33 :       if( FD_UNLIKELY( pd_write_this_slot ) ) *pd_write_this_slot = txn_out->accounts.executable_pd_write[ i ];
    1975          33 :       return ro;
    1976          36 :     }
    1977          36 :   }
    1978             : 
    1979          33 :   return NULL;
    1980          69 : }
    1981             : 
    1982             : int
    1983             : fd_runtime_get_key_of_account_at_index( fd_txn_out_t *        txn_out,
    1984             :                                         ushort                idx,
    1985       26454 :                                         fd_pubkey_t const * * key ) {
    1986             :   /* Return a MissingAccount error if idx is out of bounds.
    1987             :      https://github.com/anza-xyz/agave/blob/v3.1.4/transaction-context/src/lib.rs#L187 */
    1988       26454 :   if( FD_UNLIKELY( idx>=txn_out->accounts.cnt ) ) {
    1989           0 :     return FD_EXECUTOR_INSTR_ERR_MISSING_ACC;
    1990           0 :   }
    1991             : 
    1992       26454 :   *key = &txn_out->accounts.keys[ idx ];
    1993       26454 :   return FD_EXECUTOR_INSTR_SUCCESS;
    1994       26454 : }
    1995             : 
    1996             : /* https://github.com/anza-xyz/agave/blob/v2.1.1/sdk/program/src/message/versions/v0/loaded.rs#L162 */
    1997             : int
    1998             : fd_txn_account_is_demotion( const int        idx,
    1999             :                             const fd_txn_t * txn_descriptor,
    2000        2790 :                             const uint       bpf_upgradeable_in_txn ) {
    2001        2790 :   uint is_program = 0U;
    2002        5289 :   for( ulong j=0UL; j<txn_descriptor->instr_cnt; j++ ) {
    2003        2505 :     if( txn_descriptor->instr[j].program_id == idx ) {
    2004           6 :       is_program = 1U;
    2005           6 :       break;
    2006           6 :     }
    2007        2505 :   }
    2008             : 
    2009        2790 :   return (is_program && !bpf_upgradeable_in_txn);
    2010        2790 : }
    2011             : 
    2012             : uint
    2013             : fd_txn_account_has_bpf_loader_upgradeable( fd_pubkey_t const * account_keys,
    2014        4326 :                                            ulong               accounts_cnt ) {
    2015       26667 :   for( ulong j=0; j<accounts_cnt; j++ ) {
    2016       22710 :     const fd_pubkey_t * acc = &account_keys[j];
    2017       22710 :     if ( memcmp( acc->uc, fd_solana_bpf_loader_upgradeable_program_id.key, sizeof(fd_pubkey_t) ) == 0 ) {
    2018         369 :       return 1U;
    2019         369 :     }
    2020       22710 :   }
    2021        3957 :   return 0U;
    2022        4326 : }
    2023             : 
    2024             : static inline int
    2025             : fd_runtime_account_is_writable_idx_flat( const ushort        idx,
    2026             :                                          const fd_pubkey_t * addr_at_idx,
    2027             :                                          const fd_txn_t *    txn_descriptor,
    2028        5196 :                                          const uint          bpf_upgradeable_in_txn ) {
    2029             :   /* https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L43 */
    2030        5196 :   if( !fd_txn_is_writable( txn_descriptor, idx ) ) {
    2031        2394 :     return 0;
    2032        2394 :   }
    2033             : 
    2034             :   /* See comments in fd_system_ids.h.
    2035             :      https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L44 */
    2036        2802 :   if( fd_pubkey_is_active_reserved_key( addr_at_idx ) ||
    2037        2802 :       fd_pubkey_is_pending_reserved_key( addr_at_idx ) ) {
    2038             : 
    2039          12 :     return 0;
    2040          12 :   }
    2041             : 
    2042        2790 :   if( fd_txn_account_is_demotion( idx, txn_descriptor, bpf_upgradeable_in_txn ) ) {
    2043           6 :     return 0;
    2044           6 :   }
    2045             : 
    2046        2784 :   return 1;
    2047        2790 : }
    2048             : 
    2049             : 
    2050             : /* This function aims to mimic the writable accounts check to populate the writable accounts cache, used
    2051             :    to determine if accounts are writable or not.
    2052             : 
    2053             :    https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L38-L47 */
    2054             : int
    2055             : fd_runtime_account_is_writable_idx( fd_txn_in_t const *  txn_in,
    2056             :                                     fd_txn_out_t const * txn_out,
    2057        4134 :                                     ushort               idx ) {
    2058        4134 :   uint bpf_upgradeable = fd_txn_account_has_bpf_loader_upgradeable( txn_out->accounts.keys, txn_out->accounts.cnt );
    2059        4134 :   return fd_runtime_account_is_writable_idx_flat( idx,
    2060        4134 :                                                    &txn_out->accounts.keys[idx],
    2061        4134 :                                                    TXN( txn_in->txn ),
    2062        4134 :                                                    bpf_upgradeable );
    2063        4134 : }
    2064             : 
    2065             : /* Account pre-condition filtering functions */
    2066             : 
    2067             : int
    2068             : fd_runtime_account_check_exists( fd_txn_in_t const * txn_in,
    2069             :                                  fd_txn_out_t *      txn_out,
    2070        3258 :                                  ushort              idx ) {
    2071        3258 :   (void) txn_in;
    2072        3258 :   return txn_out->accounts.account[ idx ]->lamports!=0UL;
    2073        3258 : }
    2074             : 
    2075             : int
    2076             : fd_runtime_account_check_fee_payer_writable( fd_txn_in_t const * txn_in,
    2077             :                                              fd_txn_out_t *      txn_out,
    2078         717 :                                              ushort              idx ) {
    2079         717 :   (void) txn_out;
    2080         717 :   return fd_txn_is_writable( TXN( txn_in->txn ), idx );
    2081         717 : }
    2082             : 
    2083             : 
    2084             : int
    2085             : fd_account_meta_checked_sub_lamports( fd_acc_t * acc,
    2086         606 :                                       ulong      lamports ) {
    2087         606 :   ulong balance_post = 0UL;
    2088         606 :   int err = fd_ulong_checked_sub( acc->lamports, lamports, &balance_post );
    2089         606 :   if( FD_UNLIKELY( err ) ) return FD_EXECUTOR_INSTR_ERR_ARITHMETIC_OVERFLOW;
    2090             : 
    2091         606 :   acc->lamports = balance_post;
    2092         606 :   return FD_EXECUTOR_INSTR_SUCCESS;
    2093         606 : }
    2094             : 
    2095             : /* fd_executor_reuse_bundle_executable scans the runtime's deduplicated
    2096             :    account pools for a programdata account matching programdata_key that
    2097             :    was already opened by an earlier transaction in the bundle (either as
    2098             :    a regular transaction account or as a programdata account).  Returns
    2099             :    the existing fd_acc_t so it can be reused instead of re-acquiring it,
    2100             :    or NULL if none is found.  Must only be called for bundle txns. */
    2101             : 
    2102             : static fd_acc_t *
    2103             : reuse_bundle_executable( fd_runtime_t *      runtime,
    2104          39 :                          fd_pubkey_t const * programdata_key ) {
    2105         114 :   for( ulong j=0UL; j<runtime->accounts.account_cnt; j++ ) {
    2106          96 :     if( FD_LIKELY( !fd_pubkey_eq( fd_type_pun_const( &runtime->accounts.account[ j ].pubkey ), programdata_key ) ) ) continue;
    2107          21 :     return &runtime->accounts.account[ j ];
    2108          96 :   }
    2109          18 :   for( ulong j=0UL; j<runtime->accounts.executable_cnt; j++ ) {
    2110           6 :     if( FD_LIKELY( !fd_pubkey_eq( fd_type_pun_const( &runtime->accounts.executable[ j ].pubkey ), programdata_key ) ) ) continue;
    2111           6 :     return &runtime->accounts.executable[ j ];
    2112           6 :   }
    2113          12 :   return NULL;
    2114          18 : }
    2115             : 
    2116             : int
    2117             : fd_runtime_prepare_bundle_accounts( fd_runtime_t *      runtime,
    2118             :                                     fd_bank_t *         bank,
    2119             :                                     fd_txn_in_t const * txn_ins,
    2120             :                                     fd_txn_out_t *      txn_outs,
    2121          96 :                                     ulong               txn_cnt ) {
    2122             : 
    2123          96 : # define FD_BUNDLE_ACCT_MAX (FD_PACK_MAX_TXN_PER_BUNDLE*MAX_TX_ACCOUNT_LOCKS)
    2124             : 
    2125          96 :   runtime->accounts.account_cnt    = 0UL;
    2126          96 :   runtime->accounts.executable_cnt = 0UL;
    2127             : 
    2128          96 :   fd_runtime_sysvar_cache_refresh( runtime, bank );
    2129             : 
    2130          96 :   uchar const * acquire_pubkeys[ FD_BUNDLE_ACCT_MAX ];
    2131          96 :   int           acquire_writable[ FD_BUNDLE_ACCT_MAX ];
    2132          96 :   ulong         acquire_cnt = 0UL;
    2133             : 
    2134             :   /* First resolve a deduped set of account keys for all txns in the
    2135             :     bundle.  This includes static account keys as well as ALUT resolved
    2136             :     addresses. */
    2137             : 
    2138         288 :   for( ulong i=0UL; i<txn_cnt; i++ ) {
    2139         204 :     fd_txn_in_t const * txn_in  = &txn_ins [ i ];
    2140         204 :     fd_txn_out_t *      txn_out = &txn_outs[ i ];
    2141             : 
    2142         204 :     txn_out->accounts.cnt = (uchar)TXN( txn_in->txn )->acct_addr_cnt;
    2143         204 :     fd_pubkey_t * tx_accs = (fd_pubkey_t *)((uchar *)txn_in->txn->payload + TXN( txn_in->txn )->acct_addr_off);
    2144        1296 :     for( ulong j=0UL; j<TXN( txn_in->txn )->acct_addr_cnt; j++ ) {
    2145        1092 :       txn_out->accounts.keys[ j ]             = tx_accs[ j ];
    2146        1092 :       txn_out->accounts.account[ j ]          = NULL;
    2147        1092 :       txn_out->accounts.account_acquired[ j ] = 0U;
    2148        1092 :     }
    2149             : 
    2150         204 :     int err = fd_executor_setup_txn_alut_account_keys( runtime, bank, txn_in, txn_out );
    2151         204 :     for( ulong j=TXN( txn_in->txn )->acct_addr_cnt; j<txn_out->accounts.cnt; j++ ) {
    2152           0 :       txn_out->accounts.account[ j ]          = NULL;
    2153           0 :       txn_out->accounts.account_acquired[ j ] = 0U;
    2154           0 :     }
    2155             :     /* Validate account locks before the union acquire below, bounding
    2156             :        the deduped set within the accdb acquire limit. */
    2157         204 :     if( FD_LIKELY( err==FD_RUNTIME_EXECUTE_SUCCESS ) ) err = fd_executor_validate_account_locks( txn_out );
    2158         204 :     if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
    2159          12 :       txn_out->err.txn_err = err;
    2160          12 :       return err;
    2161          12 :     }
    2162             : 
    2163         192 :     uint bpf_upgradeable = fd_txn_account_has_bpf_loader_upgradeable( txn_out->accounts.keys, txn_out->accounts.cnt );
    2164        1254 :     for( ushort j=0; j<txn_out->accounts.cnt; j++ ) {
    2165        1062 :       fd_pubkey_t const * key = &txn_out->accounts.keys[ j ];
    2166        1062 :       int writable = fd_runtime_account_is_writable_idx_flat( j, key, TXN( txn_in->txn ), bpf_upgradeable );
    2167        1062 :       int dup = 0;
    2168        4725 :       for( ulong k=0UL; k<acquire_cnt; k++ ) if( FD_UNLIKELY( !memcmp( acquire_pubkeys[ k ], key->uc, 32UL ) ) ) { acquire_writable[ k ] |= writable; dup = 1; break; }
    2169        1062 :       if( FD_UNLIKELY( dup ) ) continue;
    2170         546 :       FD_TEST( acquire_cnt<FD_BUNDLE_ACCT_MAX );
    2171         546 :       acquire_pubkeys [ acquire_cnt ] = key->uc;
    2172             :       /* Acquire writable if any bundle member can write this account. */
    2173         546 :       acquire_writable[ acquire_cnt ] = writable;
    2174         546 :       acquire_cnt++;
    2175         546 :     }
    2176         192 :   }
    2177             : 
    2178          84 :   if( FD_LIKELY( acquire_cnt ) ) {
    2179          84 :     fd_accdb_acquire_a( runtime->accdb, bank->accdb_fork_id, acquire_cnt, acquire_pubkeys, acquire_writable, runtime->accounts.account );
    2180          84 :     runtime->accounts.account_cnt = acquire_cnt;
    2181          84 :   }
    2182             : 
    2183         264 :   for( ulong i=0UL; i<txn_cnt; i++ ) {
    2184         180 :     fd_txn_out_t * txn_out = &txn_outs[ i ];
    2185        1206 :     for( ushort j=0; j<txn_out->accounts.cnt; j++ ) {
    2186        1026 :       txn_out->accounts.account[ j ] = NULL;
    2187        4647 :       for( ulong k=0UL; k<runtime->accounts.account_cnt; k++ ) {
    2188        4647 :         fd_acc_t * acc = &runtime->accounts.account[ k ];
    2189        4647 :         if( FD_LIKELY( !fd_pubkey_eq( fd_type_pun_const( &acc->pubkey ), &txn_out->accounts.keys[ j ] ) ) ) continue;
    2190        1026 :         txn_out->accounts.account[ j ]           = acc;
    2191        1026 :         txn_out->accounts.starting_lamports[ j ] = acc->prior_lamports;
    2192        1026 :         txn_out->accounts.starting_data_len[ j ] = acc->prior_data_len;
    2193        1026 :         memcpy( &txn_out->accounts.starting_owner[ j ], acc->prior_owner, sizeof(fd_pubkey_t) );
    2194        1026 :         break;
    2195        4647 :       }
    2196        1026 :     }
    2197         180 :   }
    2198             : 
    2199             :   /* Do the same for executable accounts (programdata accounts).  Dedup
    2200             :     against all other executable-only accounts as well as ones that
    2201             :     were already included. */
    2202             : 
    2203          84 :   fd_pubkey_t   programdata_keys[ FD_BUNDLE_ACCT_MAX ];
    2204          84 :   uchar const * pd_pubkeys      [ FD_BUNDLE_ACCT_MAX ];
    2205          84 :   ulong         pd_cnt = 0UL;
    2206             : 
    2207          84 :   FD_TEST( bank->parent_accdb_fork_id.val!=USHORT_MAX );
    2208             : 
    2209         600 :   for( ulong i=0UL; i<runtime->accounts.account_cnt; i++ ) {
    2210         516 :     fd_acc_t * acc = &runtime->accounts.account[ i ];
    2211         516 :     if( FD_LIKELY( memcmp( acc->owner, fd_solana_bpf_loader_upgradeable_program_id.key, 32UL ) ) ) continue;
    2212          39 :     fd_bpf_state_t program_loader_state[1];
    2213          39 :     if( FD_UNLIKELY( fd_bpf_loader_program_get_state( acc, program_loader_state )!=FD_EXECUTOR_INSTR_SUCCESS ) ) continue;
    2214          39 :     if( FD_UNLIKELY( program_loader_state->discriminant!=FD_BPF_STATE_PROGRAM ) ) continue;
    2215             : 
    2216          24 :     fd_pubkey_t const * programdata_key = &program_loader_state->inner.program.programdata_address;
    2217             :     /* PD is not live as of the parent, so there is nothing to acquire
    2218             :        from the parent.  We will still need its latest length for loaded
    2219             :        accounts data size, but that is taken care of per transaction by
    2220             :        fd_runtime_setup_bundle_executables() without acquiring. */
    2221          24 :     if( FD_UNLIKELY( !fd_accdb_exists( runtime->accdb, bank->parent_accdb_fork_id, programdata_key->uc ) ) ) continue;
    2222             : 
    2223             :     /* Already part of the transaction account pool, or already queued. */
    2224          12 :     if( reuse_bundle_executable( runtime, programdata_key ) ) continue;
    2225           6 :     int dup = 0;
    2226           6 :     for( ulong u=0UL; u<pd_cnt; u++ ) if( FD_UNLIKELY( !memcmp( programdata_keys[ u ].uc, programdata_key->uc, 32UL ) ) ) { dup = 1; break; }
    2227           6 :     if( dup ) continue;
    2228             : 
    2229           6 :     FD_TEST( pd_cnt<FD_BUNDLE_ACCT_MAX );
    2230           6 :     programdata_keys[ pd_cnt ] = *programdata_key;
    2231           6 :     pd_pubkeys[ pd_cnt ]       = programdata_keys[ pd_cnt ].uc;
    2232           6 :     pd_cnt++;
    2233           6 :   }
    2234             : 
    2235             :   /* acquire_b refunds the per-class reservations acquire_a made for the
    2236             :     union (reserved_cnt==acquire_cnt) that did not turn out to be
    2237             :     programdata.  Skip it entirely for an empty bundle (nothing was
    2238             :     reserved and nothing is executable). */
    2239          84 :   if( FD_LIKELY( acquire_cnt || pd_cnt ) ) {
    2240          84 :     fd_accdb_acquire_b( runtime->accdb, bank->parent_accdb_fork_id, acquire_cnt, pd_cnt, pd_pubkeys, runtime->accounts.executable );
    2241          84 :   }
    2242          84 :   runtime->accounts.executable_cnt = pd_cnt;
    2243             : 
    2244          84 :   return FD_RUNTIME_EXECUTE_SUCCESS;
    2245             : 
    2246          84 : # undef FD_BUNDLE_ACCT_MAX
    2247          84 : }
    2248             : 
    2249             : int
    2250             : fd_runtime_setup_bundle_executables( fd_runtime_t * runtime,
    2251             :                                      fd_bank_t *    bank,
    2252         159 :                                      fd_txn_out_t * txn_out ) {
    2253         159 :   FD_TEST( bank->parent_accdb_fork_id.val!=USHORT_MAX );
    2254             : 
    2255         159 :   ushort exe_cnt = 0;
    2256         159 :   txn_out->accounts.executable_skipped_cnt = 0;
    2257        1128 :   for( ushort i=0; i<txn_out->accounts.cnt; i++ ) {
    2258             :     /* The checks below mimic the ones in the non-bundle path.  The
    2259             :        difference is only the source of state as of this transaction.
    2260             :        Here it's from the live pool when possible, and in the non-bundle
    2261             :        path it's from the accdb. */
    2262         969 :     fd_acc_t * acc = txn_out->accounts.account[ i ]; /* This has gone through zero-lamport reset by fd_executor_setup_accounts_for_txn_bundle(). */
    2263         969 :     if( FD_LIKELY( memcmp( acc->owner, fd_solana_bpf_loader_upgradeable_program_id.key, 32UL ) ) ) continue;
    2264          51 :     fd_bpf_state_t program_loader_state[1];
    2265          51 :     if( FD_UNLIKELY( fd_bpf_loader_program_get_state( acc, program_loader_state )!=FD_EXECUTOR_INSTR_SUCCESS ) ) continue;
    2266          51 :     if( FD_UNLIKELY( program_loader_state->discriminant!=FD_BPF_STATE_PROGRAM ) ) continue;
    2267             : 
    2268          36 :     fd_pubkey_t const * programdata_key = &program_loader_state->inner.program.programdata_address;
    2269             : 
    2270             :     /* Declared PD is charged as a plain top-level transaction account
    2271             :        and is preferred by fd_runtime_get_executable_account(). */
    2272          36 :     if( FD_UNLIKELY( fd_runtime_find_index_of_account( txn_out, programdata_key )!=ULONG_MAX ) ) continue;
    2273             : 
    2274          27 :     fd_acc_t * programdata = reuse_bundle_executable( runtime, programdata_key );
    2275             : 
    2276          27 :     if( FD_UNLIKELY( !fd_accdb_exists( runtime->accdb, bank->parent_accdb_fork_id, programdata_key->uc ) ) ) {
    2277             :       /* PD is not live as of the parent.  Length only, and no
    2278             :          executable[] entry, so the loader reports "Program is not
    2279             :          deployed" exactly as the non-bundle path does.  The non-bundle
    2280             :          path takes the length from the latest accdb view committed on
    2281             :          this fork.  The equivalent here is the live pool copy, which an
    2282             :          earlier bundle transaction may have created, resized or
    2283             :          drained.  Only a LIVE PD is recorded.  Membership in the
    2284             :          skipped list is the liveness answer, so a dead PD is left out
    2285             :          entirely rather than recorded with a zero length: a live PD may
    2286             :          itself have zero-length data, and Agave still charges the
    2287             :          64-byte base for that. */
    2288          15 :       ulong skip_len;
    2289          15 :       if( FD_LIKELY( programdata ) ) {
    2290             :         /* A dead PD must contribute nothing to loaded accounts data
    2291             :            size.  Like every other consumer, the lamports need to be
    2292             :            checked first.  The pool copy that programdata points to has
    2293             :            an up to date lamports, but it is not necessarily otherwise
    2294             :            normalized: zero length, non-executable, and system-owned.
    2295             :            The reset in setup_accounts_for_txn_bundle() only covers the
    2296             :            declared accounts of the transaction.  If PD were declared,
    2297             :            it would have short circuited above.  So an in-bundle Close
    2298             :            leaves PD here at zero lamports with length at
    2299             :            SIZE_OF_UNINITIALIZED. */
    2300           9 :         if( FD_UNLIKELY( !programdata->lamports ) ) continue;
    2301           6 :         skip_len = programdata->data_len;
    2302           6 :       } else {
    2303             :         /* At this point, this PD
    2304             :            - has no pool copy, so no bundle transaction declares PD, and
    2305             :            - it is not live on the parent.
    2306             : 
    2307             :            So PD was created this slot by something outside the bundle,
    2308             :            and only the latest accdb view has the length we need for
    2309             :            accounting.  It may also have been created and closed within
    2310             :            this slot, in which case it is dead and contributes nothing. */
    2311           6 :         int   probe_pd  = 0;
    2312           6 :         ulong probe_len = 0UL;
    2313           6 :         ulong probe_lamports = 0UL;
    2314           6 :         if( FD_UNLIKELY( !fd_accdb_probe_pd_this_fork( runtime->accdb, bank->accdb_fork_id, programdata_key->uc, &probe_pd, &probe_len, &probe_lamports ) ) ) continue;
    2315           6 :         if( FD_UNLIKELY( !probe_lamports ) ) continue;
    2316           3 :         skip_len = probe_len;
    2317           3 :       }
    2318           9 :       ushort s = txn_out->accounts.executable_skipped_cnt++;
    2319           9 :       txn_out->accounts.executable_skipped_key[ s ] = *programdata_key;
    2320           9 :       txn_out->accounts.executable_skipped_len[ s ] = skip_len;
    2321           9 :       continue;
    2322          15 :     }
    2323             : 
    2324             :     /* At this point, PD exists in the parent.  So prepare() must have
    2325             :        acquired PD, either in accounts[] if a bundle transaction
    2326             :        declares it, or in executable[] aka implied load from the parent.
    2327             :        A miss would imply that a pool account only began parsing as
    2328             :        Program{PD} after prepare() computed the acquire set, naming a PD
    2329             :        no bundle transaction declares.  This should not be possible,
    2330             :        because only the DeployWithMaxDataLen instruction writes
    2331             :        Program{PD}.  The instruction declares PD, and its CreateAccount
    2332             :        CPI cannot succeed against a PD that is already live on the
    2333             :        parent.  We cannot acquire the PD at this point, since a
    2334             :        mid-bundle acquire of an account the bundle might be holding as
    2335             :        writable would violate the accdb acquire contract.  So fail the
    2336             :        bundle. */
    2337          12 :     if( FD_UNLIKELY( !programdata ) ) {
    2338           0 :       FD_BASE58_ENCODE_32_BYTES( programdata_key->uc, pd_str );
    2339           0 :       FD_BASE58_ENCODE_64_BYTES( txn_out->details.signature.uc, sig_str );
    2340           0 :       FD_LOG_INFO(( "dropping bundle: bundle txn %s in slot %lu implies unacquired programdata %s", sig_str, bank->f.slot, pd_str ));
    2341           0 :       return FD_RUNTIME_TXN_ERR_PROGRAM_ACCOUNT_NOT_FOUND;
    2342           0 :     }
    2343             : 
    2344          12 :     int from_parent = ( programdata>=runtime->accounts.executable ) &&
    2345          12 :                       ( programdata< runtime->accounts.executable+runtime->accounts.executable_cnt ) &&
    2346          12 :                       ( bank->parent_accdb_fork_id.val!=bank->accdb_fork_id.val );
    2347          12 :     txn_out->accounts.executable[ exe_cnt ]             = programdata;
    2348          12 :     txn_out->accounts.executable_from_parent[ exe_cnt ] = from_parent;
    2349          12 :     if( from_parent ) {
    2350             :       /* A from_parent copy is one no bundle transaction declared, hence
    2351             :          one no bundle transaction could have modified, because mutating
    2352             :          PD requires declaring it writable.  So the probe from accdb
    2353             :          reports the latest state that we need. */
    2354           6 :       int   pd  = 0;
    2355           6 :       ulong len = ULONG_MAX;
    2356           6 :       ulong lamports = 0UL;
    2357           6 :       fd_accdb_probe_pd_this_fork( runtime->accdb, bank->accdb_fork_id, programdata_key->uc, &pd, &len, &lamports );
    2358           6 :       txn_out->accounts.executable_pd_write    [ exe_cnt ] = pd;
    2359           6 :       txn_out->accounts.executable_cur_len     [ exe_cnt ] = len;
    2360           6 :       txn_out->accounts.executable_cur_lamports[ exe_cnt ] = lamports;
    2361           6 :     } else {
    2362           6 :       txn_out->accounts.executable_pd_write    [ exe_cnt ] = 0;
    2363           6 :       txn_out->accounts.executable_cur_len     [ exe_cnt ] = ULONG_MAX;
    2364           6 :       txn_out->accounts.executable_cur_lamports[ exe_cnt ] = 0UL;
    2365           6 :     }
    2366          12 :     exe_cnt++;
    2367          12 :   }
    2368         159 :   txn_out->accounts.executable_cnt = exe_cnt;
    2369         159 :   return FD_RUNTIME_EXECUTE_SUCCESS;
    2370         159 : }

Generated by: LCOV version 1.14