LCOV - code coverage report
Current view: top level - flamenco/runtime - fd_runtime.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 705 1290 54.7 %
Date: 2026-11-11 12:40:43 Functions: 42 59 71.2 %

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

Generated by: LCOV version 1.14