LCOV - code coverage report
Current view: top level - flamenco/runtime - fd_runtime.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 810 1139 71.1 %
Date: 2026-08-22 04:33:51 Functions: 41 48 85.4 %

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

Generated by: LCOV version 1.14