LCOV - code coverage report
Current view: top level - flamenco/runtime - fd_runtime.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 809 1132 71.5 %
Date: 2026-08-15 04:34:25 Functions: 41 48 85.4 %

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

Generated by: LCOV version 1.14