LCOV - code coverage report
Current view: top level - flamenco/runtime - fd_runtime.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 677 1079 62.7 %
Date: 2026-04-09 06:23:31 Functions: 38 45 84.4 %

          Line data    Source code
       1             : #include "fd_runtime.h"
       2             : #include "../capture/fd_capture_ctx.h"
       3             : #include "../types/fd_cast.h"
       4             : #include "fd_alut.h"
       5             : #include "fd_bank.h"
       6             : #include "fd_executor_err.h"
       7             : #include "fd_hashes.h"
       8             : #include "fd_runtime_err.h"
       9             : #include "fd_runtime_stack.h"
      10             : #include "fd_acc_pool.h"
      11             : #include "fd_accdb_svm.h"
      12             : #include "../genesis/fd_genesis_parse.h"
      13             : #include "fd_executor.h"
      14             : #include "sysvar/fd_sysvar_cache.h"
      15             : #include "sysvar/fd_sysvar_clock.h"
      16             : #include "sysvar/fd_sysvar_epoch_schedule.h"
      17             : #include "sysvar/fd_sysvar_recent_hashes.h"
      18             : #include "sysvar/fd_sysvar_stake_history.h"
      19             : 
      20             : #include "../stakes/fd_stakes.h"
      21             : #include "../rewards/fd_rewards.h"
      22             : #include "../accdb/fd_accdb_sync.h"
      23             : 
      24             : #include "program/fd_builtin_programs.h"
      25             : #include "program/fd_precompiles.h"
      26             : #include "program/fd_program_util.h"
      27             : #include "program/vote/fd_vote_state_versioned.h"
      28             : #include "program/vote/fd_vote_codec.h"
      29             : 
      30             : #include "sysvar/fd_sysvar_clock.h"
      31             : #include "sysvar/fd_sysvar_last_restart_slot.h"
      32             : #include "sysvar/fd_sysvar_recent_hashes.h"
      33             : #include "sysvar/fd_sysvar_rent.h"
      34             : #include "sysvar/fd_sysvar_slot_hashes.h"
      35             : #include "sysvar/fd_sysvar_slot_history.h"
      36             : 
      37             : #include "tests/fd_dump_pb.h"
      38             : 
      39             : #include "fd_system_ids.h"
      40             : 
      41             : #include "../../disco/pack/fd_pack_tip_prog_blacklist.h"
      42             : 
      43             : #include <unistd.h>
      44             : #include <sys/stat.h>
      45             : #include <sys/types.h>
      46             : #include <fcntl.h>
      47             : 
      48             : /******************************************************************************/
      49             : /* Public Runtime Helpers                                                     */
      50             : /******************************************************************************/
      51             : 
      52             : 
      53             : /*
      54             :    https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/bank.rs#L1254-L1258
      55             :    https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/bank.rs#L1749
      56             :  */
      57             : int
      58             : fd_runtime_compute_max_tick_height( ulong   ticks_per_slot,
      59             :                                     ulong   slot,
      60           0 :                                     ulong * out_max_tick_height /* out */ ) {
      61           0 :   ulong max_tick_height = 0UL;
      62           0 :   if( FD_LIKELY( ticks_per_slot > 0UL ) ) {
      63           0 :     ulong next_slot = fd_ulong_sat_add( slot, 1UL );
      64           0 :     if( FD_UNLIKELY( next_slot == slot ) ) {
      65           0 :       FD_LOG_WARNING(( "max tick height addition overflowed slot %lu ticks_per_slot %lu", slot, ticks_per_slot ));
      66           0 :       return -1;
      67           0 :     }
      68           0 :     if( FD_UNLIKELY( ULONG_MAX / ticks_per_slot < next_slot ) ) {
      69           0 :       FD_LOG_WARNING(( "max tick height multiplication overflowed slot %lu ticks_per_slot %lu", slot, ticks_per_slot ));
      70           0 :       return -1;
      71           0 :     }
      72           0 :     max_tick_height = fd_ulong_sat_mul( next_slot, ticks_per_slot );
      73           0 :   }
      74           0 :   *out_max_tick_height = max_tick_height;
      75           0 :   return FD_RUNTIME_EXECUTE_SUCCESS;
      76           0 : }
      77             : 
      78             : static void
      79             : update_next_leaders( fd_bank_t *          bank,
      80             :                      fd_runtime_stack_t * runtime_stack,
      81         129 :                      fd_vote_stakes_t *   vote_stakes ) {
      82             : 
      83         129 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
      84             : 
      85         129 :   ulong epoch    = fd_slot_to_epoch ( epoch_schedule, bank->f.slot, NULL ) + 1UL;
      86         129 :   ulong slot0    = fd_epoch_slot0   ( epoch_schedule, epoch );
      87         129 :   ulong slot_cnt = fd_epoch_slot_cnt( epoch_schedule, epoch );
      88             : 
      89         129 :   fd_top_votes_t const *   top_votes_t_1    = fd_bank_top_votes_t_1_query( bank );
      90         129 :   fd_vote_stake_weight_t * epoch_weights    = runtime_stack->stakes.stake_weights;
      91         129 :   ulong                    stake_weight_cnt = fd_stake_weights_by_node_next( top_votes_t_1, vote_stakes, bank->vote_stakes_fork_id, epoch_weights, FD_FEATURE_ACTIVE_BANK( bank, validator_admission_ticket ) );
      92             : 
      93         129 :   void * epoch_leaders_mem = fd_bank_epoch_leaders_modify( bank );
      94         129 :   fd_epoch_leaders_t * leaders = fd_epoch_leaders_join( fd_epoch_leaders_new(
      95         129 :       epoch_leaders_mem,
      96         129 :       epoch,
      97         129 :       slot0,
      98         129 :       slot_cnt,
      99         129 :       stake_weight_cnt,
     100         129 :       epoch_weights,
     101         129 :       0UL ) );
     102         129 :   if( FD_UNLIKELY( !leaders ) ) {
     103           0 :     FD_LOG_ERR(( "Unable to init and join fd_epoch_leaders" ));
     104           0 :   }
     105             : 
     106             :   /* Populate a compressed set of stake weights for a valid leader
     107             :      schedule. */
     108         129 :   fd_vote_stake_weight_t * stake_weights = runtime_stack->epoch_weights.next_stake_weights;
     109         129 :   ulong idx = 0UL;
     110             : 
     111         129 :   int needs_compression = stake_weight_cnt>MAX_COMPRESSED_STAKE_WEIGHTS;
     112             : 
     113         261 :   for( ulong i=0UL; i<stake_weight_cnt; i++ ) {
     114         132 :     fd_pubkey_t const * vote_pubkey = &epoch_weights[i].vote_key;
     115         132 :     fd_pubkey_t const * node_pubkey = &epoch_weights[i].id_key;
     116         132 :     ulong               stake       = epoch_weights[i].stake;
     117             : 
     118         132 :     if( FD_LIKELY( !needs_compression || fd_epoch_leaders_is_leader_idx( leaders, i ) ) ) {
     119         132 :       stake_weights[ idx ].stake = stake;
     120         132 :       memcpy( stake_weights[ idx ].id_key.uc,   node_pubkey, sizeof(fd_pubkey_t) );
     121         132 :       memcpy( stake_weights[ idx ].vote_key.uc, vote_pubkey, sizeof(fd_pubkey_t) );
     122         132 :       idx++;
     123         132 :     } else if( idx!=0UL && !fd_epoch_leaders_is_leader_idx( leaders, i-1UL ) ) {
     124           0 :       stake_weights[ idx-1UL ].stake += stake;
     125           0 :     } else {
     126           0 :       stake_weights[ idx ].id_key   = (fd_pubkey_t){ .uc = FD_DUMMY_ACCOUNT };
     127           0 :       stake_weights[ idx ].vote_key = (fd_pubkey_t){ .uc = FD_DUMMY_ACCOUNT };
     128           0 :       stake_weights[ idx ].stake    = stake;
     129           0 :       idx++;
     130           0 :     }
     131         132 :   }
     132         129 :   runtime_stack->epoch_weights.next_stake_weights_cnt = idx;
     133             : 
     134             :   /* Produce truncated set of id weights to send to Shred tile for
     135             :      Turbine tree computation. */
     136         129 :   ulong staked_cnt = compute_id_weights_from_vote_weights( runtime_stack->stakes.id_weights, epoch_weights, stake_weight_cnt );
     137         129 :   ulong excluded_stake = 0UL;
     138         129 :   if( FD_UNLIKELY( staked_cnt>MAX_SHRED_DESTS ) ) {
     139           0 :     for( ulong i=MAX_SHRED_DESTS; i<staked_cnt; i++ ) {
     140           0 :       excluded_stake += runtime_stack->stakes.id_weights[i].stake;
     141           0 :     }
     142           0 :   }
     143         129 :   staked_cnt = fd_ulong_min( staked_cnt, MAX_SHRED_DESTS );
     144         129 :   memcpy( runtime_stack->epoch_weights.next_id_weights, runtime_stack->stakes.id_weights, staked_cnt * sizeof(fd_stake_weight_t) );
     145         129 :   runtime_stack->epoch_weights.next_id_weights_cnt      = staked_cnt;
     146         129 :   runtime_stack->epoch_weights.next_id_weights_excluded  = excluded_stake;
     147         129 : }
     148             : 
     149             : void
     150             : fd_runtime_update_leaders( fd_bank_t *          bank,
     151         129 :                            fd_runtime_stack_t * runtime_stack ) {
     152             : 
     153         129 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     154             : 
     155         129 :   ulong epoch     = fd_slot_to_epoch ( epoch_schedule, bank->f.slot, NULL );
     156         129 :   ulong vat_epoch = fd_slot_to_epoch ( epoch_schedule, bank->f.features.validator_admission_ticket, NULL );
     157         129 :   ulong slot0     = fd_epoch_slot0   ( epoch_schedule, epoch );
     158         129 :   ulong slot_cnt  = fd_epoch_slot_cnt( epoch_schedule, epoch );
     159             : 
     160         129 :   fd_vote_stakes_t * vote_stakes = fd_bank_vote_stakes( bank );
     161             : 
     162         129 :   update_next_leaders( bank, runtime_stack, vote_stakes );
     163             : 
     164         129 :   int vat_in_prev = epoch>=vat_epoch+1UL ? 1 : 0;
     165             : 
     166         129 :   fd_top_votes_t const *   top_votes_t_2    = fd_bank_top_votes_t_2_query( bank );
     167         129 :   fd_vote_stake_weight_t * epoch_weights    = runtime_stack->stakes.stake_weights;
     168         129 :   ulong                    stake_weight_cnt = fd_stake_weights_by_node( top_votes_t_2, vote_stakes, bank->vote_stakes_fork_id, epoch_weights, vat_in_prev );
     169             : 
     170             :   /* TODO: Can optimize by avoiding recomputing if another fork has
     171             :      already computed them for this epoch. */
     172         129 :   void * epoch_leaders_mem = fd_bank_epoch_leaders_modify( bank );
     173         129 :   fd_epoch_leaders_t * leaders = fd_epoch_leaders_join( fd_epoch_leaders_new(
     174         129 :       epoch_leaders_mem,
     175         129 :       epoch,
     176         129 :       slot0,
     177         129 :       slot_cnt,
     178         129 :       stake_weight_cnt,
     179         129 :       epoch_weights,
     180         129 :       0UL ) );
     181         129 :   if( FD_UNLIKELY( !leaders ) ) {
     182           0 :     FD_LOG_ERR(( "Unable to init and join fd_epoch_leaders" ));
     183           0 :   }
     184             : 
     185             :   /* Populate a compressed set of stake weights for a valid leader
     186             :      schedule. */
     187         129 :   fd_vote_stake_weight_t * stake_weights = runtime_stack->epoch_weights.stake_weights;
     188         129 :   ulong idx = 0UL;
     189             : 
     190         129 :   int needs_compression = stake_weight_cnt>MAX_COMPRESSED_STAKE_WEIGHTS;
     191             : 
     192         264 :   for( ulong i=0UL; i<leaders->pub_cnt; i++ ) {
     193         135 :     fd_pubkey_t const * vote_pubkey = &epoch_weights[i].vote_key;
     194         135 :     fd_pubkey_t const * node_pubkey = &epoch_weights[i].id_key;
     195         135 :     ulong               stake       = epoch_weights[i].stake;
     196             : 
     197         135 :     if( FD_LIKELY( !needs_compression || fd_epoch_leaders_is_leader_idx( leaders, i ) ) ) {
     198         135 :       stake_weights[ idx ].stake = stake;
     199         135 :       memcpy( stake_weights[ idx ].id_key.uc,   node_pubkey, sizeof(fd_pubkey_t) );
     200         135 :       memcpy( stake_weights[ idx ].vote_key.uc, vote_pubkey, sizeof(fd_pubkey_t) );
     201         135 :       idx++;
     202         135 :     } else if( idx!=0UL && !fd_epoch_leaders_is_leader_idx( leaders, i-1UL ) ) {
     203           0 :       stake_weights[ idx-1UL ].stake += stake;
     204           0 :     } else {
     205           0 :       stake_weights[ idx ].id_key   = (fd_pubkey_t){ .uc = FD_DUMMY_ACCOUNT };
     206           0 :       stake_weights[ idx ].vote_key = (fd_pubkey_t){ .uc = FD_DUMMY_ACCOUNT };
     207           0 :       stake_weights[ idx ].stake    = stake;
     208           0 :       idx++;
     209           0 :     }
     210         135 :   }
     211         129 :   runtime_stack->epoch_weights.stake_weights_cnt = idx;
     212             : 
     213             :   /* Produce truncated set of id weights to send to Shred tile for
     214             :      Turbine tree computation. */
     215         129 :   ulong staked_cnt = compute_id_weights_from_vote_weights( runtime_stack->stakes.id_weights, epoch_weights, stake_weight_cnt );
     216         129 :   ulong excluded_stake = 0UL;
     217         129 :   if( FD_UNLIKELY( staked_cnt>MAX_SHRED_DESTS ) ) {
     218           0 :     for( ulong i=MAX_SHRED_DESTS; i<staked_cnt; i++ ) {
     219           0 :       excluded_stake += runtime_stack->stakes.id_weights[i].stake;
     220           0 :     }
     221           0 :   }
     222         129 :   staked_cnt = fd_ulong_min( staked_cnt, MAX_SHRED_DESTS );
     223         129 :   memcpy( runtime_stack->epoch_weights.id_weights, runtime_stack->stakes.id_weights, staked_cnt * sizeof(fd_stake_weight_t) );
     224         129 :   runtime_stack->epoch_weights.id_weights_cnt      = staked_cnt;
     225         129 :   runtime_stack->epoch_weights.id_weights_excluded = excluded_stake;
     226         129 : }
     227             : 
     228             : /******************************************************************************/
     229             : /* Various Private Runtime Helpers                                            */
     230             : /******************************************************************************/
     231             : 
     232             : static int
     233             : fd_runtime_validate_fee_collector( fd_bank_t const *     bank,
     234             :                                    fd_accdb_ro_t const * collector,
     235          12 :                                    ulong                 fee ) {
     236          12 :   if( FD_UNLIKELY( !fee ) ) FD_LOG_CRIT(( "invariant violation: fee>0" ));
     237             : 
     238          12 :   if( FD_UNLIKELY( !fd_pubkey_eq( fd_accdb_ref_owner( collector ), &fd_solana_system_program_id ) ) ) {
     239           3 :     return 0;
     240           3 :   }
     241             : 
     242             :   /* https://github.com/anza-xyz/agave/blob/v1.18.23/runtime/src/bank/fee_distribution.rs#L111
     243             :      https://github.com/anza-xyz/agave/blob/v1.18.23/runtime/src/accounts/account_rent_state.rs#L39
     244             :      In agave's fee deposit code, rent state transition check logic is as follows:
     245             :      The transition is NOT allowed iff
     246             :      === BEGIN
     247             :      the post deposit account is rent paying AND the pre deposit account is not rent paying
     248             :      OR
     249             :      the post deposit account is rent paying AND the pre deposit account is rent paying AND !(post_data_size == pre_data_size && post_lamports <= pre_lamports)
     250             :      === END
     251             :      post_data_size == pre_data_size is always true during fee deposit.
     252             :      However, post_lamports > pre_lamports because we are paying a >0 amount.
     253             :      So, the above reduces down to
     254             :      === BEGIN
     255             :      the post deposit account is rent paying AND the pre deposit account is not rent paying
     256             :      OR
     257             :      the post deposit account is rent paying AND the pre deposit account is rent paying AND TRUE
     258             :      === END
     259             :      This is equivalent to checking that the post deposit account is rent paying.
     260             :      An account is rent paying if the post deposit balance is >0 AND it's not rent exempt.
     261             :      We already know that the post deposit balance is >0 because we are paying a >0 amount.
     262             :      So TLDR we just check if the account is rent exempt.
     263             :    */
     264           9 :   fd_rent_t const * rent = &bank->f.rent;
     265           9 :   ulong minbal  = fd_rent_exempt_minimum_balance( rent, fd_accdb_ref_data_sz( collector ) );
     266           9 :   ulong balance = fd_accdb_ref_lamports( collector );
     267           9 :   if( FD_UNLIKELY( __builtin_uaddl_overflow( balance, fee, &balance ) ) ) {
     268           0 :     FD_BASE58_ENCODE_32_BYTES( fd_accdb_ref_address( collector ), addr_b58 );
     269           0 :     FD_LOG_EMERG(( "integer overflow while crediting %lu fee reward lamports to %s (previous balance %lu)",
     270           0 :                    fee, addr_b58, fd_accdb_ref_lamports( collector ) ));
     271           0 :   }
     272           9 :   if( FD_UNLIKELY( balance<minbal ) ) {
     273             :     /* fee collector not rent exempt after payout */
     274           3 :     return 0;
     275           3 :   }
     276             : 
     277           6 :   return 1;
     278           9 : }
     279             : 
     280             : static void
     281             : fd_runtime_run_incinerator( fd_bank_t *               bank,
     282             :                             fd_accdb_user_t *         accdb,
     283             :                             fd_funk_txn_xid_t const * xid,
     284          78 :                             fd_capture_ctx_t *        capture_ctx ) {
     285          78 :   fd_accdb_svm_remove( accdb, bank, xid, capture_ctx, &fd_sysvar_incinerator_id );
     286          78 : }
     287             : 
     288             : /* fd_runtime_settle_fees settles transaction fees accumulated during a
     289             :    slot.  A portion is burnt, another portion is credited to the fee
     290             :    collector (typically leader). */
     291             : 
     292             : static void
     293             : fd_runtime_settle_fees( fd_bank_t *               bank,
     294             :                         fd_accdb_user_t *         accdb,
     295             :                         fd_funk_txn_xid_t const * xid,
     296          78 :                         fd_capture_ctx_t *        capture_ctx ) {
     297             : 
     298          78 :   ulong slot           = bank->f.slot;
     299          78 :   ulong execution_fees = bank->f.execution_fees;
     300          78 :   ulong priority_fees  = bank->f.priority_fees;
     301          78 :   ulong total_fees;
     302          78 :   if( FD_UNLIKELY( __builtin_uaddl_overflow( execution_fees, priority_fees, &total_fees ) ) ) {
     303           0 :     FD_LOG_EMERG(( "fee overflow detected (slot=%lu execution_fees=%lu priority_fees=%lu)",
     304           0 :                    slot, execution_fees, priority_fees ));
     305           0 :   }
     306             : 
     307          78 :   ulong fee_burn   = execution_fees / 2;
     308          78 :   ulong fee_reward = fd_ulong_sat_add( priority_fees, execution_fees - fee_burn );
     309             : 
     310             :   /* Remove fee balance from bank (decreasing capitalization) */
     311          78 :   if( FD_UNLIKELY( total_fees > bank->f.capitalization ) ) {
     312           0 :     FD_LOG_EMERG(( "fee settlement would underflow capitalization (slot=%lu total_fees=%lu cap=%lu)",
     313           0 :                    slot, total_fees, bank->f.capitalization ));
     314           0 :   }
     315          78 :   bank->f.capitalization -= total_fees;
     316          78 :   bank->f.execution_fees  = 0;
     317          78 :   bank->f.priority_fees   = 0;
     318             : 
     319          78 :   if( FD_LIKELY( fee_reward ) ) {
     320          12 :     fd_epoch_leaders_t const * leaders = fd_bank_epoch_leaders_query( bank );
     321          12 :     if( FD_UNLIKELY( !leaders ) ) FD_LOG_CRIT(( "fd_bank_epoch_leaders_query returned NULL" ));
     322          12 :     fd_pubkey_t const * leader = fd_epoch_leaders_get( leaders, bank->f.slot );
     323          12 :     if( FD_UNLIKELY( !leader ) ) FD_LOG_CRIT(( "fd_epoch_leaders_get(%lu) returned NULL", bank->f.slot ));
     324             : 
     325             :     /* Pay out reward portion of collected fees (increasing capitalization) */
     326          12 :     fd_accdb_rw_t rw[1];
     327          12 :     fd_accdb_svm_update_t update[1];
     328          12 :     FD_TEST( fd_accdb_svm_open_rw(
     329          12 :         accdb, bank, xid,
     330          12 :         rw, update,
     331          12 :         leader,
     332          12 :         0UL,
     333          12 :         FD_ACCDB_FLAG_CREATE
     334          12 :     ) );
     335          12 :     if( FD_UNLIKELY( !fd_runtime_validate_fee_collector( bank, rw->ro, fee_reward ) ) ) {  /* validation failed */
     336           6 :       FD_LOG_INFO(( "slot %lu has an invalid fee collector, burning fee reward (%lu lamports)", bank->f.slot, fee_reward ));
     337           6 :     } else {
     338             :       /* Guaranteed to not overflow, checked above */
     339           6 :       fd_accdb_ref_lamports_set( rw, fd_accdb_ref_lamports( rw->ro ) + fee_reward );
     340           6 :     }
     341          12 :     fd_accdb_svm_close_rw( accdb, bank, capture_ctx, rw, update );
     342          12 :   }
     343             : 
     344          78 :   FD_LOG_INFO(( "slot=%lu priority_fees=%lu execution_fees=%lu fee_burn=%lu fee_rewards=%lu",
     345          78 :                 slot,
     346          78 :                 priority_fees, execution_fees, fee_burn, fee_reward ));
     347          78 : }
     348             : 
     349             : static void
     350             : fd_runtime_freeze( fd_bank_t *         bank,
     351             :                    fd_accdb_user_t *   accdb,
     352          78 :                    fd_capture_ctx_t *  capture_ctx ) {
     353             : 
     354          78 :   fd_funk_txn_xid_t const xid = { .ul = { bank->f.slot, bank->idx } };
     355             : 
     356          78 :   if( FD_LIKELY( bank->f.slot != 0UL ) ) {
     357          78 :     fd_sysvar_recent_hashes_update( bank, accdb, &xid, capture_ctx );
     358          78 :   }
     359             : 
     360          78 :   fd_sysvar_slot_history_update( bank, accdb, &xid, capture_ctx );
     361             : 
     362          78 :   fd_runtime_settle_fees( bank, accdb, &xid, capture_ctx );
     363             : 
     364             :   /* jito collects a 3% fee at the end of the block + 3% fee at
     365             :      distribution time. */
     366          78 :   ulong tips_pre_comission = bank->f.tips;
     367          78 :   bank->f.tips = (tips_pre_comission - (tips_pre_comission * 6UL / 100UL));
     368             : 
     369          78 :   fd_runtime_run_incinerator( bank, accdb, &xid, capture_ctx );
     370             : 
     371          78 : }
     372             : 
     373             : /******************************************************************************/
     374             : /* Block-Level Execution Preparation/Finalization                             */
     375             : /******************************************************************************/
     376             : void
     377             : fd_runtime_new_fee_rate_governor_derived( fd_bank_t * bank,
     378         285 :                                           ulong       latest_signatures_per_slot ) {
     379             : 
     380         285 :   fd_fee_rate_governor_t const * base_fee_rate_governor = &bank->f.fee_rate_governor;
     381             : 
     382         285 :   ulong old_lamports_per_signature = bank->f.rbh_lamports_per_sig;
     383             : 
     384         285 :   fd_fee_rate_governor_t me = {
     385         285 :     .target_signatures_per_slot    = base_fee_rate_governor->target_signatures_per_slot,
     386         285 :     .target_lamports_per_signature = base_fee_rate_governor->target_lamports_per_signature,
     387         285 :     .max_lamports_per_signature    = base_fee_rate_governor->max_lamports_per_signature,
     388         285 :     .min_lamports_per_signature    = base_fee_rate_governor->min_lamports_per_signature,
     389         285 :     .burn_percent                  = base_fee_rate_governor->burn_percent
     390         285 :   };
     391             : 
     392         285 :   ulong new_lamports_per_signature = 0;
     393         285 :   if( me.target_signatures_per_slot > 0 ) {
     394           6 :     me.min_lamports_per_signature = fd_ulong_max( 1UL, (ulong)(me.target_lamports_per_signature / 2) );
     395           6 :     me.max_lamports_per_signature = me.target_lamports_per_signature * 10;
     396           6 :     ulong desired_lamports_per_signature = fd_ulong_min(
     397           6 :       me.max_lamports_per_signature,
     398           6 :       fd_ulong_max(
     399           6 :         me.min_lamports_per_signature,
     400           6 :         me.target_lamports_per_signature
     401           6 :         * fd_ulong_min(latest_signatures_per_slot, (ulong)UINT_MAX)
     402           6 :         / me.target_signatures_per_slot
     403           6 :       )
     404           6 :     );
     405           6 :     long gap = (long)desired_lamports_per_signature - (long)old_lamports_per_signature;
     406           6 :     if ( gap == 0 ) {
     407           0 :       new_lamports_per_signature = desired_lamports_per_signature;
     408           6 :     } else {
     409           6 :       long gap_adjust = (long)(fd_ulong_max( 1UL, (ulong)(me.target_lamports_per_signature / 20) ))
     410           6 :         * (gap != 0)
     411           6 :         * (gap > 0 ? 1 : -1);
     412           6 :       new_lamports_per_signature = fd_ulong_min(
     413           6 :         me.max_lamports_per_signature,
     414           6 :         fd_ulong_max(
     415           6 :           me.min_lamports_per_signature,
     416           6 :           (ulong)((long)old_lamports_per_signature + gap_adjust)
     417           6 :         )
     418           6 :       );
     419           6 :     }
     420         279 :   } else {
     421         279 :     new_lamports_per_signature = base_fee_rate_governor->target_lamports_per_signature;
     422         279 :     me.min_lamports_per_signature = me.target_lamports_per_signature;
     423         279 :     me.max_lamports_per_signature = me.target_lamports_per_signature;
     424         279 :   }
     425         285 :   bank->f.fee_rate_governor = me;
     426         285 :   bank->f.rbh_lamports_per_sig = new_lamports_per_signature;
     427         285 : }
     428             : 
     429             : /******************************************************************************/
     430             : /* Epoch Boundary                                                             */
     431             : /******************************************************************************/
     432             : 
     433             : /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6704 */
     434             : static void
     435             : fd_apply_builtin_program_feature_transitions( fd_bank_t *               bank,
     436             :                                               fd_accdb_user_t *         accdb,
     437             :                                               fd_funk_txn_xid_t const * xid,
     438             :                                               fd_runtime_stack_t *      runtime_stack,
     439         129 :                                               fd_capture_ctx_t *        capture_ctx ) {
     440             :   /* TODO: Set the upgrade authority properly from the core bpf migration config. Right now it's set to None.
     441             : 
     442             :      Migrate any necessary stateless builtins to core BPF. So far,
     443             :      the only "stateless" builtin is the Feature program. Beginning
     444             :      checks in the migrate_builtin_to_core_bpf function will fail if the
     445             :      program has already been migrated to BPF. */
     446             : 
     447         129 :   fd_builtin_program_t const * builtins = fd_builtins();
     448        1290 :   for( ulong i=0UL; i<fd_num_builtins(); i++ ) {
     449             :     /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6732-L6751 */
     450        1161 :     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 ) ) {
     451           0 :       FD_BASE58_ENCODE_32_BYTES( builtins[i].pubkey->key, pubkey_b58 );
     452           0 :       FD_LOG_DEBUG(( "Migrating builtin program %s to core BPF", pubkey_b58 ));
     453           0 :       fd_migrate_builtin_to_core_bpf( bank, accdb, xid, runtime_stack, builtins[i].core_bpf_migration_config, capture_ctx );
     454           0 :     }
     455             :     /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6753-L6774 */
     456        1161 :     if( builtins[i].enable_feature_offset!=NO_ENABLE_FEATURE_ID && FD_FEATURE_JUST_ACTIVATED_OFFSET( bank, builtins[i].enable_feature_offset ) ) {
     457           0 :       FD_BASE58_ENCODE_32_BYTES( builtins[i].pubkey->key, pubkey_b58 );
     458           0 :       FD_LOG_DEBUG(( "Enabling builtin program %s", pubkey_b58 ));
     459           0 :       fd_write_builtin_account( bank, accdb, xid, capture_ctx, *builtins[i].pubkey, builtins[i].data,strlen(builtins[i].data) );
     460           0 :     }
     461        1161 :   }
     462             : 
     463             :   /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6776-L6793 */
     464         129 :   fd_stateless_builtin_program_t const * stateless_builtins = fd_stateless_builtins();
     465         387 :   for( ulong i=0UL; i<fd_num_stateless_builtins(); i++ ) {
     466         258 :     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 ) ) {
     467           0 :       FD_BASE58_ENCODE_32_BYTES( stateless_builtins[i].pubkey->key, pubkey_b58 );
     468           0 :       FD_LOG_DEBUG(( "Migrating stateless builtin program %s to core BPF", pubkey_b58 ));
     469           0 :       fd_migrate_builtin_to_core_bpf( bank, accdb, xid, runtime_stack, stateless_builtins[i].core_bpf_migration_config, capture_ctx );
     470           0 :     }
     471         258 :   }
     472             : 
     473             :   /* https://github.com/anza-xyz/agave/blob/c1080de464cfb578c301e975f498964b5d5313db/runtime/src/bank.rs#L6795-L6805 */
     474         516 :   for( fd_precompile_program_t const * precompiles = fd_precompiles(); precompiles->verify_fn; precompiles++ ) {
     475         387 :     if( precompiles->feature_offset != NO_ENABLE_FEATURE_ID &&
     476         387 :         FD_FEATURE_JUST_ACTIVATED_OFFSET( bank, precompiles->feature_offset ) ) {
     477           0 :       fd_write_builtin_account( bank, accdb, xid, capture_ctx, *precompiles->pubkey, "", 0 );
     478           0 :     }
     479         387 :   }
     480         129 : }
     481             : 
     482             : static void
     483             : fd_feature_activate( fd_bank_t *               bank,
     484             :                      fd_accdb_user_t *         accdb,
     485             :                      fd_funk_txn_xid_t const * xid,
     486             :                      fd_capture_ctx_t *        capture_ctx,
     487             :                      fd_feature_id_t const *   id,
     488       34830 :                      fd_pubkey_t const *       addr ) {
     489       34830 :   fd_features_t * features = &bank->f.features;
     490             : 
     491       34830 :   if( id->reverted==1 ) return;
     492             : 
     493       33411 :   fd_accdb_ro_t ro[1];
     494       33411 :   if( FD_UNLIKELY( !fd_accdb_open_ro( accdb, ro, xid, addr ) ) ) {
     495       33399 :     return;
     496       33399 :   }
     497             : 
     498          12 :   if( FD_UNLIKELY( !fd_pubkey_eq( fd_accdb_ref_owner( ro ), &fd_solana_feature_program_id ) ) ) {
     499             :     /* Feature account not yet initialized */
     500           3 :     fd_accdb_close_ro( accdb, ro );
     501           3 :     return;
     502           3 :   }
     503             : 
     504           9 :   FD_BASE58_ENCODE_32_BYTES( addr->uc, addr_b58 );
     505             : 
     506           9 :   fd_feature_t feature;
     507           9 :   if( FD_UNLIKELY( !fd_feature_decode( &feature, fd_accdb_ref_data_const( ro ), fd_accdb_ref_data_sz( ro ) ) ) ) {
     508           3 :     FD_LOG_WARNING(( "cannot activate feature %s, corrupt account data", addr_b58 ));
     509           3 :     FD_LOG_HEXDUMP_NOTICE(( "corrupt feature account", fd_accdb_ref_data_const( ro ), fd_accdb_ref_data_sz( ro ) ));
     510           3 :     fd_accdb_close_ro( accdb, ro );
     511           3 :     return;
     512           3 :   }
     513           6 :   fd_accdb_close_ro( accdb, ro );
     514             : 
     515           6 :   if( feature.is_active ) {
     516           3 :     FD_LOG_DEBUG(( "feature %s already activated at slot %lu", addr_b58, feature.activation_slot ));
     517           3 :     fd_features_set( features, id, feature.activation_slot);
     518           3 :   } else {
     519           3 :     FD_LOG_DEBUG(( "feature %s not activated at slot %lu, activating", addr_b58, bank->f.slot ));
     520           3 :     fd_accdb_rw_t rw[1]; fd_accdb_svm_update_t update[1];
     521           3 :     if( FD_UNLIKELY( !fd_accdb_svm_open_rw( accdb, bank, xid, rw, update, addr, 0UL, 0 ) ) ) return;
     522           3 :     FD_TEST( fd_accdb_ref_data_sz( rw->ro )>=sizeof(fd_feature_t) );
     523           3 :     feature.is_active       = 1;
     524           3 :     feature.activation_slot = bank->f.slot;
     525           3 :     FD_STORE( fd_feature_t, fd_accdb_ref_data( rw ), feature );
     526           3 :     fd_accdb_svm_close_rw( accdb, bank, capture_ctx, rw, update );
     527           3 :   }
     528           6 : }
     529             : 
     530             : static void
     531             : fd_features_activate( fd_bank_t *               bank,
     532             :                       fd_accdb_user_t  *        accdb,
     533             :                       fd_funk_txn_xid_t const * xid,
     534         129 :                       fd_capture_ctx_t *        capture_ctx ) {
     535         129 :   for( fd_feature_id_t const * id = fd_feature_iter_init();
     536       34959 :                                    !fd_feature_iter_done( id );
     537       34830 :                                id = fd_feature_iter_next( id ) ) {
     538       34830 :     fd_feature_activate( bank, accdb, xid, capture_ctx, id, &id->id );
     539       34830 :   }
     540         129 : }
     541             : 
     542             : /* SIMD-0194: deprecate_rent_exemption_threshold
     543             :    https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5322-L5329 */
     544             : static void
     545             : deprecate_rent_exemption_threshold( fd_bank_t *               bank,
     546             :                                     fd_accdb_user_t *         accdb,
     547             :                                     fd_funk_txn_xid_t const * xid,
     548           3 :                                     fd_capture_ctx_t *        capture_ctx ) {
     549             :   /* We use the bank fields here to mirror Agave - in mainnet, devnet
     550             :      and testnet Agave's bank rent.burn_percent field is different to
     551             :      the value in the sysvar. When this feature is activated in Agave,
     552             :      the sysvar inherits the value from the bank. */
     553           3 :   fd_rent_t rent               = bank->f.rent;
     554           3 :   rent.lamports_per_uint8_year = fd_rust_cast_double_to_ulong(
     555           3 :     (double)rent.lamports_per_uint8_year * rent.exemption_threshold );
     556           3 :   rent.exemption_threshold     = FD_SIMD_0194_NEW_RENT_EXEMPTION_THRESHOLD;
     557             : 
     558             :   /* We don't refresh the sysvar cache here. The cache is refreshed in
     559             :      fd_sysvar_cache_restore, which is called at the start of every
     560             :      block in fd_runtime_block_execute_prepare, after this function. */
     561           3 :   fd_sysvar_rent_write( bank, accdb, xid, capture_ctx, &rent );
     562           3 :   bank->f.rent = rent;
     563           3 : }
     564             : 
     565             : // https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5296-L5391
     566             : static void
     567             : fd_compute_and_apply_new_feature_activations( fd_bank_t *               bank,
     568             :                                               fd_accdb_user_t *         accdb,
     569             :                                               fd_funk_txn_xid_t const * xid,
     570             :                                               fd_runtime_stack_t *      runtime_stack,
     571         129 :                                               fd_capture_ctx_t *        capture_ctx ) {
     572             :   /* Activate new features
     573             :       https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5296-L5391 */
     574         129 :   fd_features_activate( bank, accdb, xid, capture_ctx );
     575         129 :   fd_features_restore( bank, accdb, xid );
     576             : 
     577             :   /* SIMD-0194: deprecate_rent_exemption_threshold
     578             :       https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5322-L5329 */
     579         129 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, deprecate_rent_exemption_threshold ) ) ) {
     580           3 :     deprecate_rent_exemption_threshold( bank, accdb, xid, capture_ctx );
     581           3 :   }
     582             : 
     583             :   /* Apply builtin program feature transitions
     584             :       https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6621-L6624 */
     585         129 :   fd_apply_builtin_program_feature_transitions( bank, accdb, xid, runtime_stack, capture_ctx );
     586             : 
     587         129 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, vote_state_v4 ) ) ) {
     588           0 :     fd_upgrade_core_bpf_program( bank, accdb, xid, runtime_stack, &fd_solana_stake_program_id, &fd_solana_stake_program_vote_state_v4_buffer_address, capture_ctx );
     589           0 :   }
     590             : 
     591             :   /* https://github.com/anza-xyz/agave/blob/v4.0.0-beta.2/runtime/src/bank.rs#L5703-L5716 */
     592         129 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, replace_spl_token_with_p_token ) ) ) {
     593           0 :     fd_upgrade_loader_v2_program_with_loader_v3_program(
     594           0 :       bank,
     595           0 :       accdb,
     596           0 :       xid,
     597           0 :       runtime_stack,
     598           0 :       &fd_solana_spl_token_id,
     599           0 :       &fd_solana_ptoken_program_buffer_address,
     600           0 :       FD_FEATURE_ACTIVE_BANK( bank, relax_programdata_account_check_migration ),
     601           0 :       capture_ctx );
     602           0 :   }
     603             : 
     604             :   /* https://github.com/anza-xyz/agave/blob/v4.0.0-beta.4/runtime/src/bank.rs#L5736-L5744 */
     605         129 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, upgrade_bpf_stake_program_to_v5 ) ) ) {
     606           0 :     fd_upgrade_core_bpf_program(
     607           0 :       bank,
     608           0 :       accdb,
     609           0 :       xid,
     610           0 :       runtime_stack,
     611           0 :       &fd_solana_stake_program_id,
     612           0 :       &fd_solana_stake_program_v5_buffer_address,
     613           0 :       capture_ctx );
     614           0 :   }
     615         129 : }
     616             : 
     617             : /* Starting a new epoch.
     618             :   New epoch:        T
     619             :   Just ended epoch: T-1
     620             :   Epoch before:     T-2
     621             : 
     622             :   In this function:
     623             :   - stakes in T-2 (vote_states_prev_prev) should be replaced by T-1 (vote_states_prev)
     624             :   - stakes at T-1 (vote_states_prev) should be replaced by updated stakes at T (vote_states)
     625             :   - leader schedule should be calculated using new T-2 stakes (vote_states_prev_prev)
     626             : 
     627             :   Invariant during an epoch T:
     628             :   vote_states_prev holds the stakes at T-1
     629             :   vote_states_prev_prev holds the stakes at T-2
     630             :  */
     631             : /* process for the start of a new epoch */
     632             : static void
     633             : fd_runtime_process_new_epoch( fd_banks_t *              banks,
     634             :                               fd_bank_t *               bank,
     635             :                               fd_accdb_user_t *         accdb,
     636             :                               fd_funk_txn_xid_t const * xid,
     637             :                               fd_capture_ctx_t *        capture_ctx,
     638             :                               ulong                     parent_epoch,
     639         129 :                               fd_runtime_stack_t *      runtime_stack ) {
     640         129 :   long start = fd_log_wallclock();
     641             : 
     642         129 :   fd_compute_and_apply_new_feature_activations( bank, accdb, xid, runtime_stack, capture_ctx );
     643             : 
     644             :   /* Update the cached warmup/cooldown rate epoch now that features may
     645             :      have changed (reduce_stake_warmup_cooldown may have just activated). */
     646         129 :   bank->f.warmup_cooldown_rate_epoch = fd_slot_to_epoch( &bank->f.epoch_schedule,
     647         129 :                                                          bank->f.features.reduce_stake_warmup_cooldown,
     648         129 :                                                          NULL );
     649             : 
     650             :   /* Updates stake history sysvar accumulated values and recomputes
     651             :      stake delegations for vote accounts. */
     652             : 
     653         129 :   fd_stake_delegations_t const * stake_delegations = fd_bank_stake_delegations_frontier_query( banks, bank );
     654         129 :   if( FD_UNLIKELY( !stake_delegations ) ) {
     655           0 :     FD_LOG_CRIT(( "stake_delegations is NULL" ));
     656           0 :   }
     657             : 
     658         129 :   fd_stakes_activate_epoch( bank, runtime_stack, accdb, xid, capture_ctx, stake_delegations,
     659         129 :                             &bank->f.warmup_cooldown_rate_epoch );
     660             : 
     661             :   /* Distribute rewards.  This involves calculating the rewards for
     662             :      every vote and stake account. */
     663             : 
     664         129 :   fd_hash_t const * parent_blockhash = fd_blockhashes_peek_last_hash( &bank->f.block_hash_queue );
     665         129 :   fd_begin_partitioned_rewards( bank,
     666         129 :                                 accdb,
     667         129 :                                 xid,
     668         129 :                                 runtime_stack,
     669         129 :                                 capture_ctx,
     670         129 :                                 stake_delegations,
     671         129 :                                 parent_blockhash,
     672         129 :                                 parent_epoch );
     673             : 
     674         129 :   fd_bank_stake_delegations_end_frontier_query( banks, bank );
     675             : 
     676             :   /* The Agave client handles updating their stakes cache with a call to
     677             :      update_epoch_stakes() which keys stakes by the leader schedule
     678             :      epochs and retains up to 6 epochs of stakes.  However, to correctly
     679             :      calculate the leader schedule, we just need to maintain the vote
     680             :      states for the current epoch, the previous epoch, and the one
     681             :      before that.
     682             :      https://github.com/anza-xyz/agave/blob/v3.0.4/runtime/src/bank.rs#L2175
     683             :   */
     684             : 
     685             :   /* Now that our stakes caches have been updated, we can calculate the
     686             :      leader schedule for the upcoming epoch epoch using our new
     687             :      vote_states_prev_prev (stakes for T-2). */
     688             : 
     689         129 :   fd_runtime_update_leaders( bank, runtime_stack );
     690             : 
     691         129 :   long end = fd_log_wallclock();
     692         129 :   FD_LOG_NOTICE(( "starting epoch %lu at slot %lu took %.6f seconds", bank->f.epoch, bank->f.slot, (double)(end - start) / 1e9 ));
     693         129 : }
     694             : 
     695             : static void
     696             : fd_runtime_block_pre_execute_process_new_epoch( fd_banks_t *              banks,
     697             :                                                 fd_bank_t *               bank,
     698             :                                                 fd_accdb_user_t *         accdb,
     699             :                                                 fd_funk_txn_xid_t const * xid,
     700             :                                                 fd_capture_ctx_t *        capture_ctx,
     701             :                                                 fd_runtime_stack_t *      runtime_stack,
     702         285 :                                                 int *                     is_epoch_boundary ) {
     703             : 
     704         285 :   ulong const slot = bank->f.slot;
     705         285 :   if( FD_LIKELY( slot != 0UL ) ) {
     706         285 :     fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     707             : 
     708         285 :     ulong prev_epoch = fd_slot_to_epoch( epoch_schedule, bank->f.parent_slot, NULL );
     709         285 :     ulong slot_idx;
     710         285 :     ulong new_epoch  = fd_slot_to_epoch( epoch_schedule, slot, &slot_idx );
     711         285 :     if( FD_UNLIKELY( slot_idx==1UL && new_epoch==0UL ) ) {
     712             :       /* The block after genesis has a height of 1. */
     713           0 :       bank->f.block_height = 1UL;
     714           0 :     }
     715             : 
     716         285 :     if( FD_UNLIKELY( prev_epoch<new_epoch || !slot_idx ) ) {
     717         129 :       FD_LOG_DEBUG(( "Epoch boundary starting" ));
     718         129 :       fd_runtime_process_new_epoch( banks, bank, accdb, xid, capture_ctx, prev_epoch, runtime_stack );
     719         129 :       *is_epoch_boundary = 1;
     720         156 :     } else {
     721         156 :       *is_epoch_boundary = 0;
     722         156 :     }
     723             : 
     724         285 :     fd_distribute_partitioned_epoch_rewards( bank, accdb, xid, capture_ctx );
     725         285 :   } else {
     726           0 :     *is_epoch_boundary = 0;
     727           0 :   }
     728         285 : }
     729             : 
     730             : 
     731             : static void
     732             : fd_runtime_block_sysvar_update_pre_execute( fd_bank_t *               bank,
     733             :                                             fd_accdb_user_t *         accdb,
     734             :                                             fd_funk_txn_xid_t const * xid,
     735             :                                             fd_runtime_stack_t *      runtime_stack,
     736         285 :                                             fd_capture_ctx_t *        capture_ctx ) {
     737             :   // let (fee_rate_governor, fee_components_time_us) = measure_us!(
     738             :   //     FeeRateGovernor::new_derived(&parent.fee_rate_governor, parent.signature_count())
     739             :   // );
     740             :   /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L1312-L1314 */
     741             : 
     742         285 :   fd_runtime_new_fee_rate_governor_derived( bank, bank->f.parent_signature_cnt );
     743             : 
     744         285 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     745         285 :   ulong                       parent_epoch   = fd_slot_to_epoch( epoch_schedule, bank->f.parent_slot, NULL );
     746         285 :   fd_sysvar_clock_update( bank, accdb, xid, capture_ctx, runtime_stack, &parent_epoch );
     747             : 
     748             :   // It has to go into the current txn previous info but is not in slot 0
     749         285 :   if( bank->f.slot != 0 ) {
     750         285 :     fd_sysvar_slot_hashes_update( bank, accdb, xid, capture_ctx );
     751         285 :   }
     752         285 :   fd_sysvar_last_restart_slot_update( bank, accdb, xid, capture_ctx, bank->f.last_restart_slot );
     753         285 : }
     754             : 
     755             : int
     756             : fd_runtime_load_txn_address_lookup_tables( fd_txn_in_t const *       txn_in,
     757             :                                            fd_txn_t const *          txn,
     758             :                                            uchar const *             payload,
     759             :                                            fd_accdb_user_t *         accdb,
     760             :                                            fd_funk_txn_xid_t const * xid,
     761             :                                            ulong                     slot,
     762             :                                            fd_slot_hash_t const *    hashes, /* deque */
     763          90 :                                            fd_acct_addr_t *          out_accts_alt ) {
     764             : 
     765          90 :   if( FD_LIKELY( txn->transaction_version!=FD_TXN_V0 ) ) return FD_RUNTIME_EXECUTE_SUCCESS;
     766             : 
     767          90 :   fd_alut_interp_t interp[1];
     768          90 :   fd_alut_interp_new(
     769          90 :       interp,
     770          90 :       out_accts_alt,
     771          90 :       txn,
     772          90 :       payload,
     773          90 :       hashes,
     774          90 :       slot );
     775             : 
     776          90 :   fd_txn_acct_addr_lut_t const * addr_luts = fd_txn_get_address_tables_const( txn );
     777          93 :   for( ulong i=0UL; i<txn->addr_table_lookup_cnt; i++ ) {
     778           3 :     fd_txn_acct_addr_lut_t const * addr_lut = &addr_luts[i];
     779           3 :     fd_pubkey_t addr_lut_acc = FD_LOAD( fd_pubkey_t, payload+addr_lut->addr_off );
     780             : 
     781             :     /* https://github.com/anza-xyz/agave/blob/368ea563c423b0a85cc317891187e15c9a321521/accounts-db/src/accounts.rs#L90-L94 */
     782           3 :     fd_accdb_ro_t alut_ro[1];
     783             : 
     784           3 :     int is_found = 0;
     785           3 :     if( FD_UNLIKELY( txn_in && txn_in->bundle.is_bundle ) ) {
     786           6 :       for( ulong j=txn_in->bundle.prev_txn_cnt; j>0UL && !is_found; j-- ) {
     787           3 :         fd_txn_out_t * prev_txn_out = txn_in->bundle.prev_txn_outs[ j-1 ];
     788           6 :         for( ushort k=0; k<prev_txn_out->accounts.cnt; k++ ) {
     789           6 :           if( fd_pubkey_eq( &prev_txn_out->accounts.keys[ k ], &addr_lut_acc ) && prev_txn_out->accounts.is_writable[ k ]  ) {
     790           3 :             fd_accdb_ro_init_nodb( alut_ro, &addr_lut_acc, prev_txn_out->accounts.account[ k ].meta );
     791           3 :             if( FD_UNLIKELY( !alut_ro->meta->lamports ) ) {
     792           0 :               fd_alut_interp_delete( interp );
     793           0 :               return FD_RUNTIME_TXN_ERR_ADDRESS_LOOKUP_TABLE_NOT_FOUND;
     794           0 :             }
     795           3 :             is_found = 1;
     796           3 :             break;
     797           3 :           }
     798           6 :         }
     799           3 :       }
     800           3 :     }
     801             : 
     802           3 :     if( FD_UNLIKELY( !is_found && !fd_accdb_open_ro( accdb, alut_ro, xid, &addr_lut_acc ) ) ) {
     803           0 :       fd_alut_interp_delete( interp );
     804           0 :       return FD_RUNTIME_TXN_ERR_ADDRESS_LOOKUP_TABLE_NOT_FOUND;
     805           0 :     }
     806             : 
     807           3 :     int err = fd_alut_interp_next(
     808           3 :         interp,
     809           3 :         &addr_lut_acc,
     810           3 :         fd_accdb_ref_owner     ( alut_ro ),
     811           3 :         fd_accdb_ref_data_const( alut_ro ),
     812           3 :         fd_accdb_ref_data_sz   ( alut_ro ) );
     813           3 :     fd_accdb_close_ro( accdb, alut_ro );
     814           3 :     if( FD_UNLIKELY( err ) ) {
     815           0 :       fd_alut_interp_delete( interp );
     816           0 :       return err;
     817           0 :     }
     818           3 :   }
     819             : 
     820          90 :   fd_alut_interp_delete( interp );
     821             : 
     822          90 :   return FD_RUNTIME_EXECUTE_SUCCESS;
     823          90 : }
     824             : 
     825             : /* Pre-populate the bank's in-memory feature set with upcoming feature
     826             :    activations.  If the current slot is the last slot before an epoch
     827             :    boundary, scan all known feature accounts. Otherwise, returns early.
     828             : 
     829             :    For any feature that is pending (not yet activated on-chain) but has
     830             :    an account owned by the feature program, set the in-memory activation
     831             :    slot within the bank's featureset to the first slot of the next
     832             :    epoch.  This is needed so that deployment verification (which uses
     833             :    slot+1) can detect features that will activate at the next epoch
     834             :    boundary.
     835             : 
     836             :    In Agave, program deployments use the feature set from the next
     837             :    slot via DELAY_VISIBILITY_SLOT_OFFSET.  The runtime environments
     838             :    for deployment are selected based on epoch_of(slot+1):
     839             :    https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/bank.rs#L3280-L3295
     840             :    https://github.com/anza-xyz/agave/blob/v3.1.8/svm/src/transaction_processor.rs#L339-L345
     841             : 
     842             :    This function does NOT write to feature accounts or update the
     843             :    lthash.  It only modifies the bank's in-memory feature set. */
     844             : static void
     845             : fd_features_prepopulate_upcoming( fd_bank_t *               bank,
     846             :                                   fd_accdb_user_t *         accdb,
     847         285 :                                   fd_funk_txn_xid_t const * xid ) {
     848         285 :   ulong slot = bank->f.slot;
     849         285 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     850         285 :   ulong curr_epoch = fd_slot_to_epoch( epoch_schedule, slot,     NULL );
     851         285 :   ulong next_epoch = fd_slot_to_epoch( epoch_schedule, slot+1UL, NULL );
     852         285 :   if( FD_LIKELY( curr_epoch==next_epoch ) ) return;
     853             : 
     854          21 :   fd_features_restore( bank, accdb, xid );
     855          21 : }
     856             : 
     857             : void
     858             : fd_runtime_block_execute_prepare( fd_banks_t *         banks,
     859             :                                   fd_bank_t *          bank,
     860             :                                   fd_accdb_user_t  *   accdb,
     861             :                                   fd_runtime_stack_t * runtime_stack,
     862             :                                   fd_capture_ctx_t *   capture_ctx,
     863         285 :                                   int *                is_epoch_boundary ) {
     864             : 
     865         285 :   fd_funk_txn_xid_t const xid = { .ul = { bank->f.slot, bank->idx } };
     866             : 
     867         285 :   fd_runtime_block_pre_execute_process_new_epoch( banks, bank, accdb, &xid, capture_ctx, runtime_stack, is_epoch_boundary );
     868             : 
     869         285 :   if( FD_LIKELY( bank->f.slot ) ) {
     870         285 :     fd_cost_tracker_t * cost_tracker = fd_bank_cost_tracker_modify( bank );
     871         285 :     FD_TEST( cost_tracker );
     872         285 :     fd_cost_tracker_init( cost_tracker, &bank->f.features, bank->f.slot );
     873         285 :   }
     874             : 
     875         285 :   fd_features_prepopulate_upcoming( bank, accdb, &xid );
     876             : 
     877         285 :   fd_runtime_block_sysvar_update_pre_execute( bank, accdb, &xid, runtime_stack, capture_ctx );
     878             : 
     879         285 :   if( FD_UNLIKELY( !fd_sysvar_cache_restore( bank, accdb, &xid ) ) ) {
     880           0 :     FD_LOG_ERR(( "Failed to restore sysvar cache" ));
     881           0 :   }
     882         285 : }
     883             : 
     884             : static void
     885             : fd_runtime_update_bank_hash( fd_bank_t *        bank,
     886          78 :                              fd_capture_ctx_t * capture_ctx ) {
     887             :   /* Compute the new bank hash */
     888          78 :   fd_lthash_value_t const * lthash = fd_bank_lthash_locking_query( bank );
     889          78 :   fd_hash_t new_bank_hash[1] = { 0 };
     890          78 :   fd_hashes_hash_bank(
     891          78 :       lthash,
     892          78 :       &bank->f.prev_bank_hash,
     893          78 :       (fd_hash_t *)bank->f.poh.hash,
     894          78 :       bank->f.signature_count,
     895          78 :       new_bank_hash );
     896             : 
     897             :   /* Update the bank hash */
     898          78 :   bank->f.bank_hash = *new_bank_hash;
     899             : 
     900          78 :   if( capture_ctx && capture_ctx->capture_solcap &&
     901          78 :       bank->f.slot>=capture_ctx->solcap_start_slot ) {
     902             : 
     903           0 :     uchar lthash_hash[FD_HASH_FOOTPRINT];
     904           0 :     fd_blake3_hash(lthash->bytes, FD_LTHASH_LEN_BYTES, lthash_hash );
     905           0 :     fd_capture_link_write_bank_preimage(
     906           0 :       capture_ctx,
     907           0 :       bank->f.slot,
     908           0 :       (fd_hash_t *)new_bank_hash->hash,
     909           0 :       (fd_hash_t *)&bank->f.prev_bank_hash,
     910           0 :       (fd_hash_t *)lthash_hash,
     911           0 :       (fd_hash_t *)bank->f.poh.hash,
     912           0 :       bank->f.signature_count );
     913           0 :   }
     914             : 
     915          78 :   fd_bank_lthash_end_locking_query( bank );
     916          78 : }
     917             : 
     918             : /******************************************************************************/
     919             : /* Transaction Level Execution Management                                     */
     920             : /******************************************************************************/
     921             : 
     922             : /* fd_runtime_pre_execute_check is responsible for conducting many of
     923             :    the transaction sanitization checks.  This is a combination of some
     924             :    of the work done in Agave's load_and_execute_transactions(), and some
     925             :    of the work done in Agave's transaction ingestion stage, before the
     926             :    transaction even hits the scheduler.  We do some of the checks also
     927             :    in our transaction ingestion stage.  For example, the duplicate
     928             :    account check is performed in both the leader and the replay
     929             :    scheduler.  As a result, the duplicate account check below is
     930             :    essentially redundant, except that our fuzzing harness expects a
     931             :    single entry point to cover all of these checks.  So we keep all of
     932             :    the checks below for fuzzing purposes.  We could in theory hoist some
     933             :    of the pre-scheduler checks into a public function that is only
     934             :    invoked by the fuzzer to avoid duplication in the leader and the
     935             :    replay pipeline.  But all the duplicate checks are pretty cheap, and
     936             :    the order and placement of the checks are also in motion on Agave's
     937             :    side, and performing all the checks faithfully would require access
     938             :    to the bank in the scheduler which is kind of gross.  So that's all
     939             :    probably more hassle than worth. */
     940             : 
     941             : static inline int
     942             : fd_runtime_pre_execute_check( fd_runtime_t *      runtime,
     943             :                               fd_bank_t *         bank,
     944             :                               fd_txn_in_t const * txn_in,
     945         168 :                               fd_txn_out_t *      txn_out ) {
     946             : 
     947             :   /* https://github.com/anza-xyz/agave/blob/16de8b75ebcd57022409b422de557dd37b1de8db/sdk/src/transaction/sanitized.rs#L263-L275
     948             :      TODO: Agave's precompile verification is done at the slot level, before batching and executing transactions. This logic should probably
     949             :      be moved in the future. The Agave call heirarchy looks something like this:
     950             :             process_single_slot
     951             :                    v
     952             :             confirm_full_slot
     953             :                    v
     954             :             confirm_slot_entries --------------------------------------------------->
     955             :                    v                               v                                v
     956             :             verify_transaction    ComputeBudget::process_instruction         process_entries
     957             :                    v                                                                v
     958             :             verify_precompiles                                                process_batches
     959             :                                                                                     v
     960             :                                                                                    ...
     961             :                                                                                     v
     962             :                                                                         load_and_execute_transactions
     963             :                                                                                     v
     964             :                                                                                    ...
     965             :                                                                                     v
     966             :                                                                               load_accounts --> load_transaction_accounts
     967             :                                                                                     v
     968             :                                                                        general transaction execution
     969             : 
     970             :   */
     971             : 
     972             :   /* Verify the transaction. For now, this step only involves processing
     973             :      the compute budget instructions. */
     974         168 :   int err = fd_executor_verify_transaction( bank, txn_in, txn_out );
     975         168 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     976           3 :     txn_out->err.is_committable = 0;
     977           3 :     return err;
     978           3 :   }
     979             : 
     980             :   /* Resolve and verify ALUT-referenced account keys, if applicable */
     981         165 :   err = fd_executor_setup_txn_alut_account_keys( runtime, bank, txn_in, txn_out );
     982         165 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     983           0 :     txn_out->err.is_committable = 0;
     984           0 :     return err;
     985           0 :   }
     986             : 
     987             :   /* Set up the transaction accounts and other txn ctx metadata */
     988         165 :   fd_executor_setup_accounts_for_txn( runtime, bank, txn_in, txn_out );
     989             : 
     990             :   /* Post-sanitization checks. Called from prepare_sanitized_batch()
     991             :      which, for now, only is used to lock the accounts and perform a
     992             :      couple basic validations.
     993             :      https://github.com/anza-xyz/agave/blob/838c1952595809a31520ff1603a13f2c9123aa51/accounts-db/src/account_locks.rs#L118 */
     994         165 :   err = fd_executor_validate_account_locks( bank, txn_out );
     995         165 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     996           0 :     txn_out->err.is_committable = 0;
     997           0 :     return err;
     998           0 :   }
     999             : 
    1000             :   /* load_and_execute_transactions() -> check_transactions()
    1001             :      https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/runtime/src/bank.rs#L3667-L3672 */
    1002         165 :   err = fd_executor_check_transactions( runtime, bank, txn_in, txn_out );
    1003         165 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
    1004           3 :     txn_out->err.is_committable = 0;
    1005           3 :     return err;
    1006           3 :   }
    1007             : 
    1008             :   /* load_and_execute_sanitized_transactions() -> validate_fees() ->
    1009             :      validate_transaction_fee_payer()
    1010             :      https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/svm/src/transaction_processor.rs#L236-L249 */
    1011         162 :   err = fd_executor_validate_transaction_fee_payer( runtime, bank, txn_in, txn_out );
    1012         162 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
    1013           0 :     txn_out->err.is_committable = 0;
    1014           0 :     return err;
    1015           0 :   }
    1016             : 
    1017         162 :   txn_out->details.exec_start_timestamp = fd_tickcount();
    1018             : 
    1019             :   /* https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/svm/src/transaction_processor.rs#L284-L296 */
    1020         162 :   err = fd_executor_load_transaction_accounts( runtime, bank, txn_in, txn_out );
    1021         162 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
    1022             :     /* Regardless of whether transaction accounts were loaded successfully, the transaction is
    1023             :        included in the block and transaction fees are collected.
    1024             :        https://github.com/anza-xyz/agave/blob/v2.1.6/svm/src/transaction_processor.rs#L341-L357 */
    1025           0 :     txn_out->err.is_fees_only = 1;
    1026             : 
    1027             :     /* If the transaction fails to load, the "rollback" accounts will include one of the following:
    1028             :         1. Nonce account only
    1029             :         2. Fee payer only
    1030             :         3. Nonce account + fee payer
    1031             : 
    1032             :         Because the cost tracker uses the loaded account data size in block cost calculations, we need to
    1033             :         make sure our calculated loaded accounts data size is conformant with Agave's.
    1034             :         https://github.com/anza-xyz/agave/blob/v2.1.14/runtime/src/bank.rs#L4116
    1035             : 
    1036             :         In any case, we should always add the dlen of the fee payer. */
    1037           0 :     txn_out->details.loaded_accounts_data_size = fd_accdb_ref_data_sz( txn_out->accounts.account[ FD_FEE_PAYER_TXN_IDX ].ro );
    1038             : 
    1039             :     /* Special case handling for if a nonce account is present in the transaction. */
    1040           0 :     if( txn_out->accounts.nonce_idx_in_txn!=ULONG_MAX ) {
    1041             :       /* If the nonce account is not the fee payer, then we separately add the dlen of the nonce account. Otherwise, we would
    1042             :           be double counting the dlen of the fee payer. */
    1043           0 :       if( txn_out->accounts.nonce_idx_in_txn!=FD_FEE_PAYER_TXN_IDX ) {
    1044           0 :         txn_out->details.loaded_accounts_data_size += txn_out->accounts.rollback_nonce->dlen;
    1045           0 :       }
    1046           0 :     }
    1047           0 :   }
    1048             : 
    1049             :   /*
    1050             :      The fee payer and the nonce account will be stored and hashed so
    1051             :      long as the transaction landed on chain, or, in Agave terminology,
    1052             :      the transaction was processed.
    1053             :      https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/account_saver.rs#L72
    1054             : 
    1055             :      A transaction lands on chain in one of two ways:
    1056             :      (1) Passed fee validation and loaded accounts.
    1057             :      (2) Passed fee validation and failed to load accounts and the enable_transaction_loading_failure_fees feature is enabled as per
    1058             :          SIMD-0082 https://github.com/anza-xyz/feature-gate-tracker/issues/52
    1059             : 
    1060             :      So, at this point, the transaction is committable.
    1061             :    */
    1062             : 
    1063         162 :   return err;
    1064         162 : }
    1065             : 
    1066             : /* fd_runtime_finalize_account is a helper used to commit the data from
    1067             :    a writable transaction account back into the accountsdb. */
    1068             : 
    1069             : static void
    1070             : fd_runtime_finalize_account( fd_accdb_user_t *         accdb,
    1071             :                              fd_funk_txn_xid_t const * xid,
    1072             :                              fd_pubkey_t const *       pubkey,
    1073          63 :                              fd_account_meta_t *       meta ) {
    1074             :   /* FIXME if account doesn't change according to LtHash, don't update
    1075             :            database record */
    1076             : 
    1077          63 :   fd_accdb_rw_t rw[1];
    1078          63 :   int rw_ok = !!fd_accdb_open_rw(
    1079          63 :       accdb,
    1080          63 :       rw,
    1081          63 :       xid,
    1082          63 :       pubkey,
    1083          63 :       meta->dlen,
    1084          63 :       FD_ACCDB_FLAG_CREATE|FD_ACCDB_FLAG_TRUNCATE );
    1085          63 :   if( FD_UNLIKELY( !rw_ok ) ) FD_LOG_CRIT(( "fd_accdb_open_rw failed" ));
    1086             : 
    1087          63 :   void const * data = fd_account_data( meta );
    1088          63 :   fd_accdb_ref_lamports_set(        rw, meta->lamports   );
    1089          63 :   fd_accdb_ref_owner_set   (        rw, meta->owner      );
    1090          63 :   fd_accdb_ref_exec_bit_set(        rw, meta->executable );
    1091          63 :   fd_accdb_ref_data_set    ( accdb, rw, data, meta->dlen );
    1092          63 :   fd_accdb_ref_slot_set    (        rw, xid->ul[0]       );
    1093             : 
    1094          63 :   fd_accdb_close_rw( accdb, rw );
    1095          63 : }
    1096             : 
    1097             : /* fd_runtime_save_account persists a transaction account to the account
    1098             :    database and updates the bank lthash.
    1099             : 
    1100             :    This function:
    1101             :    - Loads the previous account revision
    1102             :    - Computes the LtHash of the previous revision
    1103             :    - Computes the LtHash of the new revision
    1104             :    - Removes/adds the previous/new revision's LtHash
    1105             :    - Saves the new version of the account to funk
    1106             :    - Sends updates to metrics and capture infra
    1107             : 
    1108             :    Returns FD_RUNTIME_SAVE_* */
    1109             : 
    1110             : static int
    1111             : fd_runtime_save_account( fd_accdb_user_t *         accdb,
    1112             :                          fd_funk_txn_xid_t const * xid,
    1113             :                          fd_pubkey_t const *       pubkey,
    1114             :                          fd_account_meta_t *       meta,
    1115             :                          fd_bank_t *               bank,
    1116          66 :                          fd_capture_ctx_t *        capture_ctx ) {
    1117          66 :   fd_lthash_value_t lthash_post[1];
    1118          66 :   fd_lthash_value_t lthash_prev[1];
    1119             : 
    1120             :   /* Update LtHash
    1121             :      - Query old version of account and hash it
    1122             :      - Hash new version of account */
    1123          66 :   fd_accdb_ro_t ro[1];
    1124          66 :   int old_exist = 0;
    1125          66 :   if( fd_accdb_open_ro( accdb, ro, xid, pubkey ) ) {
    1126          60 :     old_exist = fd_accdb_ref_lamports( ro )!=0UL;
    1127          60 :     fd_hashes_account_lthash(
    1128          60 :       pubkey,
    1129          60 :       ro->meta,
    1130          60 :       fd_accdb_ref_data_const( ro ),
    1131          60 :       lthash_prev );
    1132          60 :     fd_accdb_close_ro( accdb, ro );
    1133          60 :   } else {
    1134           6 :     old_exist = 0;
    1135           6 :     fd_lthash_zero( lthash_prev );
    1136           6 :   }
    1137          66 :   int new_exist = meta->lamports!=0UL;
    1138             : 
    1139          66 :   if( FD_LIKELY( old_exist || new_exist ) ) {
    1140          60 :     fd_hashes_update_lthash1( lthash_post, lthash_prev, pubkey, meta, bank, capture_ctx );
    1141          60 :   }
    1142             : 
    1143             :   /* The first 32 bytes of an LtHash with a single input element are
    1144             :      equal to the BLAKE3_256 hash of an account.  Therefore, comparing
    1145             :      the first 32 bytes is a cryptographically secure equality check
    1146             :      for an account. */
    1147          66 :   int changed = 0!=memcmp( lthash_post->bytes, lthash_prev->bytes, 32UL );
    1148             : 
    1149          66 :   if( changed ) {
    1150          63 :     fd_runtime_finalize_account( accdb, xid, pubkey, meta );
    1151          63 :   }
    1152             : 
    1153          66 :   int save_type = (old_exist<<1) | (new_exist);
    1154          66 :   if( save_type==FD_RUNTIME_SAVE_MODIFY && !changed ) {
    1155           3 :     save_type = FD_RUNTIME_SAVE_UNCHANGED;
    1156           3 :   }
    1157          66 :   return save_type;
    1158          66 : }
    1159             : 
    1160             : /* fd_runtime_commit_txn is a helper used by the non-tpool transaction
    1161             :    executor to finalize borrowed account changes back into funk. It also
    1162             :    handles txncache insertion and updates to the vote/stake cache.
    1163             :    TODO: This function should probably be moved to fd_executor.c. */
    1164             : 
    1165             : void
    1166             : fd_runtime_commit_txn( fd_runtime_t * runtime,
    1167             :                        fd_bank_t *    bank,
    1168          36 :                        fd_txn_out_t * txn_out ) {
    1169             : 
    1170          36 :   if( FD_UNLIKELY( !txn_out->err.is_committable ) ) {
    1171           0 :     FD_LOG_CRIT(( "fd_runtime_commit_txn: transaction is not committable" ));
    1172           0 :   }
    1173             : 
    1174          36 :   txn_out->details.commit_start_timestamp = fd_tickcount();
    1175             : 
    1176             :   /* Release executable accounts */
    1177             : 
    1178          36 :   for( ulong i=0UL; i<runtime->accounts.executable_cnt; i++ ) {
    1179           0 :     fd_accdb_close_ro( runtime->accdb, &runtime->accounts.executable[i] );
    1180           0 :   }
    1181          36 :   runtime->accounts.executable_cnt = 0UL;
    1182             : 
    1183             :   /* Release read-only accounts */
    1184             : 
    1185         123 :   for( ulong i=0UL; i<txn_out->accounts.cnt; i++ ) {
    1186          87 :     if( !txn_out->accounts.is_writable[i] ) {
    1187          21 :       fd_accdb_close_ro( runtime->accdb, txn_out->accounts.account[i].ro );
    1188          21 :     }
    1189          87 :   }
    1190             : 
    1191          36 :   fd_funk_txn_xid_t xid = { .ul = { bank->f.slot, bank->idx } };
    1192             : 
    1193          36 :   if( FD_UNLIKELY( txn_out->err.txn_err ) ) {
    1194             : 
    1195             :     /* Save the fee_payer. Everything but the fee balance should be reset.
    1196             :        TODO: an optimization here could be to use a dirty flag in the
    1197             :        borrowed account. If the borrowed account data has been changed in
    1198             :        any way, then the full account can be rolled back as it is done now.
    1199             :        However, most of the time the account data is not changed, and only
    1200             :        the lamport balance has to change. */
    1201             : 
    1202             :     /* With nonce account rollbacks, there are three cases:
    1203             :        1. No nonce account in the transaction
    1204             :        2. Nonce account is the fee payer
    1205             :        3. Nonce account is not the fee payer
    1206             : 
    1207             :        We should always rollback the nonce account first. Note that the nonce account may be the fee payer (case 2). */
    1208           0 :     if( txn_out->accounts.nonce_idx_in_txn!=ULONG_MAX ) {
    1209           0 :       int save_type =
    1210           0 :         fd_runtime_save_account(
    1211           0 :             runtime->accdb,
    1212           0 :             &xid,
    1213           0 :             &txn_out->accounts.keys[txn_out->accounts.nonce_idx_in_txn],
    1214           0 :             txn_out->accounts.rollback_nonce,
    1215           0 :             bank,
    1216           0 :             runtime->log.capture_ctx );
    1217           0 :       runtime->metrics.txn_account_save[ save_type ]++;
    1218           0 :     }
    1219             :     /* Now, we must only save the fee payer if the nonce account was not the fee payer (because that was already saved above) */
    1220           0 :     if( FD_LIKELY( txn_out->accounts.nonce_idx_in_txn!=FD_FEE_PAYER_TXN_IDX ) ) {
    1221           0 :       int save_type =
    1222           0 :         fd_runtime_save_account(
    1223           0 :             runtime->accdb,
    1224           0 :             &xid,
    1225           0 :             &txn_out->accounts.keys[FD_FEE_PAYER_TXN_IDX],
    1226           0 :             txn_out->accounts.rollback_fee_payer,
    1227           0 :             bank,
    1228           0 :             runtime->log.capture_ctx );
    1229           0 :       runtime->metrics.txn_account_save[ save_type ]++;
    1230           0 :     }
    1231          36 :   } else {
    1232             : 
    1233             : 
    1234          36 :     fd_top_votes_t * top_votes = fd_bank_top_votes_t_2_modify( bank );
    1235         123 :     for( ushort i=0; i<txn_out->accounts.cnt; i++ ) {
    1236             :       /* We are only interested in saving writable accounts and the fee
    1237             :          payer account. */
    1238          87 :       if( !txn_out->accounts.is_writable[i] ) {
    1239          21 :         continue;
    1240          21 :       }
    1241             : 
    1242          66 :       fd_pubkey_t const * pubkey  = &txn_out->accounts.keys[i];
    1243          66 :       fd_accdb_rw_t *     account = &txn_out->accounts.account[i];
    1244             : 
    1245             :       /* Tips for bundles are collected in the bank: a user submitting a
    1246             :          bundle must include a instruction that transfers lamports to
    1247             :          a specific tip account.  Tips accumulated through the slot. */
    1248          66 :       if( fd_pack_tip_is_tip_account( fd_type_pun_const( pubkey->uc ) ) ) {
    1249           0 :        txn_out->details.tips += fd_ulong_sat_sub( fd_accdb_ref_lamports( account->ro ), runtime->accounts.starting_lamports[i] );
    1250           0 :       }
    1251             : 
    1252          66 :       if( txn_out->accounts.stake_update[i] ) {
    1253           0 :         fd_stakes_update_stake_delegation( pubkey, account->meta, bank );
    1254           0 :       }
    1255             : 
    1256          66 :       if( txn_out->accounts.vote_update[i] ) {
    1257           0 :         if( FD_UNLIKELY( fd_accdb_ref_lamports( account->ro )==0UL || !fd_vsv_is_correct_size_and_initialized( account->meta ) ) ) {
    1258           0 :           fd_top_votes_invalidate( top_votes, pubkey );
    1259           0 :         } else {
    1260           0 :           fd_vote_block_timestamp_t last_vote;
    1261           0 :           FD_TEST( !fd_vote_account_last_timestamp( fd_account_data( account->meta ), account->meta->dlen, &last_vote ) );
    1262           0 :           fd_top_votes_update( top_votes, pubkey, last_vote.slot, last_vote.timestamp );
    1263           0 :         }
    1264           0 :       }
    1265             : 
    1266          66 :       int save_type = fd_runtime_save_account( runtime->accdb, &xid, pubkey, account->meta, bank, runtime->log.capture_ctx );
    1267          66 :       runtime->metrics.txn_account_save[ save_type ]++;
    1268          66 :     }
    1269             : 
    1270             :     /* Atomically add all accumulated tips to the bank once after processing all accounts */
    1271          36 :     if( txn_out->details.tips>0UL )
    1272           0 :       FD_ATOMIC_FETCH_AND_ADD( &bank->f.tips, txn_out->details.tips );
    1273          36 :   }
    1274             : 
    1275             :   /* Accumulate block-level information to the bank. */
    1276             : 
    1277          36 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.txn_count,               1UL );
    1278          36 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.execution_fees,  txn_out->details.execution_fee );
    1279          36 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.priority_fees,   txn_out->details.priority_fee );
    1280          36 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.signature_count, txn_out->details.signature_count );
    1281             : 
    1282          36 :   if( !txn_out->details.is_simple_vote ) {
    1283          36 :     FD_ATOMIC_FETCH_AND_ADD( &bank->f.nonvote_txn_count, 1 );
    1284          36 :     if( FD_UNLIKELY( txn_out->err.exec_err ) ) {
    1285           0 :       FD_ATOMIC_FETCH_AND_ADD( &bank->f.nonvote_failed_txn_count, 1 );
    1286           0 :     }
    1287          36 :   }
    1288             : 
    1289          36 :   if( FD_UNLIKELY( txn_out->err.exec_err ) ) {
    1290           0 :     FD_ATOMIC_FETCH_AND_ADD( &bank->f.failed_txn_count, 1 );
    1291           0 :   }
    1292             : 
    1293          36 :   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 );
    1294             : 
    1295             :   /* Update the cost tracker. */
    1296             : 
    1297          36 :   fd_cost_tracker_t * cost_tracker = fd_bank_cost_tracker_modify( bank );
    1298          36 :   int res = fd_cost_tracker_try_add_cost( cost_tracker, txn_out );
    1299          36 :   if( FD_UNLIKELY( res!=FD_COST_TRACKER_SUCCESS ) ) {
    1300           0 :     FD_LOG_DEBUG(( "fd_runtime_commit_txn: transaction failed to fit into block %d", res ));
    1301           0 :     txn_out->err.is_committable = 0;
    1302           0 :     txn_out->err.txn_err        = fd_cost_tracker_err_to_runtime_err( res );
    1303           0 :   }
    1304             : 
    1305             :   /* Finally, update the status cache. */
    1306             : 
    1307          36 :   if( FD_LIKELY( runtime->status_cache && txn_out->accounts.nonce_idx_in_txn==ULONG_MAX ) ) {
    1308             :     /* In Agave, durable nonce transactions are inserted to the status
    1309             :        cache the same as any others, but this is only to serve RPC
    1310             :        requests, they do not need to be in there for correctness as the
    1311             :        nonce mechanism itself prevents double spend.  We skip this logic
    1312             :        entirely to simplify and improve performance of the txn cache. */
    1313             : 
    1314           0 :     fd_txncache_insert( runtime->status_cache, bank->txncache_fork_id, txn_out->details.blockhash.uc, txn_out->details.blake_txn_msg_hash.uc );
    1315           0 :   }
    1316             : 
    1317         123 :   for( ushort i=0; i<txn_out->accounts.cnt; i++ ) {
    1318          87 :     if( txn_out->accounts.is_writable[i] ) {
    1319          66 :       fd_acc_pool_release( runtime->acc_pool, fd_type_pun( txn_out->accounts.account[i].meta ) );
    1320          66 :     }
    1321          87 :   }
    1322             : 
    1323          36 :   fd_acc_pool_release( runtime->acc_pool, txn_out->accounts.rollback_nonce_mem );
    1324          36 :   fd_acc_pool_release( runtime->acc_pool, txn_out->accounts.rollback_fee_payer_mem );
    1325          36 : }
    1326             : 
    1327             : void
    1328             : fd_runtime_cancel_txn( fd_runtime_t * runtime,
    1329          45 :                        fd_txn_out_t * txn_out ) {
    1330             : 
    1331          45 :   if( FD_UNLIKELY( txn_out->err.is_committable ) ) {
    1332           0 :     FD_LOG_CRIT(( "fd_runtime_cancel_txn: transaction is committable" ));
    1333           0 :   }
    1334             : 
    1335          45 :   if( !txn_out->accounts.is_setup ) {
    1336           0 :     return;
    1337           0 :   }
    1338             : 
    1339          48 :   for( ulong i=0UL; i<runtime->accounts.executable_cnt; i++ ) {
    1340           3 :     fd_accdb_close_ro( runtime->accdb, &runtime->accounts.executable[i] );
    1341           3 :   }
    1342          45 :   runtime->accounts.executable_cnt = 0UL;
    1343             : 
    1344         204 :   for( ushort i=0; i<txn_out->accounts.cnt; i++ ) {
    1345         159 :     if( txn_out->accounts.is_writable[i] ) {
    1346          90 :       fd_acc_pool_release( runtime->acc_pool, fd_type_pun( txn_out->accounts.account[i].meta ) );
    1347          90 :     } else {
    1348          69 :       fd_accdb_close_ro( runtime->accdb, txn_out->accounts.account[i].ro );
    1349          69 :     }
    1350         159 :   }
    1351             : 
    1352          45 :   fd_acc_pool_release( runtime->acc_pool, txn_out->accounts.rollback_nonce_mem );
    1353          45 :   fd_acc_pool_release( runtime->acc_pool, txn_out->accounts.rollback_fee_payer_mem );
    1354          45 : }
    1355             : 
    1356             : static inline void
    1357         168 : fd_runtime_reset_runtime( fd_runtime_t * runtime ) {
    1358         168 :   runtime->instr.stack_sz     = 0;
    1359         168 :   runtime->instr.trace_length = 0UL;
    1360             :   /* The only condition where the executable count of the current
    1361             :      runtime is not 0 is when a bundle of transaction is being executed.
    1362             :      In this case, close any outstanding executable accounts. */
    1363         171 :   for( ulong i=0UL; i<runtime->accounts.executable_cnt; i++ ) {
    1364           3 :     fd_accdb_close_ro( runtime->accdb, &runtime->accounts.executable[i] );
    1365           3 :   }
    1366         168 :   runtime->accounts.executable_cnt = 0UL;
    1367             : 
    1368         168 : }
    1369             : 
    1370             : static inline void
    1371             : fd_runtime_new_txn_out( fd_txn_in_t const * txn_in,
    1372         168 :                         fd_txn_out_t *      txn_out ) {
    1373         168 :   txn_out->details.prep_start_timestamp   = fd_tickcount();
    1374         168 :   txn_out->details.load_start_timestamp   = LONG_MAX;
    1375         168 :   txn_out->details.exec_start_timestamp   = LONG_MAX;
    1376         168 :   txn_out->details.commit_start_timestamp = LONG_MAX;
    1377             : 
    1378         168 :   fd_compute_budget_details_new( &txn_out->details.compute_budget );
    1379             : 
    1380         168 :   txn_out->details.loaded_accounts_data_size = 0UL;
    1381         168 :   txn_out->details.accounts_resize_delta     = 0L;
    1382             : 
    1383         168 :   txn_out->details.return_data.len = 0UL;
    1384         168 :   memset( txn_out->details.return_data.program_id.key, 0, sizeof(fd_pubkey_t) );
    1385             : 
    1386         168 :   txn_out->details.tips            = 0UL;
    1387         168 :   txn_out->details.execution_fee   = 0UL;
    1388         168 :   txn_out->details.priority_fee    = 0UL;
    1389         168 :   txn_out->details.signature_count = 0UL;
    1390             : 
    1391         168 :   txn_out->details.signature_count = TXN( txn_in->txn )->signature_cnt;
    1392         168 :   txn_out->details.is_simple_vote  = fd_txn_is_simple_vote_transaction( TXN( txn_in->txn ), txn_in->txn->payload );
    1393             : 
    1394         168 :   fd_hash_t * blockhash = (fd_hash_t *)((uchar *)txn_in->txn->payload + TXN( txn_in->txn )->recent_blockhash_off);
    1395         168 :   memcpy( txn_out->details.blockhash.uc, blockhash->hash, sizeof(fd_hash_t) );
    1396             : 
    1397         168 :   txn_out->accounts.is_setup           = 0;
    1398         168 :   txn_out->accounts.cnt                = 0UL;
    1399         168 :   txn_out->accounts.rollback_nonce     = NULL;
    1400         168 :   txn_out->accounts.rollback_fee_payer = NULL;
    1401         168 :   memset( txn_out->accounts.stake_update, 0, sizeof(txn_out->accounts.stake_update) );
    1402         168 :   memset( txn_out->accounts.vote_update, 0, sizeof(txn_out->accounts.vote_update) );
    1403             : 
    1404         168 :   txn_out->err.is_committable = 1;
    1405         168 :   txn_out->err.is_fees_only   = 0;
    1406         168 :   txn_out->err.txn_err        = FD_RUNTIME_EXECUTE_SUCCESS;
    1407         168 :   txn_out->err.exec_err       = FD_EXECUTOR_INSTR_SUCCESS;
    1408         168 :   txn_out->err.exec_err_kind  = FD_EXECUTOR_ERR_KIND_NONE;
    1409         168 :   txn_out->err.exec_err_idx   = INT_MAX;
    1410         168 :   txn_out->err.custom_err     = 0;
    1411         168 : }
    1412             : 
    1413             : void
    1414             : fd_runtime_prepare_and_execute_txn( fd_runtime_t *       runtime,
    1415             :                                     fd_bank_t *          bank,
    1416             :                                     fd_txn_in_t const *  txn_in,
    1417         168 :                                     fd_txn_out_t *       txn_out ) {
    1418             : 
    1419         168 :   fd_runtime_reset_runtime( runtime );
    1420             : 
    1421         168 :   fd_runtime_new_txn_out( txn_in, txn_out );
    1422             : 
    1423             :   /* Set up the core account keys before any pre-execution checks.
    1424             :      This is needed both for execution and for protobuf context
    1425             :      dumping. */
    1426         168 :   fd_executor_setup_txn_account_keys( txn_in, txn_out );
    1427             : 
    1428         168 : # if FD_HAS_FLATCC
    1429         168 :   uchar dump_txn = !!( runtime->log.dump_proto_ctx &&
    1430         168 :                        bank->f.slot >= runtime->log.dump_proto_ctx->dump_proto_start_slot &&
    1431         168 :                        runtime->log.dump_proto_ctx->dump_txn_to_pb );
    1432             : 
    1433             :   /* Phase 1: Capture TxnContext before execution. */
    1434         168 :   if( FD_UNLIKELY( dump_txn ) ) {
    1435           0 :     if( runtime->log.txn_dump_ctx ) {
    1436           0 :       fd_dump_txn_context_to_protobuf( runtime->log.txn_dump_ctx, runtime, bank, txn_in, txn_out );
    1437           0 :     } else {
    1438           0 :       fd_dump_txn_to_protobuf( runtime, bank, txn_in, txn_out );
    1439           0 :     }
    1440           0 :   }
    1441         168 : # endif
    1442             : 
    1443             :   /* Transaction sanitization.  If a transaction can't be commited or is
    1444             :      fees-only, we return early. */
    1445         168 :   txn_out->err.txn_err = fd_runtime_pre_execute_check( runtime, bank, txn_in, txn_out );
    1446         168 :   ulong cu_before = txn_out->details.compute_budget.compute_meter;
    1447             : 
    1448             :   /* Execute the transaction if eligible to do so. */
    1449         168 :   if( FD_LIKELY( txn_out->err.is_committable ) ) {
    1450         162 :     if( FD_LIKELY( !txn_out->err.is_fees_only ) ) {
    1451         162 :       txn_out->err.txn_err = fd_execute_txn( runtime, bank, txn_in, txn_out );
    1452         162 :     }
    1453         162 :     fd_cost_tracker_calculate_cost( bank, txn_in, txn_out );
    1454         162 :   }
    1455         168 :   ulong cu_after = txn_out->details.compute_budget.compute_meter;
    1456         168 :   runtime->metrics.cu_cum += fd_ulong_sat_sub( cu_before, cu_after );
    1457             : 
    1458         168 : # if FD_HAS_FLATCC
    1459             :   /* Phase 2: Capture TxnResult after execution and write to disk. */
    1460         168 :   if( FD_UNLIKELY( dump_txn && runtime->log.txn_dump_ctx ) ) {
    1461           0 :     fd_dump_txn_result_to_protobuf( runtime->log.txn_dump_ctx, txn_in, txn_out, txn_out->err.txn_err );
    1462           0 :     fd_dump_txn_fixture_to_file( runtime->log.txn_dump_ctx, runtime->log.dump_proto_ctx, txn_in );
    1463           0 :   }
    1464         168 : # endif
    1465         168 : }
    1466             : 
    1467             : /* fd_executor_txn_verify and fd_runtime_pre_execute_check are responisble
    1468             :    for the bulk of the pre-transaction execution checks in the runtime.
    1469             :    They aim to preserve the ordering present in the Agave client to match
    1470             :    parity in terms of error codes. Sigverify is kept separate from the rest
    1471             :    of the transaction checks for fuzzing convenience.
    1472             : 
    1473             :    For reference this is the general code path which contains all relevant
    1474             :    pre-transactions checks in the v2.0.x Agave client from upstream
    1475             :    to downstream is as follows:
    1476             : 
    1477             :    confirm_slot_entries() which calls verify_ticks() and
    1478             :    verify_transaction(). verify_transaction() calls verify_and_hash_message()
    1479             :    and verify_precompiles() which parallels fd_executor_txn_verify() and
    1480             :    fd_executor_verify_transaction().
    1481             : 
    1482             :    process_entries() contains a duplicate account check which is part of
    1483             :    agave account lock acquiring. This is checked inline in
    1484             :    fd_runtime_pre_execute_check().
    1485             : 
    1486             :    load_and_execute_transactions() contains the function check_transactions().
    1487             :    This contains check_age() and check_status_cache() which is paralleled by
    1488             :    fd_executor_check_transaction_age_and_compute_budget_limits() and
    1489             :    fd_executor_check_status_cache() respectively.
    1490             : 
    1491             :    load_and_execute_sanitized_transactions() contains validate_fees()
    1492             :    which is responsible for executing the compute budget instructions,
    1493             :    validating the fee payer and collecting the fee. This is mirrored in
    1494             :    firedancer with fd_executor_compute_budget_program_execute_instructions()
    1495             :    and fd_executor_collect_fees(). load_and_execute_sanitized_transactions()
    1496             :    also checks the total data size of the accounts in load_accounts() and
    1497             :    validates the program accounts in load_transaction_accounts(). This
    1498             :    is paralled by fd_executor_load_transaction_accounts(). */
    1499             : 
    1500             : 
    1501             : /******************************************************************************/
    1502             : /* Genesis                                                                    */
    1503             : /*******************************************************************************/
    1504             : 
    1505             : static void
    1506             : fd_runtime_genesis_init_program( fd_bank_t *               bank,
    1507             :                                  fd_accdb_user_t *         accdb,
    1508             :                                  fd_funk_txn_xid_t const * xid,
    1509           0 :                                  fd_capture_ctx_t *        capture_ctx ) {
    1510             : 
    1511           0 :   fd_sysvar_clock_init( bank, accdb, xid, capture_ctx );
    1512           0 :   fd_sysvar_rent_init( bank, accdb, xid, capture_ctx );
    1513             : 
    1514           0 :   fd_sysvar_slot_history_init( bank, accdb, xid, capture_ctx );
    1515           0 :   fd_sysvar_epoch_schedule_init( bank, accdb, xid, capture_ctx );
    1516           0 :   fd_sysvar_recent_hashes_init( bank, accdb, xid, capture_ctx );
    1517           0 :   fd_sysvar_stake_history_init( bank, accdb, xid, capture_ctx );
    1518           0 :   fd_sysvar_last_restart_slot_init( bank, accdb, xid, capture_ctx );
    1519             : 
    1520           0 :   fd_builtin_programs_init( bank, accdb, xid, capture_ctx );
    1521           0 : }
    1522             : 
    1523             : static void
    1524             : fd_runtime_init_bank_from_genesis( fd_banks_t *              banks,
    1525             :                                    fd_bank_t *               bank,
    1526             :                                    fd_runtime_stack_t *      runtime_stack,
    1527             :                                    fd_accdb_user_t *         accdb,
    1528             :                                    fd_funk_txn_xid_t const * xid,
    1529             :                                    fd_genesis_t const *      genesis,
    1530             :                                    uchar const *             genesis_blob,
    1531           0 :                                    fd_hash_t const *         genesis_hash ) {
    1532             : 
    1533           0 :   bank->f.parent_slot = ULONG_MAX;
    1534           0 :   bank->f.poh = *genesis_hash;
    1535             : 
    1536           0 :   fd_hash_t * bank_hash = &bank->f.bank_hash;
    1537           0 :   memset( bank_hash->hash, 0, FD_SHA256_HASH_SZ );
    1538             : 
    1539           0 :   uint128 target_tick_duration = (uint128)genesis->poh.tick_duration_secs * 1000000000UL + (uint128)genesis->poh.tick_duration_ns;
    1540             : 
    1541           0 :   fd_epoch_schedule_t * epoch_schedule = &bank->f.epoch_schedule;
    1542           0 :   epoch_schedule->leader_schedule_slot_offset = genesis->epoch_schedule.leader_schedule_slot_offset;
    1543           0 :   epoch_schedule->warmup                      = genesis->epoch_schedule.warmup;
    1544           0 :   epoch_schedule->first_normal_epoch          = genesis->epoch_schedule.first_normal_epoch;
    1545           0 :   epoch_schedule->first_normal_slot           = genesis->epoch_schedule.first_normal_slot;
    1546           0 :   epoch_schedule->slots_per_epoch             = genesis->epoch_schedule.slots_per_epoch;
    1547             : 
    1548           0 :   fd_rent_t * rent = &bank->f.rent;
    1549           0 :   rent->lamports_per_uint8_year = genesis->rent.lamports_per_uint8_year;
    1550           0 :   rent->exemption_threshold     = genesis->rent.exemption_threshold;
    1551           0 :   rent->burn_percent            = genesis->rent.burn_percent;
    1552             : 
    1553           0 :   fd_inflation_t * inflation = &bank->f.inflation;
    1554           0 :   inflation->initial         = genesis->inflation.initial;
    1555           0 :   inflation->terminal        = genesis->inflation.terminal;
    1556           0 :   inflation->taper           = genesis->inflation.taper;
    1557           0 :   inflation->foundation      = genesis->inflation.foundation;
    1558           0 :   inflation->foundation_term = genesis->inflation.foundation_term;
    1559           0 :   inflation->unused          = 0.0;
    1560             : 
    1561           0 :   bank->f.block_height = 0UL;
    1562             : 
    1563           0 :   {
    1564             :     /* FIXME Why is there a previous blockhash at genesis?  Why is the
    1565             :              last_hash field an option type in Agave, if even the first
    1566             :              real block has a previous blockhash? */
    1567           0 :     fd_blockhashes_t *    bhq  = fd_blockhashes_init( &bank->f.block_hash_queue, 0UL );
    1568           0 :     fd_blockhash_info_t * info = fd_blockhashes_push_new( bhq, genesis_hash );
    1569           0 :     info->fee_calculator.lamports_per_signature = 0UL;
    1570           0 :   }
    1571             : 
    1572           0 :   fd_fee_rate_governor_t * fee_rate_governor = &bank->f.fee_rate_governor;
    1573           0 :   fee_rate_governor->target_lamports_per_signature = genesis->fee_rate_governor.target_lamports_per_signature;
    1574           0 :   fee_rate_governor->target_signatures_per_slot    = genesis->fee_rate_governor.target_signatures_per_slot;
    1575           0 :   fee_rate_governor->min_lamports_per_signature    = genesis->fee_rate_governor.min_lamports_per_signature;
    1576           0 :   fee_rate_governor->max_lamports_per_signature    = genesis->fee_rate_governor.max_lamports_per_signature;
    1577           0 :   fee_rate_governor->burn_percent                  = genesis->fee_rate_governor.burn_percent;
    1578             : 
    1579           0 :   bank->f.max_tick_height = genesis->poh.ticks_per_slot * (bank->f.slot + 1);
    1580             : 
    1581           0 :   bank->f.hashes_per_tick = genesis->poh.hashes_per_tick;
    1582             : 
    1583           0 :   bank->f.ns_per_slot = (fd_w_u128_t) { .ud=target_tick_duration * genesis->poh.ticks_per_slot };
    1584             : 
    1585           0 :   bank->f.ticks_per_slot = genesis->poh.ticks_per_slot;
    1586             : 
    1587           0 :   bank->f.genesis_creation_time = genesis->creation_time;
    1588             : 
    1589           0 :   bank->f.slots_per_year = SECONDS_PER_YEAR * (1000000000.0 / (double)target_tick_duration) / (double)genesis->poh.ticks_per_slot;
    1590             : 
    1591           0 :   bank->f.signature_count = 0UL;
    1592             : 
    1593             :   /* Derive epoch stakes */
    1594             : 
    1595           0 :   fd_stake_delegations_t * stake_delegations = fd_banks_stake_delegations_root_query( banks );
    1596           0 :   if( FD_UNLIKELY( !stake_delegations ) ) {
    1597           0 :     FD_LOG_CRIT(( "Failed to join and new a stake delegations" ));
    1598           0 :   }
    1599             : 
    1600           0 :   ulong capitalization = 0UL;
    1601             : 
    1602           0 :   for( ulong i=0UL; i<genesis->account_cnt; i++ ) {
    1603           0 :     fd_genesis_account_t account[1];
    1604           0 :     fd_genesis_account( genesis, genesis_blob, account, i );
    1605             : 
    1606           0 :     capitalization = fd_ulong_sat_add( capitalization, account->meta.lamports );
    1607             : 
    1608           0 :     uchar const * acc_data = account->data;
    1609             : 
    1610           0 :     if( !memcmp( account->meta.owner, fd_solana_stake_program_id.key, sizeof(fd_pubkey_t) ) ) {
    1611             :       /* If an account is a stake account, then it must be added to the
    1612             :          stake delegations cache. We should only add stake accounts that
    1613             :          have a valid non-zero stake. */
    1614           0 :       fd_stake_state_t const * stake_state = fd_stake_state_view( acc_data, account->meta.dlen );
    1615           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 )); }
    1616           0 :       if( stake_state->stake_type!=FD_STAKE_STATE_STAKE ) continue;
    1617           0 :       if( !stake_state->stake.stake.delegation.stake ) continue;
    1618             : 
    1619           0 :       if( FD_UNLIKELY( stake_state->stake.stake.delegation.warmup_cooldown_rate!=0.25 &&
    1620           0 :                        stake_state->stake.stake.delegation.warmup_cooldown_rate!=0.09 ) ) {
    1621           0 :         FD_BASE58_ENCODE_32_BYTES( account->pubkey.uc, stake_b58 );
    1622           0 :         FD_LOG_ERR(( "Invalid warmup cooldown rate %f for stake account %s", stake_state->stake.stake.delegation.warmup_cooldown_rate, stake_b58 ));
    1623           0 :       }
    1624             : 
    1625           0 :       fd_stake_delegations_root_update(
    1626           0 :           stake_delegations,
    1627           0 :           &account->pubkey,
    1628           0 :           &stake_state->stake.stake.delegation.voter_pubkey,
    1629           0 :           stake_state->stake.stake.delegation.stake,
    1630           0 :           stake_state->stake.stake.delegation.activation_epoch,
    1631           0 :           stake_state->stake.stake.delegation.deactivation_epoch,
    1632           0 :           stake_state->stake.stake.credits_observed,
    1633           0 :           stake_state->stake.stake.delegation.warmup_cooldown_rate );
    1634             : 
    1635           0 :     } else if( !memcmp( account->meta.owner, fd_solana_feature_program_id.key, sizeof(fd_pubkey_t) ) ) {
    1636             :       /* Feature Account */
    1637             : 
    1638             :       /* Scan list of feature IDs to resolve address=>feature offset */
    1639           0 :       fd_feature_id_t const *found = NULL;
    1640           0 :       for( fd_feature_id_t const * id = fd_feature_iter_init();
    1641           0 :            !fd_feature_iter_done( id );
    1642           0 :            id = fd_feature_iter_next( id ) ) {
    1643           0 :         if( fd_pubkey_eq( &account->pubkey, &id->id ) ) {
    1644           0 :           found = id;
    1645           0 :           break;
    1646           0 :         }
    1647           0 :       }
    1648             : 
    1649           0 :       if( found ) {
    1650             :         /* Load feature activation */
    1651           0 :         fd_feature_t feature[1];
    1652           0 :         if( FD_UNLIKELY( !fd_feature_decode( feature, acc_data, account->meta.dlen ) ) ) {
    1653           0 :           FD_BASE58_ENCODE_32_BYTES( account->pubkey.uc, addr_b58 );
    1654           0 :           FD_LOG_WARNING(( "genesis contains corrupt feature account %s", addr_b58 ));
    1655           0 :           FD_LOG_HEXDUMP_ERR(( "data", acc_data, account->meta.dlen ));
    1656           0 :         }
    1657           0 :         fd_features_t * features = &bank->f.features;
    1658           0 :         if( feature->is_active ) {
    1659           0 :           FD_BASE58_ENCODE_32_BYTES( account->pubkey.uc, pubkey_b58 );
    1660           0 :           FD_LOG_DEBUG(( "feature %s activated at slot %lu (genesis)", pubkey_b58, feature->activation_slot ));
    1661           0 :           fd_features_set( features, found, feature->activation_slot );
    1662           0 :         } else {
    1663           0 :           FD_BASE58_ENCODE_32_BYTES( account->pubkey.uc, pubkey_b58 );
    1664           0 :           FD_LOG_DEBUG(( "feature %s not activated (genesis)", pubkey_b58 ));
    1665           0 :           fd_features_set( features, found, ULONG_MAX );
    1666           0 :         }
    1667           0 :       }
    1668           0 :     }
    1669           0 :   }
    1670             : 
    1671             :   /* fd_refresh_vote_accounts is responsible for updating the vote
    1672             :      states with the total amount of active delegated stake. It does
    1673             :      this by iterating over all active stake delegations and summing up
    1674             :      the amount of stake that is delegated to each vote account. */
    1675             : 
    1676           0 :   ulong new_rate_activation_epoch = 0UL;
    1677             : 
    1678           0 :   fd_stake_history_t stake_history[1];
    1679           0 :   fd_sysvar_stake_history_read( accdb, xid, stake_history );
    1680             : 
    1681           0 :   fd_refresh_vote_accounts(
    1682           0 :       bank,
    1683           0 :       accdb,
    1684           0 :       xid,
    1685           0 :       runtime_stack,
    1686           0 :       stake_delegations,
    1687           0 :       stake_history,
    1688           0 :       &new_rate_activation_epoch );
    1689             : 
    1690           0 :   fd_vote_stakes_t * vote_stakes = fd_bank_vote_stakes( bank );
    1691           0 :   fd_vote_stakes_genesis_fini( vote_stakes );
    1692             : 
    1693           0 :   bank->f.epoch = 0UL;
    1694             : 
    1695           0 :   bank->f.capitalization = capitalization;
    1696           0 : }
    1697             : 
    1698             : static int
    1699             : fd_runtime_process_genesis_block( fd_bank_t *               bank,
    1700             :                                   fd_accdb_user_t *         accdb,
    1701             :                                   fd_funk_txn_xid_t const * xid,
    1702             :                                   fd_capture_ctx_t *        capture_ctx,
    1703           0 :                                   fd_runtime_stack_t *      runtime_stack ) {
    1704             : 
    1705           0 :   fd_hash_t * poh = &bank->f.poh;
    1706           0 :   ulong hashcnt_per_slot = bank->f.hashes_per_tick * bank->f.ticks_per_slot;
    1707           0 :   while( hashcnt_per_slot-- ) {
    1708           0 :     fd_sha256_hash( poh->hash, sizeof(fd_hash_t), poh->hash );
    1709           0 :   }
    1710             : 
    1711           0 :   bank->f.execution_fees = 0UL;
    1712             : 
    1713           0 :   bank->f.priority_fees = 0UL;
    1714             : 
    1715           0 :   bank->f.signature_count = 0UL;
    1716             : 
    1717           0 :   bank->f.txn_count = 0UL;
    1718             : 
    1719           0 :   bank->f.failed_txn_count = 0UL;
    1720             : 
    1721           0 :   bank->f.nonvote_failed_txn_count = 0UL;
    1722             : 
    1723           0 :   bank->f.total_compute_units_used = 0UL;
    1724             : 
    1725           0 :   fd_runtime_genesis_init_program( bank, accdb, xid, capture_ctx );
    1726             : 
    1727           0 :   fd_sysvar_slot_history_update( bank, accdb, xid, capture_ctx );
    1728             : 
    1729           0 :   fd_runtime_update_leaders( bank, runtime_stack );
    1730             : 
    1731           0 :   fd_runtime_freeze( bank, accdb, capture_ctx );
    1732             : 
    1733           0 :   fd_lthash_value_t const * lthash = fd_bank_lthash_locking_query( bank );
    1734             : 
    1735           0 :   fd_hash_t const * prev_bank_hash = &bank->f.bank_hash;
    1736             : 
    1737           0 :   fd_hash_t * bank_hash = &bank->f.bank_hash;
    1738           0 :   fd_hashes_hash_bank(
    1739           0 :     lthash,
    1740           0 :     prev_bank_hash,
    1741           0 :     (fd_hash_t *)bank->f.poh.hash,
    1742           0 :     0UL,
    1743           0 :     bank_hash );
    1744             : 
    1745           0 :   fd_bank_lthash_end_locking_query( bank );
    1746             : 
    1747           0 :   return FD_RUNTIME_EXECUTE_SUCCESS;
    1748           0 : }
    1749             : 
    1750             : void
    1751             : fd_runtime_read_genesis( fd_banks_t *              banks,
    1752             :                          fd_bank_t *               bank,
    1753             :                          fd_accdb_user_t *         accdb,
    1754             :                          fd_funk_txn_xid_t const * xid,
    1755             :                          fd_capture_ctx_t *        capture_ctx,
    1756             :                          fd_hash_t const *         genesis_hash,
    1757             :                          fd_lthash_value_t const * genesis_lthash,
    1758             :                          fd_genesis_t const *      genesis,
    1759             :                          uchar const *             genesis_blob,
    1760           0 :                          fd_runtime_stack_t *      runtime_stack ) {
    1761             : 
    1762           0 :   fd_lthash_value_t * lthash = fd_bank_lthash_locking_modify( bank );
    1763           0 :   *lthash = *genesis_lthash;
    1764           0 :   fd_bank_lthash_end_locking_modify( bank );
    1765             : 
    1766             :   /* Once the accounts have been loaded from the genesis config into
    1767             :      the accounts db, we can initialize the bank state. This involves
    1768             :      setting some fields, and notably setting up the vote and stake
    1769             :      caches which are used for leader scheduling/rewards. */
    1770             : 
    1771           0 :   fd_runtime_init_bank_from_genesis( banks, bank, runtime_stack, accdb, xid, genesis, genesis_blob, genesis_hash );
    1772             : 
    1773             :   /* Write the native programs to the accounts db. */
    1774             : 
    1775           0 :   for( ulong i=0UL; i<genesis->builtin_cnt; i++ ) {
    1776           0 :     fd_genesis_builtin_t builtin[1];
    1777           0 :     fd_genesis_builtin( genesis, genesis_blob, builtin, i );
    1778           0 :     fd_write_builtin_account( bank, accdb, xid, capture_ctx, builtin->pubkey, builtin->data, builtin->dlen );
    1779           0 :   }
    1780             : 
    1781           0 :   fd_features_restore( bank, accdb, xid );
    1782             : 
    1783             :   /* At this point, state related to the bank and the accounts db
    1784             :      have been initialized and we are free to finish executing the
    1785             :      block. In practice, this updates some bank fields (notably the
    1786             :      poh and bank hash). */
    1787             : 
    1788           0 :   int err = fd_runtime_process_genesis_block( bank, accdb, xid, capture_ctx, runtime_stack );
    1789           0 :   if( FD_UNLIKELY( err ) ) FD_LOG_CRIT(( "genesis slot 0 execute failed with error %d", err ));
    1790           0 : }
    1791             : 
    1792             : void
    1793             : fd_runtime_block_execute_finalize( fd_bank_t *        bank,
    1794             :                                    fd_accdb_user_t *  accdb,
    1795          78 :                                    fd_capture_ctx_t * capture_ctx ) {
    1796             : 
    1797             :   /* This slot is now "frozen" and can't be changed anymore. */
    1798          78 :   fd_runtime_freeze( bank, accdb, capture_ctx );
    1799             : 
    1800          78 :   fd_runtime_update_bank_hash( bank, capture_ctx );
    1801          78 : }
    1802             : 
    1803             : 
    1804             : /* Mirrors Agave function solana_sdk::transaction_context::find_index_of_account
    1805             : 
    1806             :    Backward scan over transaction accounts.
    1807             :    Returns -1 if not found.
    1808             : 
    1809             :    https://github.com/anza-xyz/agave/blob/v2.1.14/sdk/src/transaction_context.rs#L233-L238 */
    1810             : 
    1811             : int
    1812             : fd_runtime_find_index_of_account( fd_txn_out_t const * txn_out,
    1813         279 :                                   fd_pubkey_t const *  pubkey ) {
    1814        1008 :   for( ulong i=txn_out->accounts.cnt; i>0UL; i-- ) {
    1815         855 :     if( 0==memcmp( pubkey, &txn_out->accounts.keys[ i-1UL ], sizeof(fd_pubkey_t) ) ) {
    1816         126 :       return (int)(i-1UL);
    1817         126 :     }
    1818         855 :   }
    1819         153 :   return -1;
    1820         279 : }
    1821             : 
    1822             : fd_accdb_ref_t *
    1823             : fd_runtime_get_account_at_index( fd_txn_in_t const *             txn_in,
    1824             :                                  fd_txn_out_t *                  txn_out,
    1825             :                                  ushort                          idx,
    1826        1704 :                                  fd_txn_account_condition_fn_t * condition ) {
    1827        1704 :   if( FD_UNLIKELY( idx>=txn_out->accounts.cnt ) ) {
    1828           0 :     return NULL;
    1829           0 :   }
    1830             : 
    1831        1704 :   if( FD_LIKELY( condition != NULL ) ) {
    1832         771 :     if( FD_UNLIKELY( !condition( txn_in, txn_out, idx ) ) ) {
    1833          18 :       return NULL;
    1834          18 :     }
    1835         771 :   }
    1836             : 
    1837        1686 :   return txn_out->accounts.account[ idx ].ref;
    1838        1704 : }
    1839             : 
    1840             : fd_accdb_ref_t *
    1841             : fd_runtime_get_account_with_key( fd_txn_in_t const *             txn_in,
    1842             :                                  fd_txn_out_t *                  txn_out,
    1843             :                                  fd_pubkey_t const *             pubkey,
    1844             :                                  int *                           index_out,
    1845           0 :                                  fd_txn_account_condition_fn_t * condition ) {
    1846           0 :   int index = fd_runtime_find_index_of_account( txn_out, pubkey );
    1847           0 :   if( FD_UNLIKELY( index<0 ) ) return NULL;
    1848             : 
    1849           0 :   *index_out = index;
    1850             : 
    1851           0 :   return fd_runtime_get_account_at_index( txn_in, txn_out, (uchar)index, condition );
    1852           0 : }
    1853             : 
    1854             : fd_accdb_ro_t *
    1855             : fd_runtime_get_executable_account( fd_runtime_t *      runtime,
    1856             :                                    fd_txn_in_t const * txn_in,
    1857             :                                    fd_txn_out_t *      txn_out,
    1858           0 :                                    fd_pubkey_t const * pubkey ) {
    1859             :   /* First try to fetch the executable account from the existing
    1860             :      borrowed accounts.  If the pubkey is in the account keys, then we
    1861             :      want to re-use that borrowed account since it reflects changes from
    1862             :      prior instructions.  Referencing the read-only executable accounts
    1863             :      list is incorrect behavior when the program data account is written
    1864             :      to in a prior instruction (e.g. program upgrade + invoke within the
    1865             :      same txn) */
    1866             : 
    1867           0 :   fd_txn_account_condition_fn_t * condition = fd_runtime_account_check_exists;
    1868             : 
    1869           0 :   int index;
    1870           0 :   fd_accdb_ref_t * ref = fd_runtime_get_account_with_key(
    1871           0 :       txn_in, txn_out, pubkey, &index, condition );
    1872           0 :   if( FD_UNLIKELY( ref ) ) return fd_accdb_ref_ro( ref );
    1873             : 
    1874           0 :   for( ushort i=0; i<runtime->accounts.executable_cnt; i++ ) {
    1875           0 :     if( fd_pubkey_eq( pubkey, fd_accdb_ref_address( &runtime->accounts.executable[i] ) ) ) {
    1876           0 :       fd_accdb_ro_t * ro = &runtime->accounts.executable[i];
    1877           0 :       if( FD_UNLIKELY( !fd_account_meta_exists( ro->meta ) ) ) {
    1878           0 :         return NULL;
    1879           0 :       }
    1880           0 :       return ro;
    1881           0 :     }
    1882           0 :   }
    1883             : 
    1884           0 :   return NULL;
    1885           0 : }
    1886             : 
    1887             : int
    1888             : fd_runtime_get_key_of_account_at_index( fd_txn_out_t *        txn_out,
    1889             :                                         ushort                idx,
    1890         990 :                                         fd_pubkey_t const * * key ) {
    1891             :   /* Return a MissingAccount error if idx is out of bounds.
    1892             :      https://github.com/anza-xyz/agave/blob/v3.1.4/transaction-context/src/lib.rs#L187 */
    1893         990 :   if( FD_UNLIKELY( idx>=txn_out->accounts.cnt ) ) {
    1894           0 :     return FD_EXECUTOR_INSTR_ERR_MISSING_ACC;
    1895           0 :   }
    1896             : 
    1897         990 :   *key = &txn_out->accounts.keys[ idx ];
    1898         990 :   return FD_EXECUTOR_INSTR_SUCCESS;
    1899         990 : }
    1900             : 
    1901             : /* https://github.com/anza-xyz/agave/blob/v2.1.1/sdk/program/src/message/versions/v0/loaded.rs#L162 */
    1902             : int
    1903             : fd_txn_account_is_demotion( const int        idx,
    1904             :                             const fd_txn_t * txn_descriptor,
    1905        6033 :                             const uint       bpf_upgradeable_in_txn ) {
    1906        6033 :   uint is_program = 0U;
    1907       12126 :   for( ulong j=0UL; j<txn_descriptor->instr_cnt; j++ ) {
    1908        6093 :     if( txn_descriptor->instr[j].program_id == idx ) {
    1909           0 :       is_program = 1U;
    1910           0 :       break;
    1911           0 :     }
    1912        6093 :   }
    1913             : 
    1914        6033 :   return (is_program && !bpf_upgradeable_in_txn);
    1915        6033 : }
    1916             : 
    1917             : uint
    1918             : fd_txn_account_has_bpf_loader_upgradeable( const fd_pubkey_t * account_keys,
    1919        6255 :                                            const ulong         accounts_cnt ) {
    1920       20256 :   for( ulong j=0; j<accounts_cnt; j++ ) {
    1921       14001 :     const fd_pubkey_t * acc = &account_keys[j];
    1922       14001 :     if ( memcmp( acc->uc, fd_solana_bpf_loader_upgradeable_program_id.key, sizeof(fd_pubkey_t) ) == 0 ) {
    1923           0 :       return 1U;
    1924           0 :     }
    1925       14001 :   }
    1926        6255 :   return 0U;
    1927        6255 : }
    1928             : 
    1929             : static inline int
    1930             : fd_runtime_account_is_writable_idx_flat( const ushort          idx,
    1931             :                                          const fd_pubkey_t *   addr_at_idx,
    1932             :                                          const fd_txn_t *      txn_descriptor,
    1933        6255 :                                          const uint            bpf_upgradeable_in_txn ) {
    1934             :   /* https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L43 */
    1935        6255 :   if( !fd_txn_is_writable( txn_descriptor, idx ) ) {
    1936         213 :     return 0;
    1937         213 :   }
    1938             : 
    1939             :   /* See comments in fd_system_ids.h.
    1940             :      https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L44 */
    1941        6042 :   if( fd_pubkey_is_active_reserved_key( addr_at_idx ) ||
    1942        6042 :       fd_pubkey_is_pending_reserved_key( addr_at_idx ) ) {
    1943             : 
    1944           9 :     return 0;
    1945           9 :   }
    1946             : 
    1947        6033 :   if( fd_txn_account_is_demotion( idx, txn_descriptor, bpf_upgradeable_in_txn ) ) {
    1948           0 :     return 0;
    1949           0 :   }
    1950             : 
    1951        6033 :   return 1;
    1952        6033 : }
    1953             : 
    1954             : 
    1955             : /* This function aims to mimic the writable accounts check to populate the writable accounts cache, used
    1956             :    to determine if accounts are writable or not.
    1957             : 
    1958             :    https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L38-L47 */
    1959             : int
    1960             : fd_runtime_account_is_writable_idx( fd_txn_in_t const *  txn_in,
    1961             :                                     fd_txn_out_t const * txn_out,
    1962        6255 :                                     ushort               idx ) {
    1963        6255 :   uint bpf_upgradeable = fd_txn_account_has_bpf_loader_upgradeable( txn_out->accounts.keys, txn_out->accounts.cnt );
    1964        6255 :   return fd_runtime_account_is_writable_idx_flat( idx,
    1965        6255 :                                                    &txn_out->accounts.keys[idx],
    1966        6255 :                                                    TXN( txn_in->txn ),
    1967        6255 :                                                    bpf_upgradeable );
    1968        6255 : }
    1969             : 
    1970             : /* Account pre-condition filtering functions */
    1971             : 
    1972             : int
    1973             : fd_runtime_account_check_exists( fd_txn_in_t const * txn_in,
    1974             :                                  fd_txn_out_t *      txn_out,
    1975         609 :                                  ushort              idx ) {
    1976         609 :   (void) txn_in;
    1977         609 :   return fd_account_meta_exists( txn_out->accounts.account[idx].meta );
    1978         609 : }
    1979             : 
    1980             : int
    1981             : fd_runtime_account_check_fee_payer_writable( fd_txn_in_t const * txn_in,
    1982             :                                              fd_txn_out_t *      txn_out,
    1983         162 :                                              ushort              idx ) {
    1984         162 :   (void) txn_out;
    1985         162 :   return fd_txn_is_writable( TXN( txn_in->txn ), idx );
    1986         162 : }
    1987             : 
    1988             : 
    1989             : int
    1990         324 : fd_account_meta_checked_sub_lamports( fd_account_meta_t * meta, ulong lamports ) {
    1991         324 :   ulong balance_post = 0UL;
    1992         324 :   int err = fd_ulong_checked_sub( meta->lamports,
    1993         324 :                                   lamports,
    1994         324 :                                   &balance_post );
    1995         324 :   if( FD_UNLIKELY( err ) ) {
    1996           0 :     return FD_EXECUTOR_INSTR_ERR_ARITHMETIC_OVERFLOW;
    1997           0 :   }
    1998             : 
    1999         324 :   meta->lamports = balance_post;
    2000         324 :   return FD_EXECUTOR_INSTR_SUCCESS;
    2001         324 : }

Generated by: LCOV version 1.14