LCOV - code coverage report
Current view: top level - flamenco/runtime - fd_runtime.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 796 1108 71.8 %
Date: 2026-08-08 04:48:28 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_top_votes_t const *   top_votes_t_1    = fd_bank_top_votes_t_1_query( 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( top_votes_t_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_top_votes_t const *   top_votes_t_2    = fd_bank_top_votes_t_2_query( 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( top_votes_t_2, 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        4443 :                                           ulong       latest_signatures_per_slot ) {
     302             : 
     303        4443 :   fd_fee_rate_governor_t const * base_fee_rate_governor = &bank->f.fee_rate_governor;
     304             : 
     305        4443 :   ulong old_lamports_per_signature = bank->f.rbh_lamports_per_sig;
     306             : 
     307        4443 :   fd_fee_rate_governor_t me = {
     308        4443 :     .target_signatures_per_slot    = base_fee_rate_governor->target_signatures_per_slot,
     309        4443 :     .target_lamports_per_signature = base_fee_rate_governor->target_lamports_per_signature,
     310        4443 :     .max_lamports_per_signature    = base_fee_rate_governor->max_lamports_per_signature,
     311        4443 :     .min_lamports_per_signature    = base_fee_rate_governor->min_lamports_per_signature,
     312        4443 :     .burn_percent                  = base_fee_rate_governor->burn_percent
     313        4443 :   };
     314             : 
     315        4443 :   ulong new_lamports_per_signature = 0;
     316        4443 :   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        4437 :   } else {
     344        4437 :     new_lamports_per_signature = base_fee_rate_governor->target_lamports_per_signature;
     345        4437 :     me.min_lamports_per_signature = me.target_lamports_per_signature;
     346        4437 :     me.max_lamports_per_signature = me.target_lamports_per_signature;
     347        4437 :   }
     348        4443 :   bank->f.fee_rate_governor = me;
     349        4443 :   bank->f.rbh_lamports_per_sig = new_lamports_per_signature;
     350        4443 : }
     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         264 :   fd_bank_stake_delegations_end_frontier_query( banks, bank );
     656             : 
     657             :   /* The Agave client handles updating their stakes cache with a call to
     658             :      update_epoch_stakes() which keys stakes by the leader schedule
     659             :      epochs and retains up to 6 epochs of stakes.  However, to correctly
     660             :      calculate the leader schedule, we just need to maintain the vote
     661             :      states for the current epoch, the previous epoch, and the one
     662             :      before that.
     663             :      https://github.com/anza-xyz/agave/blob/v3.0.4/runtime/src/bank.rs#L2175
     664             :   */
     665             : 
     666             :   /* Now that our stakes caches have been updated, we can calculate the
     667             :      leader schedule for the upcoming epoch epoch using our new
     668             :      vote_states_prev_prev (stakes for T-2). */
     669             : 
     670         264 :   fd_runtime_update_leaders( bank, runtime_stack );
     671             : 
     672         264 :   long end = fd_log_wallclock();
     673         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() ));
     674         264 : }
     675             : 
     676             : static void
     677             : fd_runtime_block_pre_execute_process_new_epoch( fd_banks_t *         banks,
     678             :                                                 fd_bank_t *          bank,
     679             :                                                 fd_accdb_t *         accdb,
     680             :                                                 fd_capture_ctx_t *   capture_ctx,
     681             :                                                 fd_runtime_stack_t * runtime_stack,
     682        4443 :                                                 int *                is_epoch_boundary ) {
     683             : 
     684        4443 :   ulong const slot = bank->f.slot;
     685        4443 :   if( FD_LIKELY( slot != 0UL ) ) {
     686        4443 :     fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     687             : 
     688        4443 :     ulong prev_epoch = fd_slot_to_epoch( epoch_schedule, bank->f.parent_slot, NULL );
     689        4443 :     ulong slot_idx;
     690        4443 :     ulong new_epoch  = fd_slot_to_epoch( epoch_schedule, slot, &slot_idx );
     691        4443 :     if( FD_UNLIKELY( slot_idx==1UL && new_epoch==0UL ) ) {
     692             :       /* The block after genesis has a height of 1. */
     693           0 :       bank->f.block_height = 1UL;
     694           0 :     }
     695             : 
     696        4443 :     if( FD_UNLIKELY( prev_epoch<new_epoch || !slot_idx ) ) {
     697         264 :       FD_LOG_DEBUG(( "Epoch boundary starting" ));
     698         264 :       fd_runtime_process_new_epoch( banks, bank, accdb, capture_ctx, prev_epoch, runtime_stack );
     699         264 :       *is_epoch_boundary = 1;
     700        4179 :     } else {
     701        4179 :       *is_epoch_boundary = 0;
     702        4179 :     }
     703             : 
     704        4443 :     fd_distribute_partitioned_epoch_rewards( banks, bank, accdb, runtime_stack, capture_ctx );
     705        4443 :   } else {
     706           0 :     *is_epoch_boundary = 0;
     707           0 :   }
     708        4443 : }
     709             : 
     710             : 
     711             : static void
     712             : fd_runtime_block_sysvar_update_pre_execute( fd_bank_t *          bank,
     713             :                                             fd_accdb_t *         accdb,
     714             :                                             fd_runtime_stack_t * runtime_stack,
     715        4443 :                                             fd_capture_ctx_t *   capture_ctx ) {
     716             :   // let (fee_rate_governor, fee_components_time_us) = measure_us!(
     717             :   //     FeeRateGovernor::new_derived(&parent.fee_rate_governor, parent.signature_count())
     718             :   // );
     719             :   /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L1312-L1314 */
     720             : 
     721        4443 :   fd_runtime_new_fee_rate_governor_derived( bank, bank->f.parent_signature_cnt );
     722             : 
     723        4443 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     724        4443 :   ulong                       parent_epoch   = fd_slot_to_epoch( epoch_schedule, bank->f.parent_slot, NULL );
     725        4443 :   fd_sysvar_clock_update( bank, accdb, capture_ctx, runtime_stack, &parent_epoch );
     726             : 
     727             :   // It has to go into the current txn previous info but is not in slot 0
     728        4443 :   if( bank->f.slot != 0 ) {
     729        4443 :     fd_sysvar_slot_hashes_update( bank, accdb, capture_ctx );
     730        4443 :   }
     731        4443 :   fd_sysvar_last_restart_slot_update( bank, accdb, capture_ctx );
     732        4443 : }
     733             : 
     734             : int
     735             : fd_runtime_load_txn_address_lookup_tables( fd_txn_t const *         txn,
     736             :                                            uchar const *            payload,
     737             :                                            fd_accdb_t *             accdb,
     738             :                                            fd_accdb_fork_id_t       fork_id,
     739             :                                            ulong                    slot,
     740             :                                            fd_slot_hashes_t const * hashes,
     741         210 :                                            fd_acct_addr_t *         out_accts_alt ) {
     742             : 
     743         210 :   if( FD_LIKELY( txn->transaction_version!=FD_TXN_V0 ) ) return FD_RUNTIME_EXECUTE_SUCCESS;
     744             : 
     745         207 :   fd_alut_interp_t interp[1];
     746         207 :   fd_alut_interp_new( interp, out_accts_alt, txn, payload, hashes, slot );
     747             : 
     748         207 :   fd_txn_acct_addr_lut_t const * addr_luts = fd_txn_get_address_tables_const( txn );
     749         297 :   for( ulong i=0UL; i<txn->addr_table_lookup_cnt; i++ ) {
     750         129 :     fd_txn_acct_addr_lut_t const * addr_lut = &addr_luts[i];
     751         129 :     fd_pubkey_t addr_lut_acc = FD_LOAD( fd_pubkey_t, payload+addr_lut->addr_off );
     752             : 
     753         129 :     fd_acc_t acc = fd_accdb_read_one( accdb, fork_id, addr_lut_acc.uc );
     754         129 :     if( FD_UNLIKELY( !acc.lamports ) ) {
     755           3 :       fd_accdb_unread_one( accdb, &acc );
     756           3 :       return FD_RUNTIME_TXN_ERR_ADDRESS_LOOKUP_TABLE_NOT_FOUND;
     757           3 :     }
     758         126 :     int err = fd_alut_interp_next( interp, &addr_lut_acc, acc.owner, acc.data, acc.data_len );
     759         126 :     fd_accdb_unread_one( accdb, &acc );
     760         126 :     if( FD_UNLIKELY( err ) ) return err;
     761         126 :   }
     762             : 
     763         168 :   return FD_RUNTIME_EXECUTE_SUCCESS;
     764         207 : }
     765             : 
     766             : /* Pre-populate the bank's in-memory feature set with upcoming feature
     767             :    activations.  If the current slot is the last slot before an epoch
     768             :    boundary, scan all known feature accounts. Otherwise, returns early.
     769             : 
     770             :    For any feature that is pending (not yet activated on-chain) but has
     771             :    an account owned by the feature program, set the in-memory activation
     772             :    slot within the bank's featureset to the first slot of the next
     773             :    epoch.  This is needed so that deployment verification (which uses
     774             :    slot+1) can detect features that will activate at the next epoch
     775             :    boundary.
     776             : 
     777             :    In Agave, program deployments use the feature set from the next
     778             :    slot via DELAY_VISIBILITY_SLOT_OFFSET.  The runtime environments
     779             :    for deployment are selected based on epoch_of(slot+1):
     780             :    https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/bank.rs#L3280-L3295
     781             :    https://github.com/anza-xyz/agave/blob/v3.1.8/svm/src/transaction_processor.rs#L339-L345
     782             : 
     783             :    This function does NOT write to feature accounts or update the
     784             :    lthash.  It only modifies the bank's in-memory feature set. */
     785             : static void
     786             : fd_features_prepopulate_upcoming( fd_bank_t *  bank,
     787        4443 :                                   fd_accdb_t * accdb ) {
     788        4443 :   ulong slot = bank->f.slot;
     789        4443 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     790        4443 :   ulong curr_epoch = fd_slot_to_epoch( epoch_schedule, slot,     NULL );
     791        4443 :   ulong next_epoch = fd_slot_to_epoch( epoch_schedule, slot+1UL, NULL );
     792        4443 :   if( FD_LIKELY( curr_epoch==next_epoch ) ) return;
     793             : 
     794          69 :   fd_features_restore( bank, accdb );
     795          69 : }
     796             : 
     797             : void
     798             : fd_runtime_block_execute_prepare( fd_banks_t *         banks,
     799             :                                   fd_bank_t *          bank,
     800             :                                   fd_accdb_t *         accdb,
     801             :                                   fd_runtime_stack_t * runtime_stack,
     802             :                                   fd_capture_ctx_t *   capture_ctx,
     803        4443 :                                   int *                is_epoch_boundary ) {
     804        4443 :   fd_runtime_block_pre_execute_process_new_epoch( banks, bank, accdb, capture_ctx, runtime_stack, is_epoch_boundary );
     805             : 
     806        4443 :   if( FD_LIKELY( bank->f.slot ) ) {
     807        4443 :     fd_cost_tracker_t * cost_tracker = fd_bank_cost_tracker_modify( bank );
     808        4443 :     FD_TEST( cost_tracker );
     809        4443 :     fd_cost_tracker_init( cost_tracker, &bank->f.features, &bank->f.slot_params, bank->f.slot );
     810        4443 :   }
     811             : 
     812        4443 :   fd_features_prepopulate_upcoming( bank, accdb );
     813        4443 :   fd_runtime_block_sysvar_update_pre_execute( bank, accdb, runtime_stack, capture_ctx );
     814        4443 :   FD_TEST( fd_sysvar_cache_restore( bank, accdb ) );
     815        4443 : }
     816             : 
     817             : static void
     818             : fd_runtime_update_bank_hash( fd_bank_t *        bank,
     819         339 :                              fd_capture_ctx_t * capture_ctx ) {
     820             :   /* Compute the new bank hash */
     821         339 :   fd_lthash_value_t const * lthash = fd_bank_lthash_locking_query( bank );
     822         339 :   fd_hash_t new_bank_hash[1] = { 0 };
     823         339 :   fd_hashes_hash_bank(
     824         339 :       lthash,
     825         339 :       &bank->f.prev_bank_hash,
     826         339 :       (fd_hash_t *)bank->f.poh.hash,
     827         339 :       bank->f.signature_count,
     828         339 :       new_bank_hash );
     829             : 
     830             :   /* Update the bank hash */
     831         339 :   bank->f.bank_hash = *new_bank_hash;
     832             : 
     833         339 :   if( capture_ctx && capture_ctx->capture_solcap &&
     834         339 :       bank->f.slot>=capture_ctx->solcap_start_slot ) {
     835             : 
     836           0 :     uchar lthash_hash[FD_HASH_FOOTPRINT];
     837           0 :     fd_blake3_hash(lthash->bytes, FD_LTHASH_LEN_BYTES, lthash_hash );
     838           0 :     fd_capture_link_write_bank_preimage(
     839           0 :       capture_ctx,
     840           0 :       bank->f.slot,
     841           0 :       (fd_hash_t *)new_bank_hash->hash,
     842           0 :       (fd_hash_t *)&bank->f.prev_bank_hash,
     843           0 :       (fd_hash_t *)lthash_hash,
     844           0 :       (fd_hash_t *)bank->f.poh.hash,
     845           0 :       bank->f.signature_count );
     846           0 :   }
     847             : 
     848         339 :   fd_bank_lthash_end_locking_query( bank );
     849         339 : }
     850             : 
     851             : /******************************************************************************/
     852             : /* Transaction Level Execution Management                                     */
     853             : /******************************************************************************/
     854             : 
     855             : /* fd_runtime_pre_execute_check is responsible for conducting many of
     856             :    the transaction sanitization checks.  This is a combination of some
     857             :    of the work done in Agave's load_and_execute_transactions(), and some
     858             :    of the work done in Agave's transaction ingestion stage, before the
     859             :    transaction even hits the scheduler.  We do some of the checks also
     860             :    in our transaction ingestion stage.  For example, the duplicate
     861             :    account check is performed in both the leader and the replay
     862             :    scheduler.  As a result, the duplicate account check below is
     863             :    essentially redundant, except that our fuzzing harness expects a
     864             :    single entry point to cover all of these checks.  So we keep all of
     865             :    the checks below for fuzzing purposes.  We could in theory hoist some
     866             :    of the pre-scheduler checks into a public function that is only
     867             :    invoked by the fuzzer to avoid duplication in the leader and the
     868             :    replay pipeline.  But all the duplicate checks are pretty cheap, and
     869             :    the order and placement of the checks are also in motion on Agave's
     870             :    side, and performing all the checks faithfully would require access
     871             :    to the bank in the scheduler which is kind of gross.  So that's all
     872             :    probably more hassle than worth. */
     873             : 
     874             : static inline int
     875             : fd_runtime_pre_execute_check( fd_runtime_t *      runtime,
     876             :                               fd_bank_t *         bank,
     877             :                               fd_txn_in_t const * txn_in,
     878         381 :                               fd_txn_out_t *      txn_out ) {
     879             : 
     880             :   /* https://github.com/anza-xyz/agave/blob/16de8b75ebcd57022409b422de557dd37b1de8db/sdk/src/transaction/sanitized.rs#L263-L275
     881             :      TODO: Agave's precompile verification is done at the slot level, before batching and executing transactions. This logic should probably
     882             :      be moved in the future. The Agave call hierarchy looks something like this:
     883             :             process_single_slot
     884             :                    v
     885             :             confirm_full_slot
     886             :                    v
     887             :             confirm_slot_entries --------------------------------------------------->
     888             :                    v                               v                                v
     889             :             verify_transaction    ComputeBudget::process_instruction         process_entries
     890             :                    v                                                                v
     891             :             verify_precompiles                                                process_batches
     892             :                                                                                     v
     893             :                                                                                    ...
     894             :                                                                                     v
     895             :                                                                         load_and_execute_transactions
     896             :                                                                                     v
     897             :                                                                                    ...
     898             :                                                                                     v
     899             :                                                                               load_accounts --> load_transaction_accounts
     900             :                                                                                     v
     901             :                                                                        general transaction execution
     902             : 
     903             :   */
     904             : 
     905             :   /* Verify the transaction. For now, this step only involves processing
     906             :      the compute budget instructions. */
     907         381 :   int err = fd_executor_verify_transaction( bank, txn_in, txn_out );
     908         381 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     909           0 :     txn_out->err.is_committable = 0;
     910           0 :     return err;
     911           0 :   }
     912             : 
     913             :   /* Set up the transaction accounts and other txn ctx metadata. This
     914             :      also resolves ALUT-referenced account keys and validates account
     915             :      locks before accounts are acquired.  Bundle transactions bind to
     916             :      the pool acquired and validated once for the whole bundle by
     917             :      fd_runtime_prepare_bundle_accounts() and never acquire on a
     918             :      per-transaction basis.  However, the implicit programdata state
     919             :      must be re-derived here per-transaction, and not once up front.  An
     920             :      earlier bundle transaction can deploy a program, which changes
     921             :      whether a pool account parses as a program account, and therefore
     922             :      which PD account is being implicitly accounted for. */
     923         381 :   if( FD_UNLIKELY( txn_in->bundle.is_bundle ) ) {
     924          99 :     fd_executor_setup_accounts_for_txn_bundle( runtime, txn_in, txn_out );
     925          99 :     err = fd_runtime_setup_bundle_executables( runtime, bank, txn_out );
     926         282 :   } else {
     927         282 :     err = fd_executor_setup_accounts_for_txn( runtime, bank, txn_in, txn_out );
     928         282 :   }
     929         381 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     930           0 :     txn_out->err.is_committable = 0;
     931           0 :     return err;
     932           0 :   }
     933             : 
     934         381 :   txn_out->details.check_start_ticks = fd_tickcount();
     935             : 
     936             :   /* load_and_execute_transactions() -> check_transactions()
     937             :      https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/runtime/src/bank.rs#L3667-L3672 */
     938         381 :   err = fd_executor_check_transactions( runtime, bank, txn_in, txn_out );
     939         381 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     940           3 :     txn_out->err.is_committable = 0;
     941           3 :     return err;
     942           3 :   }
     943             : 
     944             :   /* load_and_execute_sanitized_transactions() -> validate_fees() ->
     945             :      validate_transaction_fee_payer()
     946             :      https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/svm/src/transaction_processor.rs#L236-L249 */
     947         378 :   err = fd_executor_validate_transaction_fee_payer( bank, txn_in, txn_out );
     948         378 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     949           0 :     txn_out->err.is_committable = 0;
     950           0 :     return err;
     951           0 :   }
     952             : 
     953             :   /* https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/svm/src/transaction_processor.rs#L284-L296 */
     954         378 :   err = fd_executor_load_transaction_accounts( bank, txn_in, txn_out );
     955         378 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     956             :     /* Regardless of whether transaction accounts were loaded successfully, the transaction is
     957             :        included in the block and transaction fees are collected.
     958             :        https://github.com/anza-xyz/agave/blob/v2.1.6/svm/src/transaction_processor.rs#L341-L357 */
     959          21 :     txn_out->err.is_fees_only = 1;
     960             : 
     961             :     /* If the transaction fails to load, the "rollback" accounts will include one of the following:
     962             :         1. Nonce account only
     963             :         2. Fee payer only
     964             :         3. Nonce account + fee payer
     965             : 
     966             :         Because the cost tracker uses the loaded account data size in block cost calculations, we need to
     967             :         make sure our calculated loaded accounts data size is conformant with Agave's.
     968             :         https://github.com/anza-xyz/agave/blob/v4.1.0-beta.1/svm/src/account_loader.rs#L437-L449
     969             : 
     970             :         These are different depending on if define_ltds_fee_only_semantics is enabled or not.
     971             : 
     972             :         If define_ltds_fee_only_semantics is enabled, we use the accumulated load size so far,
     973             :         clamped to the compute budget requested loaded_accounts_data_size_limit. */
     974          21 :     if( FD_FEATURE_ACTIVE_BANK( bank, define_ltds_fee_only_semantics ) ) {
     975             :       /* https://github.com/anza-xyz/agave/blob/v4.1.0-beta.1/svm/src/account_loader.rs#L495-L501 */
     976           9 :       txn_out->details.loaded_accounts_data_size = fd_ulong_min(
     977           9 :         txn_out->details.loaded_accounts_data_size,
     978           9 :         txn_out->details.compute_budget.loaded_accounts_data_size_limit );
     979          12 :     } else {
     980             :       /* If define_ltds_fee_only_semantics is not enabled, initialize
     981             :          loaded_accounts_data_size with the dlen of the fee payer. */
     982          12 :       txn_out->details.loaded_accounts_data_size = txn_out->accounts.account[ FD_FEE_PAYER_TXN_IDX ]->data_len;
     983             : 
     984             :       /* Special case handling for if a nonce account is present in the transaction. */
     985          12 :       if( txn_out->accounts.nonce_idx_in_txn!=ULONG_MAX ) {
     986             :         /* If the nonce account is not the fee payer, then we separately add the dlen of the nonce account. Otherwise, we would
     987             :             be double counting the dlen of the fee payer. */
     988           6 :         if( txn_out->accounts.nonce_idx_in_txn!=FD_FEE_PAYER_TXN_IDX ) {
     989           3 :           txn_out->details.loaded_accounts_data_size += txn_out->accounts.account[ txn_out->accounts.nonce_idx_in_txn ]->data_len;
     990           3 :         }
     991           6 :       }
     992          12 :     }
     993          21 :   }
     994             : 
     995             :   /*
     996             :      The fee payer and the nonce account will be stored and hashed so
     997             :      long as the transaction landed on chain, or, in Agave terminology,
     998             :      the transaction was processed.
     999             :      https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/account_saver.rs#L72
    1000             : 
    1001             :      A transaction lands on chain in one of two ways:
    1002             :      (1) Passed fee validation and loaded accounts.
    1003             :      (2) Passed fee validation and failed to load accounts and the enable_transaction_loading_failure_fees feature is enabled as per
    1004             :          SIMD-0082 https://github.com/anza-xyz/feature-gate-tracker/issues/52
    1005             : 
    1006             :      So, at this point, the transaction is committable.
    1007             :    */
    1008             : 
    1009         378 :   return err;
    1010         378 : }
    1011             : 
    1012             : /* fd_runtime_lthash_account updates the running lthash of the bank
    1013             :    given an account that might have been updated. */
    1014             : 
    1015             : static void
    1016             : fd_runtime_lthash_account( fd_bank_t *         bank,
    1017             :                            fd_pubkey_t const * pubkey,
    1018             :                            fd_acc_t *          acc,
    1019         375 :                            fd_capture_ctx_t *  capture_ctx ) {
    1020         375 :   if( FD_UNLIKELY( !acc->lamports ) ) {
    1021          24 :     acc->data_len   = 0UL;
    1022          24 :     acc->executable = 0;
    1023          24 :     memset( acc->owner, 0, sizeof(acc->owner) );
    1024          24 :   }
    1025             : 
    1026         375 :   fd_lthash_value_t lthash_prev[1];
    1027         375 :   if( FD_LIKELY( acc->prior_data ) ) {
    1028         360 :     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 );
    1029         360 :   } else {
    1030          15 :     fd_lthash_zero( lthash_prev );
    1031          15 :   }
    1032             : 
    1033         375 :   fd_lthash_value_t lthash_post[1];
    1034         375 :   if( FD_LIKELY( acc->prior_lamports || acc->lamports ) ) {
    1035         375 :     fd_hashes_update_simple( lthash_post, lthash_prev, pubkey->uc, acc->owner, acc->lamports, acc->executable, acc->data, acc->data_len, bank, capture_ctx );
    1036         375 :   }
    1037         375 : }
    1038             : 
    1039             : /* fd_runtime_commit_txn is a helper used by the transaction executor to
    1040             :    finalize account changes back into the database.  It also handles
    1041             :    txncache insertion and updates to the vote/stake cache.  TODO: This
    1042             :    function should probably be moved to fd_executor.c. */
    1043             : 
    1044             : void
    1045             : fd_runtime_commit_txn( fd_runtime_t *      runtime,
    1046             :                        fd_bank_t *         bank,
    1047             :                        fd_txn_in_t const * txn_in,
    1048             :                        fd_txn_out_t *      txn_out,
    1049         231 :                        int                 report_transaction_diffs ) {
    1050         231 :   FD_TEST( txn_out->err.is_committable );
    1051             : 
    1052         231 :   txn_out->details.commit_start_ticks = fd_tickcount();
    1053             : 
    1054         231 :   if( FD_UNLIKELY( !txn_out->err.txn_err ) ) {
    1055         159 :     fd_top_votes_t * top_votes = fd_bank_top_votes_t_2_modify( bank );
    1056        1113 :     for( ushort i=0; i<txn_out->accounts.cnt; i++ ) {
    1057             :       /* We are only interested in saving writable accounts and the fee
    1058             :          payer account. */
    1059         954 :       if( FD_UNLIKELY( !txn_out->accounts.is_writable[ i ] ) ) continue;
    1060             : 
    1061         357 :       fd_pubkey_t const * pubkey = &txn_out->accounts.keys[ i ];
    1062             : 
    1063             :       /* Only the txn that owns the accdb reference commits the account
    1064             :          state.  In a bundle, an account is owned by its last writable
    1065             :          user (account_acquired==1); every other txn referencing it has
    1066             :          account_acquired==0 and skips here, so the final shared state is
    1067             :          lthashed exactly once and not double-counted.  stake_update/
    1068             :          vote_update are recomputed from the final state and were moved
    1069             :          onto this owner, so they also fire here exactly once. */
    1070         357 :       if( FD_UNLIKELY( !txn_out->accounts.account_acquired[ i ] ) ) continue;
    1071             : 
    1072         303 :       fd_acc_t * account = txn_out->accounts.account[ i ];
    1073         303 :       account->commit = 1;
    1074             : 
    1075         303 :       if( FD_UNLIKELY( txn_out->accounts.stake_update[ i ] ) ) {
    1076           6 :         fd_stakes_update_stake_delegation( pubkey, account, bank );
    1077           6 :       }
    1078             : 
    1079         303 :       if( txn_out->accounts.vote_update[i] ) {
    1080          60 :         fd_vote_block_timestamp_t last_vote;
    1081          60 :         if( FD_UNLIKELY( !account->lamports ||
    1082          60 :                          !fd_vsv_is_correct_size_owner_and_init( account->owner, account->data, account->data_len ) ||
    1083          60 :                          fd_vote_account_last_timestamp( account->data, account->data_len, &last_vote ) ) ) {
    1084           0 :           fd_top_votes_invalidate( top_votes, pubkey );
    1085          60 :         } else {
    1086          60 :           fd_top_votes_update( top_votes, pubkey, last_vote.slot, last_vote.timestamp );
    1087          60 :         }
    1088          60 :       }
    1089             : 
    1090         303 :       fd_runtime_lthash_account( bank, pubkey, account, runtime->log.capture_ctx );
    1091         303 :     }
    1092             : 
    1093             :     /* Atomically add all accumulated tips to the bank once after
    1094             :        processing all accounts. */
    1095         159 :     if( FD_UNLIKELY( txn_out->details.tips ) ) FD_ATOMIC_FETCH_AND_ADD( &bank->f.tips, txn_out->details.tips );
    1096         159 :   }
    1097             : 
    1098         231 :   txn_out->details.commit_index_in_slot = FD_ATOMIC_FETCH_AND_ADD( &bank->f.txn_count, 1UL );
    1099         231 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.execution_fees,  txn_out->details.execution_fee );
    1100         231 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.priority_fees,   txn_out->details.priority_fee );
    1101         231 :   FD_ATOMIC_FETCH_AND_ADD( &bank->f.signature_count, txn_out->details.signature_count );
    1102             : 
    1103         231 :   if( FD_LIKELY( !txn_out->details.is_simple_vote ) ) {
    1104         156 :     FD_ATOMIC_FETCH_AND_ADD( &bank->f.nonvote_txn_count, 1 );
    1105         156 :     if( FD_UNLIKELY( txn_out->err.exec_err ) ) FD_ATOMIC_FETCH_AND_ADD( &bank->f.nonvote_failed_txn_count, 1 );
    1106         156 :   }
    1107             : 
    1108         231 :   if( FD_UNLIKELY( txn_out->err.exec_err ) ) FD_ATOMIC_FETCH_AND_ADD( &bank->f.failed_txn_count, 1 );
    1109         231 :   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 );
    1110             : 
    1111         231 :   fd_cost_tracker_t * cost_tracker = fd_bank_cost_tracker_modify( bank );
    1112         231 :   int res = fd_cost_tracker_try_add_cost( cost_tracker, txn_out );
    1113         231 :   if( FD_UNLIKELY( res!=FD_COST_TRACKER_SUCCESS ) ) {
    1114           0 :     FD_LOG_DEBUG(( "fd_runtime_commit_txn: transaction failed to fit into block %d", res ));
    1115           0 :     txn_out->err.is_committable = 0;
    1116           0 :     txn_out->err.txn_err        = fd_cost_tracker_err_to_runtime_err( res );
    1117           0 :   }
    1118             : 
    1119         231 :   if( FD_LIKELY( runtime->status_cache && txn_out->accounts.nonce_idx_in_txn==ULONG_MAX && txn_out->err.is_committable ) ) {
    1120             :     /* In Agave, durable nonce transactions are inserted to the status
    1121             :        cache the same as any others, but this is only to serve RPC
    1122             :        requests, they do not need to be in there for correctness as the
    1123             :        nonce mechanism itself prevents double spend.  We skip this logic
    1124             :        entirely to simplify and improve performance of the txn cache.
    1125             : 
    1126             :        Cost tracker rejected transactions are also skipped: the block
    1127             :        is already dead, and skipping keeps the per slot insert count
    1128             :        bounded by the cost model, which sizes the txn cache. */
    1129         225 :     fd_txncache_insert( runtime->status_cache, bank->txncache_fork_id, txn_out->details.blockhash.uc, txn_out->details.blake_txn_msg_hash.uc );
    1130         225 :   }
    1131             : 
    1132         231 :   if( FD_UNLIKELY( txn_out->err.txn_err ) ) {
    1133             :     /* With nonce account rollbacks, there are three cases:
    1134             : 
    1135             :        1. No nonce account in the transaction
    1136             :        2. Nonce account is the fee payer
    1137             :        3. Nonce account is not the fee payer
    1138             : 
    1139             :        We should always rollback the nonce account first.  Note that the
    1140             :        nonce account may be the fee payer (case 2). */
    1141          72 :     if( FD_UNLIKELY( txn_out->accounts.nonce_idx_in_txn!=ULONG_MAX ) ) {
    1142           0 :       fd_acc_t * nonce_account = txn_out->accounts.account[ txn_out->accounts.nonce_idx_in_txn ];
    1143           0 :       fd_memcpy( nonce_account->data, txn_out->accounts.nonce_rollback_data, txn_out->accounts.nonce_rollback_data_len );
    1144           0 :       nonce_account->data_len = txn_out->accounts.nonce_rollback_data_len;
    1145           0 :       fd_memcpy( nonce_account->owner, nonce_account->prior_owner, 32UL );
    1146           0 :       if( FD_UNLIKELY( txn_out->accounts.nonce_idx_in_txn==FD_FEE_PAYER_TXN_IDX ) ) {
    1147           0 :         nonce_account->lamports = txn_out->accounts.fee_payer_rollback_lamports;
    1148           0 :       } else {
    1149           0 :         nonce_account->lamports = nonce_account->prior_lamports;
    1150           0 :       }
    1151           0 :       nonce_account->executable = nonce_account->prior_executable;
    1152           0 :       nonce_account->commit = 1;
    1153           0 :       fd_runtime_lthash_account( bank, &txn_out->accounts.keys[ txn_out->accounts.nonce_idx_in_txn ], nonce_account, runtime->log.capture_ctx );
    1154           0 :     }
    1155             : 
    1156             :     /* Now, we must only save the fee payer if the nonce account was not
    1157             :        the fee payer (because that was already saved above). */
    1158          72 :     if( FD_LIKELY( txn_out->accounts.nonce_idx_in_txn!=FD_FEE_PAYER_TXN_IDX ) ) {
    1159          72 :       fd_acc_t * fee_payer_account = txn_out->accounts.account[ FD_FEE_PAYER_TXN_IDX ];
    1160          72 :       fd_memcpy( fee_payer_account->data, fee_payer_account->prior_data, fee_payer_account->prior_data_len );
    1161          72 :       fee_payer_account->data_len = fee_payer_account->prior_data_len;
    1162          72 :       fd_memcpy( fee_payer_account->owner, fee_payer_account->prior_owner, 32UL );
    1163          72 :       fee_payer_account->lamports = txn_out->accounts.fee_payer_rollback_lamports;
    1164          72 :       fee_payer_account->executable = fee_payer_account->prior_executable;
    1165             : 
    1166          72 :       fee_payer_account->commit = 1;
    1167          72 :       fd_runtime_lthash_account( bank, &txn_out->accounts.keys[ FD_FEE_PAYER_TXN_IDX ], fee_payer_account, runtime->log.capture_ctx );
    1168          72 :     }
    1169          72 :   }
    1170             : 
    1171         231 :   if( FD_UNLIKELY( report_transaction_diffs ) ) fd_event_runtime_txn_emit( txn_in, txn_out, bank );
    1172             : 
    1173         231 :   if( FD_LIKELY( !txn_out->accounts.is_bundle ) ) {
    1174         156 :     fd_accdb_release_ab( runtime->accdb,
    1175         156 :                          txn_out->accounts.cnt, runtime->accounts.account,
    1176         156 :                          runtime->accounts.executable_cnt, runtime->accounts.executable );
    1177         156 :     runtime->accounts.executable_cnt = 0UL;
    1178         156 :   }
    1179         231 : }
    1180             : 
    1181             : void
    1182             : fd_runtime_cancel_txn( fd_runtime_t *      runtime,
    1183             :                        fd_bank_t *         bank,
    1184             :                        fd_txn_in_t const * txn_in,
    1185             :                        fd_txn_out_t *      txn_out,
    1186           9 :                        int                 report_transaction_diffs ) {
    1187           9 :   FD_TEST( !txn_out->err.is_committable );
    1188           9 :   if( FD_UNLIKELY( !txn_out->accounts.is_setup ) ) return;
    1189             : 
    1190           9 :   if( FD_UNLIKELY( report_transaction_diffs ) ) fd_event_runtime_txn_emit( txn_in, txn_out, bank );
    1191             : 
    1192           9 :   fd_accdb_release_ab( runtime->accdb,
    1193           9 :                        txn_out->accounts.cnt, runtime->accounts.account,
    1194           9 :                        runtime->accounts.executable_cnt, runtime->accounts.executable );
    1195           9 :   runtime->accounts.executable_cnt = 0UL;
    1196           9 : }
    1197             : 
    1198             : void
    1199          48 : fd_runtime_fini_bundle( fd_runtime_t * runtime ) {
    1200          48 :   fd_accdb_release_ab( runtime->accdb,
    1201          48 :     runtime->accounts.account_cnt, runtime->accounts.account,
    1202          48 :     runtime->accounts.executable_cnt, runtime->accounts.executable );
    1203          48 :   runtime->accounts.account_cnt    = 0UL;
    1204          48 :   runtime->accounts.executable_cnt = 0UL;
    1205          48 : }
    1206             : 
    1207             : static inline void
    1208         381 : fd_runtime_reset_runtime( fd_runtime_t * runtime ) {
    1209         381 :   runtime->instr.stack_sz     = 0;
    1210         381 :   runtime->instr.trace_length = 0UL;
    1211         381 : }
    1212             : 
    1213             : static inline void
    1214             : fd_runtime_new_txn_out( fd_txn_in_t const * txn_in,
    1215         381 :                         fd_txn_out_t *      txn_out ) {
    1216         381 :   txn_out->details.load_start_ticks   = fd_tickcount();
    1217         381 :   txn_out->details.check_start_ticks  = LONG_MAX;
    1218         381 :   txn_out->details.exec_start_ticks   = LONG_MAX;
    1219         381 :   txn_out->details.commit_start_ticks = LONG_MAX;
    1220             : 
    1221         381 :   fd_compute_budget_details_new( &txn_out->details.compute_budget );
    1222             : 
    1223         381 :   txn_out->details.loaded_accounts_data_size = 0UL;
    1224         381 :   txn_out->details.accounts_resize_delta     = 0L;
    1225             : 
    1226         381 :   txn_out->details.return_data.len = 0UL;
    1227         381 :   memset( txn_out->details.return_data.program_id.key, 0, sizeof(fd_pubkey_t) );
    1228             : 
    1229         381 :   txn_out->details.tips            = 0UL;
    1230         381 :   txn_out->details.execution_fee   = 0UL;
    1231         381 :   txn_out->details.priority_fee    = 0UL;
    1232         381 :   txn_out->details.signature_count = 0UL;
    1233         381 :   fd_memset( txn_out->details.signature.uc, 0, sizeof(fd_signature_t) );
    1234             : 
    1235         381 :   txn_out->details.signature_count = TXN( txn_in->txn )->signature_cnt;
    1236         381 :   if( FD_LIKELY( txn_out->details.signature_count ) ) {
    1237         381 :     fd_memcpy( txn_out->details.signature.uc,
    1238         381 :                (uchar const *)txn_in->txn->payload + TXN( txn_in->txn )->signature_off,
    1239         381 :                sizeof(fd_signature_t) );
    1240         381 :   }
    1241         381 :   txn_out->details.is_simple_vote  = fd_txn_is_simple_vote_transaction( TXN( txn_in->txn ), txn_in->txn->payload );
    1242             : 
    1243         381 :   fd_hash_t * blockhash = (fd_hash_t *)((uchar *)txn_in->txn->payload + TXN( txn_in->txn )->recent_blockhash_off);
    1244         381 :   memcpy( txn_out->details.blockhash.uc, blockhash->hash, sizeof(fd_hash_t) );
    1245             : 
    1246         381 :   txn_out->accounts.is_setup           = 0;
    1247         381 :   txn_out->accounts.is_bundle          = txn_in->bundle.is_bundle;
    1248         381 :   if( FD_LIKELY( !txn_in->bundle.is_bundle ) ) txn_out->accounts.cnt= 0UL;
    1249         381 :   memset( txn_out->accounts.is_writable, 0, sizeof(txn_out->accounts.is_writable) );
    1250         381 :   memset( txn_out->accounts.account_acquired, 0, sizeof(txn_out->accounts.account_acquired) );
    1251         381 :   memset( txn_out->accounts.stake_update, 0, sizeof(txn_out->accounts.stake_update) );
    1252         381 :   memset( txn_out->accounts.vote_update, 0, sizeof(txn_out->accounts.vote_update) );
    1253         381 :   memset( txn_out->accounts.new_vote, 0, sizeof(txn_out->accounts.new_vote) );
    1254         381 :   memset( txn_out->accounts.rm_vote, 0, sizeof(txn_out->accounts.rm_vote) );
    1255         381 :   txn_out->accounts.nonce_idx_in_txn            = ULONG_MAX;
    1256             : 
    1257             :   /* For bundle transactions the resolved key list is bound once up
    1258             :      front by fd_runtime_prepare_bundle_accounts() before this runs per
    1259             :      transaction, so preserve it here.  The executable list is rebuilt
    1260             :      per transaction by fd_runtime_setup_bundle_executables(), which
    1261             :      sets every element it reports, so it needs no reset either.  For a
    1262             :      non-bundle transaction the executable list is built in
    1263             :      fd_executor_setup_accounts_for_txn(), which only writes the entries
    1264             :      it acquires, so reset it here.  executable_cur_len needs no reset:
    1265             :      it is written per-element for every i in [0, executable_cnt) before
    1266             :      any read (its sentinel is ULONG_MAX, so a zero memset would be
    1267             :      wrong anyway). */
    1268         381 :   if( FD_LIKELY( !txn_in->bundle.is_bundle ) ) {
    1269         282 :     memset( txn_out->accounts.executable_from_parent, 0, sizeof(txn_out->accounts.executable_from_parent) );
    1270         282 :     memset( txn_out->accounts.executable_pd_write,    0, sizeof(txn_out->accounts.executable_pd_write) );
    1271         282 :     txn_out->accounts.executable_cnt         = 0UL;
    1272         282 :     txn_out->accounts.executable_skipped_cnt = 0;
    1273         282 :   }
    1274         381 :   txn_out->accounts.nonce_rollback_data_len     = 0UL;
    1275         381 :   txn_out->accounts.fee_payer_rollback_lamports = 0UL;
    1276             : 
    1277         381 :   txn_out->err.is_committable = 1;
    1278         381 :   txn_out->err.is_fees_only   = 0;
    1279         381 :   txn_out->err.txn_err        = FD_RUNTIME_EXECUTE_SUCCESS;
    1280         381 :   txn_out->err.exec_err       = FD_EXECUTOR_INSTR_SUCCESS;
    1281         381 :   txn_out->err.exec_err_kind  = FD_EXECUTOR_ERR_KIND_NONE;
    1282         381 :   txn_out->err.exec_err_idx   = UINT_MAX;
    1283         381 :   txn_out->err.custom_err     = 0;
    1284         381 : }
    1285             : 
    1286             : void
    1287             : fd_runtime_prepare_and_execute_txn( fd_runtime_t *      runtime,
    1288             :                                     fd_bank_t *         bank,
    1289             :                                     fd_txn_in_t const * txn_in,
    1290         381 :                                     fd_txn_out_t *      txn_out ) {
    1291         381 :   fd_runtime_reset_runtime( runtime );
    1292             : 
    1293         381 :   fd_runtime_new_txn_out( txn_in, txn_out );
    1294             : 
    1295         381 :   uchar dump_txn = !!(runtime->log.dump_proto_ctx &&
    1296         381 :                       bank->f.slot >= runtime->log.dump_proto_ctx->dump_proto_start_slot &&
    1297         381 :                       runtime->log.dump_proto_ctx->dump_txn_to_pb);
    1298             : 
    1299             :   /* Phase 1: Capture TxnContext before execution. */
    1300         381 :   if( FD_UNLIKELY( dump_txn ) ) {
    1301           0 :     if( runtime->log.txn_dump_ctx ) {
    1302           0 :       fd_dump_txn_context_to_protobuf( runtime->log.txn_dump_ctx, runtime, bank, txn_in, txn_out );
    1303           0 :     } else {
    1304           0 :       fd_dump_txn_to_protobuf( runtime, bank, txn_in, txn_out );
    1305           0 :     }
    1306           0 :   }
    1307             : 
    1308             :   /* Transaction sanitization.  If a transaction can't be committed or is
    1309             :      fees-only, we return early. */
    1310         381 :   txn_out->err.txn_err = fd_runtime_pre_execute_check( runtime, bank, txn_in, txn_out );
    1311         381 :   ulong cu_before = txn_out->details.compute_budget.compute_meter;
    1312             : 
    1313             :   /* Execute the transaction if eligible to do so. */
    1314         381 :   if( FD_LIKELY( txn_out->err.is_committable ) ) {
    1315         378 :     if( FD_LIKELY( !txn_out->err.is_fees_only ) ) {
    1316         357 :       txn_out->details.exec_start_ticks = fd_tickcount();
    1317         357 :       txn_out->err.txn_err = fd_execute_txn( runtime, bank, txn_in, txn_out );
    1318         357 :     }
    1319         378 :     fd_cost_tracker_calculate_cost( bank, txn_in, txn_out );
    1320         378 :   }
    1321         381 :   ulong cu_after = txn_out->details.compute_budget.compute_meter;
    1322         381 :   runtime->metrics.cu_cum += fd_ulong_sat_sub( cu_before, cu_after );
    1323             : 
    1324             :   /* Phase 2: Capture TxnResult after execution and write to disk. */
    1325         381 :   if( FD_UNLIKELY( dump_txn && runtime->log.txn_dump_ctx ) ) {
    1326           0 :     fd_dump_txn_result_to_protobuf( runtime->log.txn_dump_ctx, txn_in, txn_out, txn_out->err.txn_err );
    1327           0 :     fd_dump_txn_fixture_to_file( runtime->log.txn_dump_ctx, runtime->log.dump_proto_ctx, txn_in );
    1328           0 :   }
    1329         381 : }
    1330             : 
    1331             : /* fd_executor_txn_verify and fd_runtime_pre_execute_check are responsible
    1332             :    for the bulk of the pre-transaction execution checks in the runtime.
    1333             :    They aim to preserve the ordering present in the Agave client to match
    1334             :    parity in terms of error codes. Sigverify is kept separate from the rest
    1335             :    of the transaction checks for fuzzing convenience.
    1336             : 
    1337             :    For reference this is the general code path which contains all relevant
    1338             :    pre-transactions checks in the v2.0.x Agave client from upstream
    1339             :    to downstream is as follows:
    1340             : 
    1341             :    confirm_slot_entries() which calls verify_ticks() and
    1342             :    verify_transaction(). verify_transaction() calls verify_and_hash_message()
    1343             :    and verify_precompiles() which parallels fd_executor_txn_verify() and
    1344             :    fd_executor_verify_transaction().
    1345             : 
    1346             :    process_entries() contains a duplicate account check which is part of
    1347             :    agave account lock acquiring. This is checked inline in
    1348             :    fd_runtime_pre_execute_check().
    1349             : 
    1350             :    load_and_execute_transactions() contains the function check_transactions().
    1351             :    This contains check_age() and check_status_cache() which is paralleled by
    1352             :    fd_executor_check_transaction_age_and_compute_budget_limits() and
    1353             :    fd_executor_check_status_cache() respectively.
    1354             : 
    1355             :    load_and_execute_sanitized_transactions() contains validate_fees()
    1356             :    which is responsible for executing the compute budget instructions,
    1357             :    validating the fee payer and collecting the fee. This is mirrored in
    1358             :    firedancer with fd_executor_compute_budget_program_execute_instructions()
    1359             :    and fd_executor_collect_fees(). load_and_execute_sanitized_transactions()
    1360             :    also checks the total data size of the accounts in load_accounts() and
    1361             :    validates the program accounts in load_transaction_accounts(). This
    1362             :    is paralled by fd_executor_load_transaction_accounts(). */
    1363             : 
    1364             : 
    1365             : /******************************************************************************/
    1366             : /* Genesis                                                                    */
    1367             : /*******************************************************************************/
    1368             : 
    1369             : static void
    1370             : fd_runtime_genesis_init_program( fd_bank_t *        bank,
    1371             :                                  fd_accdb_t *       accdb,
    1372           0 :                                  fd_capture_ctx_t * capture_ctx ) {
    1373             : 
    1374           0 :   fd_sysvar_clock_init( bank, accdb, capture_ctx );
    1375           0 :   fd_sysvar_rent_init( bank, accdb, capture_ctx );
    1376             : 
    1377           0 :   fd_sysvar_slot_history_init( bank, accdb, capture_ctx );
    1378           0 :   fd_sysvar_epoch_schedule_init( bank, accdb, capture_ctx );
    1379           0 :   fd_sysvar_recent_hashes_init( bank, accdb, capture_ctx );
    1380           0 :   fd_sysvar_stake_history_init( bank, accdb, capture_ctx );
    1381           0 :   fd_sysvar_last_restart_slot_init( bank, accdb, capture_ctx );
    1382             : 
    1383           0 :   fd_builtin_programs_init( bank, accdb, capture_ctx );
    1384           0 : }
    1385             : 
    1386             : static void
    1387             : fd_runtime_init_bank_from_genesis( fd_banks_t *         banks,
    1388             :                                    fd_bank_t *          bank,
    1389             :                                    fd_runtime_stack_t * runtime_stack,
    1390             :                                    fd_accdb_t *         accdb,
    1391             :                                    fd_genesis_t const * genesis,
    1392             :                                    uchar const *        genesis_blob,
    1393           0 :                                    fd_hash_t const *    genesis_hash ) {
    1394             : 
    1395           0 :   bank->f.parent_slot = ULONG_MAX;
    1396           0 :   bank->f.poh = *genesis_hash;
    1397             : 
    1398           0 :   fd_hash_t * bank_hash = &bank->f.bank_hash;
    1399           0 :   memset( bank_hash->hash, 0, FD_SHA256_HASH_SZ );
    1400             : 
    1401           0 :   uint128 target_tick_duration = (uint128)genesis->poh.tick_duration_secs * 1000000000UL + (uint128)genesis->poh.tick_duration_ns;
    1402             : 
    1403           0 :   fd_epoch_schedule_t * epoch_schedule = &bank->f.epoch_schedule;
    1404           0 :   epoch_schedule->leader_schedule_slot_offset = genesis->epoch_schedule.leader_schedule_slot_offset;
    1405           0 :   epoch_schedule->warmup                      = genesis->epoch_schedule.warmup;
    1406           0 :   epoch_schedule->first_normal_epoch          = genesis->epoch_schedule.first_normal_epoch;
    1407           0 :   epoch_schedule->first_normal_slot           = genesis->epoch_schedule.first_normal_slot;
    1408           0 :   epoch_schedule->slots_per_epoch             = genesis->epoch_schedule.slots_per_epoch;
    1409             : 
    1410           0 :   fd_rent_t * rent = &bank->f.rent;
    1411           0 :   rent->lamports_per_uint8_year = genesis->rent.lamports_per_uint8_year;
    1412           0 :   rent->exemption_threshold     = genesis->rent.exemption_threshold;
    1413           0 :   rent->burn_percent            = genesis->rent.burn_percent;
    1414             : 
    1415           0 :   fd_inflation_t * inflation = &bank->f.inflation;
    1416           0 :   inflation->initial         = genesis->inflation.initial;
    1417           0 :   inflation->terminal        = genesis->inflation.terminal;
    1418           0 :   inflation->taper           = genesis->inflation.taper;
    1419           0 :   inflation->foundation      = genesis->inflation.foundation;
    1420           0 :   inflation->foundation_term = genesis->inflation.foundation_term;
    1421           0 :   inflation->unused          = 0.0;
    1422             : 
    1423           0 :   bank->f.block_height = 0UL;
    1424             : 
    1425           0 :   {
    1426             :     /* FIXME Why is there a previous blockhash at genesis?  Why is the
    1427             :              last_hash field an option type in Agave, if even the first
    1428             :              real block has a previous blockhash? */
    1429           0 :     fd_blockhashes_t *    bhq  = fd_blockhashes_init( &bank->f.block_hash_queue, 0UL );
    1430           0 :     fd_blockhash_info_t * info = fd_blockhashes_push_new( bhq, genesis_hash );
    1431           0 :     info->lamports_per_signature = 0UL;
    1432           0 :   }
    1433             : 
    1434           0 :   fd_fee_rate_governor_t * fee_rate_governor = &bank->f.fee_rate_governor;
    1435           0 :   fee_rate_governor->target_lamports_per_signature = genesis->fee_rate_governor.target_lamports_per_signature;
    1436           0 :   fee_rate_governor->target_signatures_per_slot    = genesis->fee_rate_governor.target_signatures_per_slot;
    1437           0 :   fee_rate_governor->min_lamports_per_signature    = genesis->fee_rate_governor.min_lamports_per_signature;
    1438           0 :   fee_rate_governor->max_lamports_per_signature    = genesis->fee_rate_governor.max_lamports_per_signature;
    1439           0 :   fee_rate_governor->burn_percent                  = genesis->fee_rate_governor.burn_percent;
    1440             : 
    1441           0 :   bank->f.max_tick_height                  = genesis->poh.ticks_per_slot * (bank->f.slot + 1);
    1442           0 :   bank->f.slot_params                      = FD_SLOT_PARAMS_400MS;
    1443           0 :   bank->f.slot_params.ns_per_slot          = (ulong)( target_tick_duration * genesis->poh.ticks_per_slot );
    1444           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 );
    1445           0 :   bank->f.slot_params.slots_per_year       = SECONDS_PER_YEAR * (1000000000.0 / (double)target_tick_duration) / (double)genesis->poh.ticks_per_slot;
    1446           0 :   bank->f.slot_params.hashes_per_tick      = genesis->poh.hashes_per_tick;
    1447           0 :   bank->f.slot_params_default              = bank->f.slot_params;
    1448             : 
    1449           0 :   bank->f.ticks_per_slot = genesis->poh.ticks_per_slot;
    1450           0 :   bank->f.genesis_creation_time = genesis->creation_time;
    1451             : 
    1452           0 :   bank->f.signature_count = 0UL;
    1453             : 
    1454             :   /* Derive epoch stakes */
    1455             : 
    1456           0 :   fd_stake_delegations_t * stake_delegations = fd_banks_stake_delegations_root_query( banks );
    1457           0 :   if( FD_UNLIKELY( !stake_delegations ) ) {
    1458           0 :     FD_LOG_CRIT(( "Failed to join and new a stake delegations" ));
    1459           0 :   }
    1460             : 
    1461           0 :   ulong capitalization = 0UL;
    1462             : 
    1463           0 :   fd_feature_snoop_t feature_snoop[1];
    1464           0 :   fd_memset( feature_snoop, 0, sizeof(feature_snoop) );
    1465             : 
    1466           0 :   for( ulong i=0UL; i<genesis->account_cnt; i++ ) {
    1467           0 :     fd_genesis_account_t account[1];
    1468           0 :     fd_genesis_account( genesis, genesis_blob, account, i );
    1469             : 
    1470           0 :     capitalization = fd_ulong_sat_add( capitalization, account->lamports );
    1471             : 
    1472           0 :     uchar const * acc_data = account->data;
    1473             : 
    1474           0 :     if( !memcmp( account->owner.uc, fd_solana_stake_program_id.key, sizeof(fd_pubkey_t) ) ) {
    1475             :       /* If an account is a stake account, then it must be added to the
    1476             :          stake delegations cache.  Like Agave, membership is decided by
    1477             :          the variant alone: a delegation of zero is still a delegation. */
    1478           0 :       fd_stake_state_t const * stake_state = fd_stake_state_view( acc_data, account->data_len );
    1479           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 )); }
    1480           0 :       if( stake_state->stake_type!=FD_STAKE_STATE_STAKE ) continue;
    1481             : 
    1482           0 :       fd_stake_delegations_root_update(
    1483           0 :           stake_delegations,
    1484           0 :           &account->pubkey,
    1485           0 :           &stake_state->stake.stake.delegation.voter_pubkey,
    1486           0 :           stake_state->stake.stake.delegation.stake,
    1487           0 :           stake_state->stake.stake.delegation.activation_epoch,
    1488           0 :           stake_state->stake.stake.delegation.deactivation_epoch,
    1489           0 :           stake_state->stake.stake.credits_observed,
    1490           0 :           account->lamports,
    1491           0 :           (uint)account->data_len,
    1492           0 :           FD_STAKE_DELEGATIONS_WARMUP_COOLDOWN_RATE_ENUM_025 /* genesis is epoch 0, always 0.25 */ );
    1493             : 
    1494           0 :     } else if( !memcmp( account->owner.uc, fd_solana_feature_program_id.key, sizeof(fd_pubkey_t) ) ) {
    1495           0 :       fd_feature_snoop_account( feature_snoop, &account->pubkey, account->lamports,
    1496           0 :                                  account->owner.uc, acc_data, account->data_len );
    1497           0 :     }
    1498           0 :   }
    1499             : 
    1500           0 :   fd_feature_snoop_finalize( &bank->f.features, bank->f.slot, &bank->f.epoch_schedule, feature_snoop );
    1501             : 
    1502             :   /* fd_refresh_vote_accounts is responsible for updating the vote
    1503             :      states with the total amount of active delegated stake.  It does
    1504             :      this by iterating over all active stake delegations and summing up
    1505             :      the amount of stake that is delegated to each vote account. */
    1506           0 :   ulong new_rate_activation_epoch = 0UL;
    1507             : 
    1508           0 :   {
    1509             :     /* Snapshot the stake history sysvar into a local buffer and release
    1510             :        the accdb bracket before calling fd_refresh_vote_accounts, which
    1511             :        performs its own accdb acquires.  fd_sysvar_stake_history_view
    1512             :        aliases the source bytes, so the bracket cannot be held open
    1513             :        across an inner acquire. */
    1514           0 :     uchar                stake_history_data[ FD_SYSVAR_STAKE_HISTORY_BINCODE_SZ ];
    1515           0 :     fd_stake_history_t   stake_history_[1];
    1516           0 :     fd_stake_history_t * stake_history = NULL;
    1517           0 :     fd_acc_t ro = fd_accdb_read_one( accdb, bank->accdb_fork_id, fd_sysvar_stake_history_id.uc );
    1518           0 :     if( FD_LIKELY( ro.lamports ) ) {
    1519           0 :       ulong copy_sz = fd_ulong_min( ro.data_len, FD_SYSVAR_STAKE_HISTORY_BINCODE_SZ );
    1520           0 :       fd_memcpy( stake_history_data, ro.data, copy_sz );
    1521           0 :       fd_accdb_unread_one( accdb, &ro );
    1522           0 :       stake_history = fd_sysvar_stake_history_view( stake_history_, stake_history_data, copy_sz );
    1523           0 :     } else {
    1524           0 :       fd_accdb_unread_one( accdb, &ro );
    1525           0 :     }
    1526             : 
    1527           0 :     fd_refresh_vote_accounts( bank, accdb, runtime_stack, stake_delegations, stake_history, &new_rate_activation_epoch );
    1528           0 :   }
    1529             : 
    1530             :   /* At genesis (epoch 0) there is no previous epoch, so the t-2 set
    1531             :      should equal the genesis staked set. */
    1532             : 
    1533           0 :   {
    1534           0 :     fd_top_votes_t * top_votes_t_1 = fd_bank_top_votes_t_1_modify( bank );
    1535           0 :     fd_top_votes_t * top_votes_t_2 = fd_bank_top_votes_t_2_modify( bank );
    1536           0 :     fd_memcpy( top_votes_t_2, top_votes_t_1, FD_TOP_VOTES_MAX_FOOTPRINT );
    1537           0 :   }
    1538             : 
    1539           0 :   bank->f.epoch = 0UL;
    1540           0 :   bank->f.capitalization = capitalization;
    1541           0 : }
    1542             : 
    1543             : static int
    1544             : fd_runtime_process_genesis_block( fd_bank_t *          bank,
    1545             :                                   fd_accdb_t *         accdb,
    1546             :                                   fd_capture_ctx_t *   capture_ctx,
    1547           0 :                                   fd_runtime_stack_t * runtime_stack ) {
    1548           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 );
    1549             : 
    1550           0 :   bank->f.execution_fees = 0UL;
    1551           0 :   bank->f.priority_fees = 0UL;
    1552           0 :   bank->f.signature_count = 0UL;
    1553           0 :   bank->f.txn_count = 0UL;
    1554           0 :   bank->f.failed_txn_count = 0UL;
    1555           0 :   bank->f.nonvote_failed_txn_count = 0UL;
    1556           0 :   bank->f.total_compute_units_used = 0UL;
    1557             : 
    1558           0 :   fd_runtime_genesis_init_program( bank, accdb, capture_ctx );
    1559           0 :   fd_sysvar_slot_history_update( bank, accdb, capture_ctx );
    1560           0 :   fd_runtime_update_leaders( bank, runtime_stack );
    1561           0 :   fd_runtime_freeze( bank, accdb, capture_ctx );
    1562             : 
    1563           0 :   fd_hash_t const * prev_bank_hash = &bank->f.bank_hash;
    1564             : 
    1565           0 :   fd_lthash_value_t const * lthash = fd_bank_lthash_locking_query( bank );
    1566             : 
    1567           0 :   fd_hash_t * bank_hash = &bank->f.bank_hash;
    1568           0 :   fd_hashes_hash_bank( lthash, prev_bank_hash, (fd_hash_t *)bank->f.poh.hash, 0UL, bank_hash );
    1569             : 
    1570           0 :   fd_bank_lthash_end_locking_query( bank );
    1571             : 
    1572           0 :   return FD_RUNTIME_EXECUTE_SUCCESS;
    1573           0 : }
    1574             : 
    1575             : void
    1576             : fd_runtime_read_genesis( fd_banks_t *              banks,
    1577             :                          fd_bank_t *               bank,
    1578             :                          fd_accdb_t *              accdb,
    1579             :                          fd_capture_ctx_t *        capture_ctx,
    1580             :                          fd_hash_t const *         genesis_hash,
    1581             :                          fd_lthash_value_t const * genesis_lthash,
    1582             :                          fd_genesis_t const *      genesis,
    1583             :                          uchar const *             genesis_blob,
    1584           0 :                          fd_runtime_stack_t *      runtime_stack ) {
    1585           0 :   fd_lthash_value_t * lthash = fd_bank_lthash_locking_modify( bank );
    1586           0 :   *lthash = *genesis_lthash;
    1587           0 :   fd_bank_lthash_end_locking_modify( bank );
    1588             : 
    1589             :   /* Once the accounts have been loaded from the genesis config into
    1590             :      the accounts db, we can initialize the bank state. This involves
    1591             :      setting some fields, and notably setting up the vote and stake
    1592             :      caches which are used for leader scheduling/rewards. */
    1593             : 
    1594           0 :   fd_runtime_init_bank_from_genesis( banks, bank, runtime_stack, accdb, genesis, genesis_blob, genesis_hash );
    1595             : 
    1596             :   /* Write the native programs to the accounts db. */
    1597             : 
    1598           0 :   for( ulong i=0UL; i<genesis->builtin_cnt; i++ ) {
    1599           0 :     fd_genesis_builtin_t builtin[1];
    1600           0 :     fd_genesis_builtin( genesis, genesis_blob, builtin, i );
    1601           0 :     fd_write_builtin_account( bank, accdb, capture_ctx, builtin->pubkey, builtin->data, builtin->data_len );
    1602           0 :   }
    1603             : 
    1604             :   /* At this point, state related to the bank and the accounts db
    1605             :      have been initialized and we are free to finish executing the
    1606             :      block. In practice, this updates some bank fields (notably the
    1607             :      poh and bank hash). */
    1608             : 
    1609           0 :   int err = fd_runtime_process_genesis_block( bank, accdb, capture_ctx, runtime_stack );
    1610           0 :   if( FD_UNLIKELY( err ) ) FD_LOG_CRIT(( "genesis slot 0 execute failed with error %d", err ));
    1611           0 : }
    1612             : 
    1613             : void
    1614             : fd_runtime_block_execute_finalize( fd_bank_t *        bank,
    1615             :                                    fd_accdb_t *       accdb,
    1616         339 :                                    fd_capture_ctx_t * capture_ctx ) {
    1617         339 :   fd_runtime_freeze( bank, accdb, capture_ctx );
    1618         339 :   fd_runtime_update_bank_hash( bank, capture_ctx );
    1619         339 : }
    1620             : 
    1621             : /* Mirrors Agave function solana_sdk::transaction_context::find_index_of_account
    1622             : 
    1623             :    Backward scan over transaction accounts. Returns ULONG_MAX if not found.
    1624             : 
    1625             :    https://github.com/anza-xyz/agave/blob/v2.1.14/sdk/src/transaction_context.rs#L233-L238 */
    1626             : 
    1627             : ulong
    1628             : fd_runtime_find_index_of_account( fd_txn_out_t const * txn_out,
    1629       10524 :                                   fd_pubkey_t const *  pubkey ) {
    1630       25683 :   for( ulong i=0UL; i<txn_out->accounts.cnt; i++ ) {
    1631       22812 :     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;
    1632       22812 :   }
    1633        2871 :   return ULONG_MAX;
    1634       10524 : }
    1635             : 
    1636             : fd_acc_t *
    1637             : fd_runtime_get_account_at_index( fd_txn_in_t const *             txn_in,
    1638             :                                  fd_txn_out_t *                  txn_out,
    1639             :                                  ushort                          idx,
    1640       25647 :                                  fd_txn_account_condition_fn_t * condition ) {
    1641       25647 :   if( FD_UNLIKELY( idx>=txn_out->accounts.cnt ) ) return NULL;
    1642       25647 :   if( FD_LIKELY( condition && !condition( txn_in, txn_out, idx ) ) ) return NULL;
    1643       25506 :   return txn_out->accounts.account[ idx ];
    1644       25647 : }
    1645             : 
    1646             : fd_acc_t *
    1647             : fd_runtime_get_executable_account( fd_txn_out_t *      txn_out,
    1648             :                                    fd_pubkey_t const * pubkey,
    1649             :                                    int *               from_parent_copy,
    1650          54 :                                    int *               pd_write_this_slot ) {
    1651             :   /* First try to fetch the executable account from the existing
    1652             :      borrowed accounts.  If the pubkey is in the account keys, then we
    1653             :      want to re-use that borrowed account since it reflects changes from
    1654             :      prior instructions.  Referencing the read-only executable accounts
    1655             :      list is incorrect behavior when the program data account is written
    1656             :      to in a prior instruction (e.g. program upgrade + invoke within the
    1657             :      same txn) */
    1658             : 
    1659          54 :   if( FD_UNLIKELY( from_parent_copy   ) ) *from_parent_copy   = 0;
    1660          54 :   if( FD_UNLIKELY( pd_write_this_slot ) ) *pd_write_this_slot = 0;
    1661             : 
    1662          54 :   ulong account_idx = fd_runtime_find_index_of_account( txn_out, pubkey );
    1663          54 :   if( FD_LIKELY( account_idx!=ULONG_MAX && txn_out->accounts.account[ account_idx ]->lamports ) ) return txn_out->accounts.account[ account_idx ];
    1664             : 
    1665          51 :   for( ushort i=0; i<txn_out->accounts.executable_cnt; i++ ) {
    1666          27 :     fd_acc_t * ro = txn_out->accounts.executable[ i ];
    1667          27 :     if( FD_UNLIKELY( !memcmp( pubkey->uc, ro->pubkey, 32UL ) ) ) {
    1668          27 :       if( FD_UNLIKELY( !ro->lamports ) ) return NULL;
    1669          27 :       if( FD_UNLIKELY( from_parent_copy   ) ) *from_parent_copy   = txn_out->accounts.executable_from_parent[ i ];
    1670          27 :       if( FD_UNLIKELY( pd_write_this_slot ) ) *pd_write_this_slot = txn_out->accounts.executable_pd_write[ i ];
    1671          27 :       return ro;
    1672          27 :     }
    1673          27 :   }
    1674             : 
    1675          24 :   return NULL;
    1676          51 : }
    1677             : 
    1678             : int
    1679             : fd_runtime_get_key_of_account_at_index( fd_txn_out_t *        txn_out,
    1680             :                                         ushort                idx,
    1681       23808 :                                         fd_pubkey_t const * * key ) {
    1682             :   /* Return a MissingAccount error if idx is out of bounds.
    1683             :      https://github.com/anza-xyz/agave/blob/v3.1.4/transaction-context/src/lib.rs#L187 */
    1684       23808 :   if( FD_UNLIKELY( idx>=txn_out->accounts.cnt ) ) {
    1685           0 :     return FD_EXECUTOR_INSTR_ERR_MISSING_ACC;
    1686           0 :   }
    1687             : 
    1688       23808 :   *key = &txn_out->accounts.keys[ idx ];
    1689       23808 :   return FD_EXECUTOR_INSTR_SUCCESS;
    1690       23808 : }
    1691             : 
    1692             : /* https://github.com/anza-xyz/agave/blob/v2.1.1/sdk/program/src/message/versions/v0/loaded.rs#L162 */
    1693             : int
    1694             : fd_txn_account_is_demotion( const int        idx,
    1695             :                             const fd_txn_t * txn_descriptor,
    1696        1311 :                             const uint       bpf_upgradeable_in_txn ) {
    1697        1311 :   uint is_program = 0U;
    1698        2682 :   for( ulong j=0UL; j<txn_descriptor->instr_cnt; j++ ) {
    1699        1377 :     if( txn_descriptor->instr[j].program_id == idx ) {
    1700           6 :       is_program = 1U;
    1701           6 :       break;
    1702           6 :     }
    1703        1377 :   }
    1704             : 
    1705        1311 :   return (is_program && !bpf_upgradeable_in_txn);
    1706        1311 : }
    1707             : 
    1708             : uint
    1709             : fd_txn_account_has_bpf_loader_upgradeable( fd_pubkey_t const * account_keys,
    1710        2487 :                                            ulong               accounts_cnt ) {
    1711       16710 :   for( ulong j=0; j<accounts_cnt; j++ ) {
    1712       14529 :     const fd_pubkey_t * acc = &account_keys[j];
    1713       14529 :     if ( memcmp( acc->uc, fd_solana_bpf_loader_upgradeable_program_id.key, sizeof(fd_pubkey_t) ) == 0 ) {
    1714         306 :       return 1U;
    1715         306 :     }
    1716       14529 :   }
    1717        2181 :   return 0U;
    1718        2487 : }
    1719             : 
    1720             : static inline int
    1721             : fd_runtime_account_is_writable_idx_flat( const ushort        idx,
    1722             :                                          const fd_pubkey_t * addr_at_idx,
    1723             :                                          const fd_txn_t *    txn_descriptor,
    1724        2487 :                                          const uint          bpf_upgradeable_in_txn ) {
    1725             :   /* https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L43 */
    1726        2487 :   if( !fd_txn_is_writable( txn_descriptor, idx ) ) {
    1727        1170 :     return 0;
    1728        1170 :   }
    1729             : 
    1730             :   /* See comments in fd_system_ids.h.
    1731             :      https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L44 */
    1732        1317 :   if( fd_pubkey_is_active_reserved_key( addr_at_idx ) ||
    1733        1317 :       fd_pubkey_is_pending_reserved_key( addr_at_idx ) ) {
    1734             : 
    1735           6 :     return 0;
    1736           6 :   }
    1737             : 
    1738        1311 :   if( fd_txn_account_is_demotion( idx, txn_descriptor, bpf_upgradeable_in_txn ) ) {
    1739           6 :     return 0;
    1740           6 :   }
    1741             : 
    1742        1305 :   return 1;
    1743        1311 : }
    1744             : 
    1745             : 
    1746             : /* This function aims to mimic the writable accounts check to populate the writable accounts cache, used
    1747             :    to determine if accounts are writable or not.
    1748             : 
    1749             :    https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L38-L47 */
    1750             : int
    1751             : fd_runtime_account_is_writable_idx( fd_txn_in_t const *  txn_in,
    1752             :                                     fd_txn_out_t const * txn_out,
    1753        2487 :                                     ushort               idx ) {
    1754        2487 :   uint bpf_upgradeable = fd_txn_account_has_bpf_loader_upgradeable( txn_out->accounts.keys, txn_out->accounts.cnt );
    1755        2487 :   return fd_runtime_account_is_writable_idx_flat( idx,
    1756        2487 :                                                    &txn_out->accounts.keys[idx],
    1757        2487 :                                                    TXN( txn_in->txn ),
    1758        2487 :                                                    bpf_upgradeable );
    1759        2487 : }
    1760             : 
    1761             : /* Account pre-condition filtering functions */
    1762             : 
    1763             : int
    1764             : fd_runtime_account_check_exists( fd_txn_in_t const * txn_in,
    1765             :                                  fd_txn_out_t *      txn_out,
    1766        2109 :                                  ushort              idx ) {
    1767        2109 :   (void) txn_in;
    1768        2109 :   return txn_out->accounts.account[ idx ]->lamports!=0UL;
    1769        2109 : }
    1770             : 
    1771             : int
    1772             : fd_runtime_account_check_fee_payer_writable( fd_txn_in_t const * txn_in,
    1773             :                                              fd_txn_out_t *      txn_out,
    1774         378 :                                              ushort              idx ) {
    1775         378 :   (void) txn_out;
    1776         378 :   return fd_txn_is_writable( TXN( txn_in->txn ), idx );
    1777         378 : }
    1778             : 
    1779             : 
    1780             : int
    1781             : fd_account_meta_checked_sub_lamports( fd_acc_t * acc,
    1782         378 :                                       ulong      lamports ) {
    1783         378 :   ulong balance_post = 0UL;
    1784         378 :   int err = fd_ulong_checked_sub( acc->lamports, lamports, &balance_post );
    1785         378 :   if( FD_UNLIKELY( err ) ) return FD_EXECUTOR_INSTR_ERR_ARITHMETIC_OVERFLOW;
    1786             : 
    1787         378 :   acc->lamports = balance_post;
    1788         378 :   return FD_EXECUTOR_INSTR_SUCCESS;
    1789         378 : }
    1790             : 
    1791             : /* fd_executor_reuse_bundle_executable scans the runtime's deduplicated
    1792             :    account pools for a programdata account matching programdata_key that
    1793             :    was already opened by an earlier transaction in the bundle (either as
    1794             :    a regular transaction account or as a programdata account).  Returns
    1795             :    the existing fd_acc_t so it can be reused instead of re-acquiring it,
    1796             :    or NULL if none is found.  Must only be called for bundle txns. */
    1797             : 
    1798             : static fd_acc_t *
    1799             : reuse_bundle_executable( fd_runtime_t *      runtime,
    1800          30 :                          fd_pubkey_t const * programdata_key ) {
    1801          87 :   for( ulong j=0UL; j<runtime->accounts.account_cnt; j++ ) {
    1802          72 :     if( FD_LIKELY( !fd_pubkey_eq( fd_type_pun_const( &runtime->accounts.account[ j ].pubkey ), programdata_key ) ) ) continue;
    1803          15 :     return &runtime->accounts.account[ j ];
    1804          72 :   }
    1805          15 :   for( ulong j=0UL; j<runtime->accounts.executable_cnt; j++ ) {
    1806           6 :     if( FD_LIKELY( !fd_pubkey_eq( fd_type_pun_const( &runtime->accounts.executable[ j ].pubkey ), programdata_key ) ) ) continue;
    1807           6 :     return &runtime->accounts.executable[ j ];
    1808           6 :   }
    1809           9 :   return NULL;
    1810          15 : }
    1811             : 
    1812             : int
    1813             : fd_runtime_prepare_bundle_accounts( fd_runtime_t *      runtime,
    1814             :                                     fd_bank_t *         bank,
    1815             :                                     fd_txn_in_t const * txn_ins,
    1816             :                                     fd_txn_out_t *      txn_outs,
    1817          51 :                                     ulong               txn_cnt ) {
    1818             : 
    1819          51 : # define FD_BUNDLE_ACCT_MAX (FD_PACK_MAX_TXN_PER_BUNDLE*MAX_TX_ACCOUNT_LOCKS)
    1820             : 
    1821          51 :   runtime->accounts.account_cnt    = 0UL;
    1822          51 :   runtime->accounts.executable_cnt = 0UL;
    1823             : 
    1824          51 :   uchar const * acquire_pubkeys[ FD_BUNDLE_ACCT_MAX ];
    1825          51 :   int           acquire_writable[ FD_BUNDLE_ACCT_MAX ];
    1826          51 :   ulong         acquire_cnt = 0UL;
    1827             : 
    1828             :   /* First resolve a deduped set of account keys for all txns in the
    1829             :     bundle.  This includes static account keys as well as ALUT resolved
    1830             :     addresses. */
    1831             : 
    1832         153 :   for( ulong i=0UL; i<txn_cnt; i++ ) {
    1833         105 :     fd_txn_in_t const * txn_in  = &txn_ins [ i ];
    1834         105 :     fd_txn_out_t *      txn_out = &txn_outs[ i ];
    1835             : 
    1836         105 :     txn_out->accounts.cnt = (uchar)TXN( txn_in->txn )->acct_addr_cnt;
    1837         105 :     fd_pubkey_t * tx_accs = (fd_pubkey_t *)((uchar *)txn_in->txn->payload + TXN( txn_in->txn )->acct_addr_off);
    1838         846 :     for( ulong j=0UL; j<TXN( txn_in->txn )->acct_addr_cnt; j++ ) {
    1839         741 :       txn_out->accounts.keys[ j ]             = tx_accs[ j ];
    1840         741 :       txn_out->accounts.account[ j ]          = NULL;
    1841         741 :       txn_out->accounts.account_acquired[ j ] = 0U;
    1842         741 :     }
    1843             : 
    1844         105 :     int err = fd_executor_setup_txn_alut_account_keys( runtime, bank, txn_in, txn_out );
    1845         105 :     for( ulong j=TXN( txn_in->txn )->acct_addr_cnt; j<txn_out->accounts.cnt; j++ ) {
    1846           0 :       txn_out->accounts.account[ j ]          = NULL;
    1847           0 :       txn_out->accounts.account_acquired[ j ] = 0U;
    1848           0 :     }
    1849         105 :     if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) return err;
    1850             : 
    1851             :     /* Validate account locks before the union acquire below, bounding
    1852             :        the deduped set within the accdb acquire limit. */
    1853         102 :     err = fd_executor_validate_account_locks( txn_out );
    1854         102 :     if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) return err;
    1855             : 
    1856         840 :     for( ushort j=0; j<txn_out->accounts.cnt; j++ ) {
    1857         738 :       fd_pubkey_t const * key = &txn_out->accounts.keys[ j ];
    1858         738 :       int dup = 0;
    1859        3696 :       for( ulong k=0UL; k<acquire_cnt; k++ ) if( FD_UNLIKELY( !memcmp( acquire_pubkeys[ k ], key->uc, 32UL ) ) ) { dup = 1; break; }
    1860         738 :       if( FD_UNLIKELY( dup ) ) continue;
    1861         345 :       FD_TEST( acquire_cnt<FD_BUNDLE_ACCT_MAX );
    1862         345 :       acquire_pubkeys [ acquire_cnt ] = key->uc;
    1863             :       /* Bundle accounts are always acquired writable so that a later
    1864             :         txn can cleanly upgrade a read permission to a write. */
    1865         345 :       acquire_writable[ acquire_cnt ] = 1;
    1866         345 :       acquire_cnt++;
    1867         345 :     }
    1868         102 :   }
    1869             : 
    1870          48 :   if( FD_LIKELY( acquire_cnt ) ) {
    1871          48 :     fd_accdb_acquire_a( runtime->accdb, bank->accdb_fork_id, acquire_cnt, acquire_pubkeys, acquire_writable, runtime->accounts.account );
    1872          48 :     runtime->accounts.account_cnt = acquire_cnt;
    1873          48 :   }
    1874             : 
    1875         147 :   for( ulong i=0UL; i<txn_cnt; i++ ) {
    1876          99 :     fd_txn_out_t * txn_out = &txn_outs[ i ];
    1877         828 :     for( ushort j=0; j<txn_out->accounts.cnt; j++ ) {
    1878         729 :       txn_out->accounts.account[ j ] = NULL;
    1879        3678 :       for( ulong k=0UL; k<runtime->accounts.account_cnt; k++ ) {
    1880        3678 :         fd_acc_t * acc = &runtime->accounts.account[ k ];
    1881        3678 :         if( FD_LIKELY( !fd_pubkey_eq( fd_type_pun_const( &acc->pubkey ), &txn_out->accounts.keys[ j ] ) ) ) continue;
    1882         729 :         txn_out->accounts.account[ j ]           = acc;
    1883         729 :         txn_out->accounts.starting_lamports[ j ] = acc->prior_lamports;
    1884         729 :         txn_out->accounts.starting_data_len[ j ] = acc->prior_data_len;
    1885         729 :         memcpy( &txn_out->accounts.starting_owner[ j ], acc->prior_owner, sizeof(fd_pubkey_t) );
    1886         729 :         break;
    1887        3678 :       }
    1888         729 :     }
    1889          99 :   }
    1890             : 
    1891             :   /* Do the same for executable accounts (programdata accounts).  Dedup
    1892             :     against all other executable-only accounts as well as ones that
    1893             :     were already included. */
    1894             : 
    1895          48 :   fd_pubkey_t   programdata_keys[ FD_BUNDLE_ACCT_MAX ];
    1896          48 :   uchar const * pd_pubkeys      [ FD_BUNDLE_ACCT_MAX ];
    1897          48 :   int           pd_writable     [ FD_BUNDLE_ACCT_MAX ];
    1898          48 :   ulong         pd_cnt = 0UL;
    1899             : 
    1900          48 :   FD_TEST( bank->parent_accdb_fork_id.val!=USHORT_MAX );
    1901             : 
    1902         384 :   for( ulong i=0UL; i<runtime->accounts.account_cnt; i++ ) {
    1903         336 :     fd_acc_t * acc = &runtime->accounts.account[ i ];
    1904         336 :     if( FD_LIKELY( memcmp( acc->owner, fd_solana_bpf_loader_upgradeable_program_id.key, 32UL ) ) ) continue;
    1905          30 :     fd_bpf_state_t program_loader_state[1];
    1906          30 :     if( FD_UNLIKELY( fd_bpf_loader_program_get_state( acc, program_loader_state )!=FD_EXECUTOR_INSTR_SUCCESS ) ) continue;
    1907          30 :     if( FD_UNLIKELY( program_loader_state->discriminant!=FD_BPF_STATE_PROGRAM ) ) continue;
    1908             : 
    1909          18 :     fd_pubkey_t const * programdata_key = &program_loader_state->inner.program.programdata_address;
    1910             :     /* PD is not live as of the parent, so there is nothing to acquire
    1911             :        from the parent.  We will still need its latest length for loaded
    1912             :        accounts data size, but that is taken care of per transaction by
    1913             :        fd_runtime_setup_bundle_executables() without acquiring. */
    1914          18 :     if( FD_UNLIKELY( !fd_accdb_exists( runtime->accdb, bank->parent_accdb_fork_id, programdata_key->uc ) ) ) continue;
    1915             : 
    1916             :     /* Already part of the transaction account pool, or already queued. */
    1917           9 :     if( reuse_bundle_executable( runtime, programdata_key ) ) continue;
    1918           6 :     int dup = 0;
    1919           6 :     for( ulong u=0UL; u<pd_cnt; u++ ) if( FD_UNLIKELY( !memcmp( programdata_keys[ u ].uc, programdata_key->uc, 32UL ) ) ) { dup = 1; break; }
    1920           6 :     if( dup ) continue;
    1921             : 
    1922           6 :     FD_TEST( pd_cnt<FD_BUNDLE_ACCT_MAX );
    1923           6 :     programdata_keys[ pd_cnt ] = *programdata_key;
    1924           6 :     pd_pubkeys[ pd_cnt ]       = programdata_keys[ pd_cnt ].uc;
    1925           6 :     pd_writable[ pd_cnt ]      = 0;
    1926           6 :     pd_cnt++;
    1927           6 :   }
    1928             : 
    1929             :   /* acquire_b refunds the per-class reservations acquire_a made for the
    1930             :     union (reserved_cnt==acquire_cnt) that did not turn out to be
    1931             :     programdata.  Skip it entirely for an empty bundle (nothing was
    1932             :     reserved and nothing is executable). */
    1933          48 :   if( FD_LIKELY( acquire_cnt || pd_cnt ) ) {
    1934          48 :     fd_accdb_acquire_b( runtime->accdb, bank->parent_accdb_fork_id, acquire_cnt, pd_cnt, pd_pubkeys, pd_writable, runtime->accounts.executable );
    1935          48 :   }
    1936          48 :   runtime->accounts.executable_cnt = pd_cnt;
    1937             : 
    1938          48 :   return FD_RUNTIME_EXECUTE_SUCCESS;
    1939             : 
    1940          48 : # undef FD_BUNDLE_ACCT_MAX
    1941          48 : }
    1942             : 
    1943             : int
    1944             : fd_runtime_setup_bundle_executables( fd_runtime_t * runtime,
    1945             :                                      fd_bank_t *    bank,
    1946          99 :                                      fd_txn_out_t * txn_out ) {
    1947          99 :   FD_TEST( bank->parent_accdb_fork_id.val!=USHORT_MAX );
    1948             : 
    1949          99 :   ushort exe_cnt = 0;
    1950          99 :   txn_out->accounts.executable_skipped_cnt = 0;
    1951         828 :   for( ushort i=0; i<txn_out->accounts.cnt; i++ ) {
    1952             :     /* The checks below mimic the ones in the non-bundle path.  The
    1953             :        difference is only the source of state as of this transaction.
    1954             :        Here it's from the live pool when possible, and in the non-bundle
    1955             :        path it's from the accdb. */
    1956         729 :     fd_acc_t * acc = txn_out->accounts.account[ i ]; /* This has gone through zero-lamport reset by fd_executor_setup_accounts_for_txn_bundle(). */
    1957         729 :     if( FD_LIKELY( memcmp( acc->owner, fd_solana_bpf_loader_upgradeable_program_id.key, 32UL ) ) ) continue;
    1958          39 :     fd_bpf_state_t program_loader_state[1];
    1959          39 :     if( FD_UNLIKELY( fd_bpf_loader_program_get_state( acc, program_loader_state )!=FD_EXECUTOR_INSTR_SUCCESS ) ) continue;
    1960          39 :     if( FD_UNLIKELY( program_loader_state->discriminant!=FD_BPF_STATE_PROGRAM ) ) continue;
    1961             : 
    1962          27 :     fd_pubkey_t const * programdata_key = &program_loader_state->inner.program.programdata_address;
    1963             : 
    1964             :     /* Declared PD is charged as a plain top-level transaction account
    1965             :        and is preferred by fd_runtime_get_executable_account(). */
    1966          27 :     if( FD_UNLIKELY( fd_runtime_find_index_of_account( txn_out, programdata_key )!=ULONG_MAX ) ) continue;
    1967             : 
    1968          21 :     fd_acc_t * programdata = reuse_bundle_executable( runtime, programdata_key );
    1969             : 
    1970          21 :     if( FD_UNLIKELY( !fd_accdb_exists( runtime->accdb, bank->parent_accdb_fork_id, programdata_key->uc ) ) ) {
    1971             :       /* PD is not live as of the parent.  Length only, and no
    1972             :          executable[] entry, so the loader reports "Program is not
    1973             :          deployed" exactly as the non-bundle path does.  The non-bundle
    1974             :          path takes the length from the latest accdb view committed on
    1975             :          this fork.  The equivalent here is the live pool copy, which an
    1976             :          earlier bundle transaction may have created, resized or
    1977             :          drained. */
    1978          12 :       ulong skip_len;
    1979          12 :       if( FD_LIKELY( programdata ) ) {
    1980             :         /* A dead PD must contribute nothing to loaded accounts data
    1981             :            size.  Like every other consumer, the lamports need to be
    1982             :            checked first.  The pool copy that programdata points to has
    1983             :            an up to date lamports, but it is not necessarily otherwise
    1984             :            normalized: zero length, non-executable, and system-owned.
    1985             :            The reset in setup_accounts_for_txn_bundle() only covers the
    1986             :            declared accounts of the transaction.  If PD were declared,
    1987             :            it would have short circuited above.  So an in-bundle Close
    1988             :            leaves PD here at zero lamports with length at
    1989             :            SIZE_OF_UNINITIALIZED. */
    1990           9 :         skip_len = programdata->lamports ? programdata->data_len : 0UL;
    1991           9 :       } else {
    1992             :         /* At this point, this PD
    1993             :            - has no pool copy, so no bundle transaction declares PD, and
    1994             :            - it is not live on the parent.
    1995             : 
    1996             :            So PD was created this slot by something outside the bundle,
    1997             :            and only the latest accdb view has the length we need for
    1998             :            accounting. */
    1999           3 :         int   probe_pd  = 0;
    2000           3 :         ulong probe_len = 0UL;
    2001           3 :         ulong probe_lamports = 0UL;
    2002           3 :         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;
    2003           3 :         skip_len = probe_len;
    2004           3 :       }
    2005          12 :       ushort s = txn_out->accounts.executable_skipped_cnt++;
    2006          12 :       txn_out->accounts.executable_skipped_key[ s ] = *programdata_key;
    2007          12 :       txn_out->accounts.executable_skipped_len[ s ] = skip_len;
    2008          12 :       continue;
    2009          12 :     }
    2010             : 
    2011             :     /* At this point, PD exists in the parent.  So prepare() must have
    2012             :        acquired PD, either in accounts[] if a bundle transaction
    2013             :        declares it, or in executable[] aka implied load from the parent.
    2014             :        A miss would imply that a pool account only began parsing as
    2015             :        Program{PD} after prepare() computed the acquire set, naming a PD
    2016             :        no bundle transaction declares.  This should not be possible,
    2017             :        because only the DeployWithMaxDataLen instruction writes
    2018             :        Program{PD}.  The instruction declares PD, and its CreateAccount
    2019             :        CPI cannot succeed against a PD that is already live on the
    2020             :        parent.  We cannot acquire the PD at this point, since a
    2021             :        mid-bundle acquire of an account the bundle might be holding as
    2022             :        writable would violate the accdb acquire contract.  So fail the
    2023             :        bundle. */
    2024           9 :     if( FD_UNLIKELY( !programdata ) ) {
    2025           0 :       FD_BASE58_ENCODE_32_BYTES( programdata_key->uc, pd_str );
    2026           0 :       FD_BASE58_ENCODE_64_BYTES( txn_out->details.signature.uc, sig_str );
    2027           0 :       FD_LOG_INFO(( "dropping bundle: bundle txn %s in slot %lu implies unacquired programdata %s", sig_str, bank->f.slot, pd_str ));
    2028           0 :       return FD_RUNTIME_TXN_ERR_PROGRAM_ACCOUNT_NOT_FOUND;
    2029           0 :     }
    2030             : 
    2031           9 :     int from_parent = ( programdata>=runtime->accounts.executable ) &&
    2032           9 :                       ( programdata< runtime->accounts.executable+runtime->accounts.executable_cnt ) &&
    2033           9 :                       ( bank->parent_accdb_fork_id.val!=bank->accdb_fork_id.val );
    2034           9 :     txn_out->accounts.executable[ exe_cnt ]             = programdata;
    2035           9 :     txn_out->accounts.executable_from_parent[ exe_cnt ] = from_parent;
    2036           9 :     if( from_parent ) {
    2037             :       /* A from_parent copy is one no bundle transaction declared, hence
    2038             :          one no bundle transaction could have modified, because mutating
    2039             :          PD requires declaring it writable.  So the probe from accdb
    2040             :          reports the latest state that we need. */
    2041           6 :       int   pd  = 0;
    2042           6 :       ulong len = ULONG_MAX;
    2043           6 :       ulong lamports = 0UL;
    2044           6 :       fd_accdb_probe_pd_this_fork( runtime->accdb, bank->accdb_fork_id, programdata_key->uc, &pd, &len, &lamports );
    2045           6 :       txn_out->accounts.executable_pd_write    [ exe_cnt ] = pd;
    2046           6 :       txn_out->accounts.executable_cur_len     [ exe_cnt ] = len;
    2047           6 :       txn_out->accounts.executable_cur_lamports[ exe_cnt ] = lamports;
    2048           6 :     } else {
    2049           3 :       txn_out->accounts.executable_pd_write    [ exe_cnt ] = 0;
    2050           3 :       txn_out->accounts.executable_cur_len     [ exe_cnt ] = ULONG_MAX;
    2051           3 :       txn_out->accounts.executable_cur_lamports[ exe_cnt ] = 0UL;
    2052           3 :     }
    2053           9 :     exe_cnt++;
    2054           9 :   }
    2055          99 :   txn_out->accounts.executable_cnt = exe_cnt;
    2056          99 :   return FD_RUNTIME_EXECUTE_SUCCESS;
    2057          99 : }

Generated by: LCOV version 1.14