LCOV - code coverage report
Current view: top level - flamenco/runtime - fd_runtime.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 202 999 20.2 %
Date: 2025-12-25 05:10:20 Functions: 16 42 38.1 %

          Line data    Source code
       1             : #include "fd_runtime.h"
       2             : #include "../capture/fd_capture_ctx.h"
       3             : #include "../types/fd_cast.h"
       4             : #include "fd_acc_mgr.h"
       5             : #include "fd_alut_interp.h"
       6             : #include "fd_bank.h"
       7             : #include "fd_executor_err.h"
       8             : #include "fd_hashes.h"
       9             : #include "fd_runtime_err.h"
      10             : #include "fd_runtime_stack.h"
      11             : #include "fd_genesis_parse.h"
      12             : 
      13             : #include "fd_executor.h"
      14             : #include "fd_txn_account.h"
      15             : #include "sysvar/fd_sysvar_cache.h"
      16             : #include "sysvar/fd_sysvar_clock.h"
      17             : #include "sysvar/fd_sysvar_epoch_schedule.h"
      18             : #include "sysvar/fd_sysvar_recent_hashes.h"
      19             : #include "sysvar/fd_sysvar_stake_history.h"
      20             : 
      21             : #include "../stakes/fd_stakes.h"
      22             : #include "../rewards/fd_rewards.h"
      23             : #include "../accdb/fd_accdb_impl_v1.h"
      24             : #include "../progcache/fd_progcache_user.h"
      25             : 
      26             : #include "program/fd_stake_program.h"
      27             : #include "program/fd_builtin_programs.h"
      28             : #include "program/fd_program_util.h"
      29             : 
      30             : #include "sysvar/fd_sysvar_clock.h"
      31             : #include "sysvar/fd_sysvar_last_restart_slot.h"
      32             : #include "sysvar/fd_sysvar_recent_hashes.h"
      33             : #include "sysvar/fd_sysvar_rent.h"
      34             : #include "sysvar/fd_sysvar_slot_hashes.h"
      35             : #include "sysvar/fd_sysvar_slot_history.h"
      36             : 
      37             : #include "tests/fd_dump_pb.h"
      38             : 
      39             : #include "fd_system_ids.h"
      40             : 
      41             : #include "../../disco/pack/fd_pack.h"
      42             : #include "../../disco/pack/fd_pack_tip_prog_blacklist.h"
      43             : 
      44             : #include <unistd.h>
      45             : #include <sys/stat.h>
      46             : #include <sys/types.h>
      47             : #include <fcntl.h>
      48             : 
      49             : /******************************************************************************/
      50             : /* Public Runtime Helpers                                                     */
      51             : /******************************************************************************/
      52             : 
      53             : 
      54             : /*
      55             :    https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/bank.rs#L1254-L1258
      56             :    https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/bank.rs#L1749
      57             :  */
      58             : int
      59             : fd_runtime_compute_max_tick_height( ulong   ticks_per_slot,
      60             :                                     ulong   slot,
      61           0 :                                     ulong * out_max_tick_height /* out */ ) {
      62           0 :   ulong max_tick_height = 0UL;
      63           0 :   if( FD_LIKELY( ticks_per_slot > 0UL ) ) {
      64           0 :     ulong next_slot = fd_ulong_sat_add( slot, 1UL );
      65           0 :     if( FD_UNLIKELY( next_slot == slot ) ) {
      66           0 :       FD_LOG_WARNING(( "max tick height addition overflowed slot %lu ticks_per_slot %lu", slot, ticks_per_slot ));
      67           0 :       return -1;
      68           0 :     }
      69           0 :     if( FD_UNLIKELY( ULONG_MAX / ticks_per_slot < next_slot ) ) {
      70           0 :       FD_LOG_WARNING(( "max tick height multiplication overflowed slot %lu ticks_per_slot %lu", slot, ticks_per_slot ));
      71           0 :       return -1;
      72           0 :     }
      73           0 :     max_tick_height = fd_ulong_sat_mul( next_slot, ticks_per_slot );
      74           0 :   }
      75           0 :   *out_max_tick_height = max_tick_height;
      76           0 :   return FD_RUNTIME_EXECUTE_SUCCESS;
      77           0 : }
      78             : 
      79             : /* Returns whether the specified epoch should use the new vote account
      80             :    keyed leader schedule (returns 1) or the old validator identity keyed
      81             :    leader schedule (returns 0). See SIMD-0180.  This is the analogous to
      82             :    Agave's Bank::should_use_vote_keyed_leader_schedule():
      83             :    https://github.com/anza-xyz/agave/blob/v2.3.1/runtime/src/bank.rs#L6148 */
      84             : 
      85             : static int
      86           0 : fd_runtime_should_use_vote_keyed_leader_schedule( fd_bank_t * bank ) {
      87             :   /* Agave uses an option type for their effective_epoch value. We
      88             :      represent None as ULONG_MAX and Some(value) as the value.
      89             :      https://github.com/anza-xyz/agave/blob/v2.3.1/runtime/src/bank.rs#L6149-L6165 */
      90           0 :   if( FD_FEATURE_ACTIVE_BANK( bank, enable_vote_address_leader_schedule ) ) {
      91             :     /* Return the first epoch if activated at genesis
      92             :        https://github.com/anza-xyz/agave/blob/v2.3.1/runtime/src/bank.rs#L6153-L6157 */
      93           0 :     ulong activation_slot = fd_bank_features_query( bank )->enable_vote_address_leader_schedule;
      94           0 :     if( activation_slot==0UL ) return 1; /* effective_epoch=0, current_epoch >= effective_epoch always true */
      95             : 
      96             :     /* Calculate the epoch that the feature became activated in
      97             :        https://github.com/anza-xyz/agave/blob/v2.3.1/runtime/src/bank.rs#L6159-L6160 */
      98           0 :     fd_epoch_schedule_t const * epoch_schedule = fd_bank_epoch_schedule_query( bank );
      99           0 :     ulong activation_epoch = fd_slot_to_epoch( epoch_schedule, activation_slot, NULL );
     100             : 
     101             :     /* The effective epoch is the epoch immediately after the activation
     102             :        epoch.
     103             :        https://github.com/anza-xyz/agave/blob/v2.3.1/runtime/src/bank.rs#L6162-L6164 */
     104           0 :     ulong effective_epoch = activation_epoch + 1UL;
     105           0 :     ulong current_epoch   = fd_bank_epoch_get( bank );
     106             : 
     107             :     /* https://github.com/anza-xyz/agave/blob/v2.3.1/runtime/src/bank.rs#L6167-L6170 */
     108           0 :     return !!( current_epoch >= effective_epoch );
     109           0 :   }
     110             : 
     111             :   /* ...The rest of the logic in this function either returns None or
     112             :      Some(false) so we will just return 0 by default. */
     113           0 :   return 0;
     114           0 : }
     115             : 
     116             : void
     117             : fd_runtime_update_leaders( fd_bank_t *          bank,
     118           9 :                            fd_runtime_stack_t * runtime_stack ) {
     119             : 
     120           9 :   fd_epoch_schedule_t const * epoch_schedule = fd_bank_epoch_schedule_query( bank );
     121             : 
     122           9 :   ulong epoch    = fd_slot_to_epoch ( epoch_schedule, fd_bank_slot_get( bank ), NULL );
     123           9 :   ulong slot0    = fd_epoch_slot0   ( epoch_schedule, epoch );
     124           9 :   ulong slot_cnt = fd_epoch_slot_cnt( epoch_schedule, epoch );
     125             : 
     126           9 :   fd_vote_states_t const * vote_states_prev_prev = fd_bank_vote_states_prev_prev_locking_query( bank );
     127           9 :   fd_vote_stake_weight_t * epoch_weights         = runtime_stack->stakes.stake_weights;
     128           9 :   ulong                    stake_weight_cnt      = fd_stake_weights_by_node( vote_states_prev_prev, epoch_weights );
     129           9 :   fd_bank_vote_states_prev_prev_end_locking_query( bank );
     130             : 
     131             :   /* Derive leader schedule */
     132             : 
     133           9 :   ulong epoch_leaders_footprint = fd_epoch_leaders_footprint( stake_weight_cnt, slot_cnt );
     134           9 :   if( FD_LIKELY( epoch_leaders_footprint ) ) {
     135           0 :     if( FD_UNLIKELY( stake_weight_cnt>MAX_PUB_CNT ) ) {
     136           0 :       FD_LOG_ERR(( "Stake weight count exceeded max" ));
     137           0 :     }
     138           0 :     if( FD_UNLIKELY( slot_cnt>MAX_SLOTS_PER_EPOCH ) ) {
     139           0 :       FD_LOG_ERR(( "Slot count exceeeded max" ));
     140           0 :     }
     141             : 
     142           0 :     ulong vote_keyed_lsched = (ulong)fd_runtime_should_use_vote_keyed_leader_schedule( bank );
     143           0 :     void * epoch_leaders_mem = fd_bank_epoch_leaders_locking_modify( bank );
     144           0 :     fd_epoch_leaders_t * leaders = fd_epoch_leaders_join( fd_epoch_leaders_new(
     145           0 :         epoch_leaders_mem,
     146           0 :         epoch,
     147           0 :         slot0,
     148           0 :         slot_cnt,
     149           0 :         stake_weight_cnt,
     150           0 :         epoch_weights,
     151           0 :         0UL,
     152           0 :         vote_keyed_lsched ) );
     153           0 :     if( FD_UNLIKELY( !leaders ) ) {
     154           0 :       FD_LOG_ERR(( "Unable to init and join fd_epoch_leaders" ));
     155           0 :     }
     156           0 :     fd_bank_epoch_leaders_end_locking_modify( bank );
     157           0 :   }
     158           9 : }
     159             : 
     160             : /******************************************************************************/
     161             : /* Various Private Runtime Helpers                                            */
     162             : /******************************************************************************/
     163             : 
     164             : /* fee to be deposited should be > 0
     165             :    Returns 0 if validation succeeds
     166             :    Returns the amount to burn(==fee) on failure */
     167             : static ulong
     168             : fd_runtime_validate_fee_collector( fd_bank_t *              bank,
     169             :                                    fd_txn_account_t const * collector,
     170           0 :                                    ulong                    fee ) {
     171           0 :   if( FD_UNLIKELY( fee<=0UL ) ) {
     172           0 :     FD_LOG_ERR(( "expected fee(%lu) to be >0UL", fee ));
     173           0 :   }
     174             : 
     175           0 :   if( FD_UNLIKELY( memcmp( fd_txn_account_get_owner( collector ), fd_solana_system_program_id.key, sizeof(fd_pubkey_t) ) ) ) {
     176           0 :     FD_BASE58_ENCODE_32_BYTES( collector->pubkey->key, _out_key );
     177           0 :     FD_LOG_WARNING(( "cannot pay a non-system-program owned account (%s)", _out_key ));
     178           0 :     return fee;
     179           0 :   }
     180             : 
     181             :   /* https://github.com/anza-xyz/agave/blob/v1.18.23/runtime/src/bank/fee_distribution.rs#L111
     182             :      https://github.com/anza-xyz/agave/blob/v1.18.23/runtime/src/accounts/account_rent_state.rs#L39
     183             :      In agave's fee deposit code, rent state transition check logic is as follows:
     184             :      The transition is NOT allowed iff
     185             :      === BEGIN
     186             :      the post deposit account is rent paying AND the pre deposit account is not rent paying
     187             :      OR
     188             :      the post deposit account is rent paying AND the pre deposit account is rent paying AND !(post_data_size == pre_data_size && post_lamports <= pre_lamports)
     189             :      === END
     190             :      post_data_size == pre_data_size is always true during fee deposit.
     191             :      However, post_lamports > pre_lamports because we are paying a >0 amount.
     192             :      So, the above reduces down to
     193             :      === BEGIN
     194             :      the post deposit account is rent paying AND the pre deposit account is not rent paying
     195             :      OR
     196             :      the post deposit account is rent paying AND the pre deposit account is rent paying AND TRUE
     197             :      === END
     198             :      This is equivalent to checking that the post deposit account is rent paying.
     199             :      An account is rent paying if the post deposit balance is >0 AND it's not rent exempt.
     200             :      We already know that the post deposit balance is >0 because we are paying a >0 amount.
     201             :      So TLDR we just check if the account is rent exempt.
     202             :    */
     203           0 :   fd_rent_t const * rent = fd_bank_rent_query( bank );
     204           0 :   ulong minbal = fd_rent_exempt_minimum_balance( rent, fd_txn_account_get_data_len( collector ) );
     205           0 :   if( FD_UNLIKELY( fd_txn_account_get_lamports( collector )+fee<minbal ) ) {
     206           0 :     FD_BASE58_ENCODE_32_BYTES( collector->pubkey->key, _out_key );
     207           0 :     FD_LOG_WARNING(("cannot pay a rent paying account (%s)", _out_key ));
     208           0 :     return fee;
     209           0 :   }
     210             : 
     211           0 :   return 0UL;
     212           0 : }
     213             : 
     214             : static int
     215             : fd_runtime_run_incinerator( fd_bank_t *               bank,
     216             :                             fd_accdb_user_t *         accdb,
     217             :                             fd_funk_txn_xid_t const * xid,
     218           0 :                             fd_capture_ctx_t *        capture_ctx ) {
     219           0 :   fd_txn_account_t rec[1];
     220           0 :   fd_funk_rec_prepare_t prepare = {0};
     221             : 
     222           0 :   int ok = !!fd_txn_account_init_from_funk_mutable(
     223           0 :       rec,
     224           0 :       &fd_sysvar_incinerator_id,
     225           0 :       accdb,
     226           0 :       xid,
     227           0 :       0,
     228           0 :       0UL,
     229           0 :       &prepare );
     230           0 :   if( FD_UNLIKELY( !ok ) ) {
     231             :     // TODO: not really an error! This is fine!
     232           0 :     return -1;
     233           0 :   }
     234             : 
     235           0 :   fd_lthash_value_t prev_hash[1];
     236           0 :   fd_hashes_account_lthash( rec->pubkey, fd_txn_account_get_meta( rec ), fd_txn_account_get_data( rec ), prev_hash );
     237             : 
     238           0 :   ulong new_capitalization = fd_ulong_sat_sub( fd_bank_capitalization_get( bank ), fd_txn_account_get_lamports( rec ) );
     239           0 :   fd_bank_capitalization_set( bank, new_capitalization );
     240             : 
     241           0 :   fd_txn_account_set_lamports( rec, 0UL );
     242           0 :   fd_hashes_update_lthash( rec->pubkey, rec->meta, prev_hash, bank, capture_ctx );
     243           0 :   fd_txn_account_mutable_fini( rec, accdb, &prepare );
     244             : 
     245           0 :   return 0;
     246           0 : }
     247             : 
     248             : static void
     249             : fd_runtime_freeze( fd_bank_t *         bank,
     250             :                    fd_accdb_user_t *   accdb,
     251           0 :                    fd_capture_ctx_t *  capture_ctx ) {
     252             : 
     253           0 :   fd_funk_txn_xid_t const xid = { .ul = { fd_bank_slot_get( bank ), bank->idx } };
     254             : 
     255           0 :   if( FD_LIKELY( fd_bank_slot_get( bank ) != 0UL ) ) {
     256           0 :     fd_sysvar_recent_hashes_update( bank, accdb, &xid, capture_ctx );
     257           0 :   }
     258             : 
     259           0 :   fd_sysvar_slot_history_update( bank, accdb, &xid, capture_ctx );
     260             : 
     261           0 :   ulong execution_fees = fd_bank_execution_fees_get( bank );
     262           0 :   ulong priority_fees  = fd_bank_priority_fees_get( bank );
     263             : 
     264           0 :   ulong burn = execution_fees / 2;
     265           0 :   ulong fees = fd_ulong_sat_add( priority_fees, execution_fees - burn );
     266             : 
     267           0 :   if( FD_LIKELY( fees ) ) {
     268             :     // Look at collect_fees... I think this was where I saw the fee payout..
     269           0 :     fd_txn_account_t rec[1];
     270             : 
     271           0 :     do {
     272             :       /* do_create=1 because we might wanna pay fees to a leader
     273             :          account that we've purged due to 0 balance. */
     274             : 
     275           0 :       fd_epoch_leaders_t const * leaders = fd_bank_epoch_leaders_locking_query( bank );
     276           0 :       if( FD_UNLIKELY( !leaders ) ) {
     277           0 :         FD_LOG_CRIT(( "fd_runtime_freeze: leaders not found" ));
     278           0 :         fd_bank_epoch_leaders_end_locking_query( bank );
     279           0 :         break;
     280           0 :       }
     281             : 
     282           0 :       fd_pubkey_t const * leader = fd_epoch_leaders_get( leaders, fd_bank_slot_get( bank ) );
     283           0 :       if( FD_UNLIKELY( !leader ) ) {
     284           0 :         FD_LOG_CRIT(( "fd_runtime_freeze: leader not found" ));
     285           0 :         fd_bank_epoch_leaders_end_locking_query( bank );
     286           0 :         break;
     287           0 :       }
     288             : 
     289           0 :       fd_funk_rec_prepare_t prepare = {0};
     290           0 :       int ok = !!fd_txn_account_init_from_funk_mutable(
     291           0 :           rec,
     292           0 :           leader,
     293           0 :           accdb,
     294           0 :           &xid,
     295           0 :           1,
     296           0 :           0UL,
     297           0 :           &prepare );
     298           0 :       if( FD_UNLIKELY( !ok ) ) {
     299           0 :         FD_BASE58_ENCODE_32_BYTES( leader->uc, leader_b58 );
     300           0 :         FD_LOG_WARNING(( "fd_runtime_freeze: fd_txn_account_init_from_funk_mutable for leader (%s) failed", leader_b58 ));
     301           0 :         burn = fd_ulong_sat_add( burn, fees );
     302           0 :         fd_bank_epoch_leaders_end_locking_query( bank );
     303           0 :         break;
     304           0 :       }
     305             : 
     306           0 :       fd_lthash_value_t prev_hash[1];
     307           0 :       fd_hashes_account_lthash( leader, fd_txn_account_get_meta( rec ), fd_txn_account_get_data( rec ), prev_hash );
     308             : 
     309           0 :       fd_bank_epoch_leaders_end_locking_query( bank );
     310             : 
     311           0 :       if ( FD_LIKELY( FD_FEATURE_ACTIVE_BANK( bank, validate_fee_collector_account ) ) ) {
     312           0 :         ulong _burn;
     313           0 :         if( FD_UNLIKELY( _burn=fd_runtime_validate_fee_collector( bank, rec, fees ) ) ) {
     314           0 :           if( FD_UNLIKELY( _burn!=fees ) ) {
     315           0 :             FD_LOG_ERR(( "expected _burn(%lu)==fees(%lu)", _burn, fees ));
     316           0 :           }
     317           0 :           burn = fd_ulong_sat_add( burn, fees );
     318           0 :           FD_LOG_WARNING(("fd_runtime_freeze: burned %lu", fees ));
     319           0 :           break;
     320           0 :         }
     321           0 :       }
     322             : 
     323             :       /* TODO: is it ok to not check the overflow error here? */
     324           0 :       fd_txn_account_checked_add_lamports( rec, fees );
     325           0 :       fd_txn_account_set_slot( rec, fd_bank_slot_get( bank ) );
     326             : 
     327           0 :       fd_hashes_update_lthash( rec->pubkey, rec->meta, prev_hash, bank, capture_ctx );
     328           0 :       fd_txn_account_mutable_fini( rec, accdb, &prepare );
     329             : 
     330           0 :     } while(0);
     331             : 
     332           0 :     ulong old = fd_bank_capitalization_get( bank );
     333           0 :     fd_bank_capitalization_set( bank, fd_ulong_sat_sub( old, burn ) );
     334           0 :     FD_LOG_DEBUG(( "fd_runtime_freeze: burn %lu, capitalization %lu->%lu ", burn, old, fd_bank_capitalization_get( bank ) ));
     335           0 :   }
     336             : 
     337             :   /* jito collects a 3% fee at the end of the block + 3% fee at
     338             :      distribution time. */
     339           0 :   fd_bank_tips_set( bank, (fd_bank_tips_get( bank ) * 6UL / 100UL) );
     340             : 
     341           0 :   fd_runtime_run_incinerator( bank, accdb, &xid, capture_ctx );
     342             : 
     343           0 : }
     344             : 
     345             : /******************************************************************************/
     346             : /* Block-Level Execution Preparation/Finalization                             */
     347             : /******************************************************************************/
     348             : void
     349             : fd_runtime_new_fee_rate_governor_derived( fd_bank_t * bank,
     350          27 :                                           ulong       latest_signatures_per_slot ) {
     351             : 
     352          27 :   fd_fee_rate_governor_t const * base_fee_rate_governor = fd_bank_fee_rate_governor_query( bank );
     353             : 
     354          27 :   ulong old_lamports_per_signature = fd_bank_rbh_lamports_per_sig_get( bank );
     355             : 
     356          27 :   fd_fee_rate_governor_t me = {
     357          27 :     .target_signatures_per_slot    = base_fee_rate_governor->target_signatures_per_slot,
     358          27 :     .target_lamports_per_signature = base_fee_rate_governor->target_lamports_per_signature,
     359          27 :     .max_lamports_per_signature    = base_fee_rate_governor->max_lamports_per_signature,
     360          27 :     .min_lamports_per_signature    = base_fee_rate_governor->min_lamports_per_signature,
     361          27 :     .burn_percent                  = base_fee_rate_governor->burn_percent
     362          27 :   };
     363             : 
     364          27 :   ulong new_lamports_per_signature = 0;
     365          27 :   if( me.target_signatures_per_slot > 0 ) {
     366           0 :     me.min_lamports_per_signature = fd_ulong_max( 1UL, (ulong)(me.target_lamports_per_signature / 2) );
     367           0 :     me.max_lamports_per_signature = me.target_lamports_per_signature * 10;
     368           0 :     ulong desired_lamports_per_signature = fd_ulong_min(
     369           0 :       me.max_lamports_per_signature,
     370           0 :       fd_ulong_max(
     371           0 :         me.min_lamports_per_signature,
     372           0 :         me.target_lamports_per_signature
     373           0 :         * fd_ulong_min(latest_signatures_per_slot, (ulong)UINT_MAX)
     374           0 :         / me.target_signatures_per_slot
     375           0 :       )
     376           0 :     );
     377           0 :     long gap = (long)desired_lamports_per_signature - (long)old_lamports_per_signature;
     378           0 :     if ( gap == 0 ) {
     379           0 :       new_lamports_per_signature = desired_lamports_per_signature;
     380           0 :     } else {
     381           0 :       long gap_adjust = (long)(fd_ulong_max( 1UL, (ulong)(me.target_lamports_per_signature / 20) ))
     382           0 :         * (gap != 0)
     383           0 :         * (gap > 0 ? 1 : -1);
     384           0 :       new_lamports_per_signature = fd_ulong_min(
     385           0 :         me.max_lamports_per_signature,
     386           0 :         fd_ulong_max(
     387           0 :           me.min_lamports_per_signature,
     388           0 :           (ulong)((long)old_lamports_per_signature + gap_adjust)
     389           0 :         )
     390           0 :       );
     391           0 :     }
     392          27 :   } else {
     393          27 :     new_lamports_per_signature = base_fee_rate_governor->target_lamports_per_signature;
     394          27 :     me.min_lamports_per_signature = me.target_lamports_per_signature;
     395          27 :     me.max_lamports_per_signature = me.target_lamports_per_signature;
     396          27 :   }
     397          27 :   fd_bank_fee_rate_governor_set( bank, me );
     398          27 :   fd_bank_rbh_lamports_per_sig_set( bank, new_lamports_per_signature );
     399          27 : }
     400             : 
     401             : /******************************************************************************/
     402             : /* Epoch Boundary                                                             */
     403             : /******************************************************************************/
     404             : 
     405             : static void
     406           9 : fd_runtime_refresh_previous_stake_values( fd_bank_t * bank ) {
     407           9 :   fd_vote_states_t * vote_states = fd_bank_vote_states_locking_modify( bank );
     408           9 :   fd_vote_states_iter_t iter_[1];
     409           9 :   for( fd_vote_states_iter_t * iter = fd_vote_states_iter_init( iter_, vote_states );
     410           9 :        !fd_vote_states_iter_done( iter );
     411           9 :        fd_vote_states_iter_next( iter ) ) {
     412           0 :     fd_vote_state_ele_t * vote_state = fd_vote_states_iter_ele( iter );
     413           0 :     vote_state->stake_t_2 = vote_state->stake_t_1;
     414           0 :     vote_state->stake_t_1 = vote_state->stake;
     415           0 :   }
     416           9 :   fd_bank_vote_states_end_locking_modify( bank );
     417           9 : }
     418             : 
     419             : /* Replace the vote states for T-2 (vote_states_prev_prev) with the vote
     420             :    states for T-1 (vote_states_prev) */
     421             : 
     422             : static void
     423           9 : fd_runtime_update_vote_states_prev_prev( fd_bank_t * bank ) {
     424             : 
     425           9 :   fd_vote_states_t *       vote_states_prev_prev = fd_bank_vote_states_prev_prev_locking_modify( bank );
     426           9 :   fd_vote_states_t const * vote_states_prev      = fd_bank_vote_states_prev_locking_query( bank );
     427           9 :   fd_memcpy( vote_states_prev_prev, vote_states_prev, fd_bank_vote_states_footprint );
     428           9 :   fd_bank_vote_states_prev_prev_end_locking_modify( bank );
     429           9 :   fd_bank_vote_states_prev_end_locking_query( bank );
     430           9 : }
     431             : 
     432             : /* Replace the vote states for T-1 (vote_states_prev) with the vote
     433             :    states for T-1 (vote_states) */
     434             : 
     435             : static void
     436           9 : fd_runtime_update_vote_states_prev( fd_bank_t * bank ) {
     437           9 :   fd_vote_states_t *       vote_states_prev = fd_bank_vote_states_prev_locking_modify( bank );
     438           9 :   fd_vote_states_t const * vote_states      = fd_bank_vote_states_locking_query( bank );
     439           9 :   fd_memcpy( vote_states_prev, vote_states, fd_bank_vote_states_footprint );
     440           9 :   fd_bank_vote_states_prev_end_locking_modify( bank );
     441           9 :   fd_bank_vote_states_end_locking_query( bank );
     442           9 : }
     443             : 
     444             : /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6704 */
     445             : static void
     446             : fd_apply_builtin_program_feature_transitions( fd_bank_t *               bank,
     447             :                                               fd_accdb_user_t *         accdb,
     448             :                                               fd_funk_txn_xid_t const * xid,
     449             :                                               fd_runtime_stack_t *      runtime_stack,
     450           9 :                                               fd_capture_ctx_t *        capture_ctx ) {
     451             :   /* TODO: Set the upgrade authority properly from the core bpf migration config. Right now it's set to None.
     452             : 
     453             :      Migrate any necessary stateless builtins to core BPF. So far,
     454             :      the only "stateless" builtin is the Feature program. Beginning
     455             :      checks in the migrate_builtin_to_core_bpf function will fail if the
     456             :      program has already been migrated to BPF. */
     457             : 
     458           9 :   fd_builtin_program_t const * builtins = fd_builtins();
     459         117 :   for( ulong i=0UL; i<fd_num_builtins(); i++ ) {
     460             :     /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6732-L6751 */
     461         108 :     if( builtins[i].core_bpf_migration_config && FD_FEATURE_ACTIVE_OFFSET( fd_bank_slot_get( bank ), fd_bank_features_query( bank ), builtins[i].core_bpf_migration_config->enable_feature_offset ) ) {
     462           0 :       FD_BASE58_ENCODE_32_BYTES( builtins[i].pubkey->key, pubkey_b58 );
     463           0 :       FD_LOG_DEBUG(( "Migrating builtin program %s to core BPF", pubkey_b58 ));
     464           0 :       fd_migrate_builtin_to_core_bpf( bank, accdb, xid, runtime_stack, builtins[i].core_bpf_migration_config, capture_ctx );
     465           0 :     }
     466             :     /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6753-L6774 */
     467         108 :     if( builtins[i].enable_feature_offset!=NO_ENABLE_FEATURE_ID && FD_FEATURE_JUST_ACTIVATED_OFFSET( bank, builtins[i].enable_feature_offset ) ) {
     468           0 :       FD_BASE58_ENCODE_32_BYTES( builtins[i].pubkey->key, pubkey_b58 );
     469           0 :       FD_LOG_DEBUG(( "Enabling builtin program %s", pubkey_b58 ));
     470           0 :       fd_write_builtin_account( bank, accdb, xid, capture_ctx, *builtins[i].pubkey, builtins[i].data,strlen(builtins[i].data) );
     471           0 :     }
     472         108 :   }
     473             : 
     474             :   /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6776-L6793 */
     475           9 :   fd_stateless_builtin_program_t const * stateless_builtins = fd_stateless_builtins();
     476          27 :   for( ulong i=0UL; i<fd_num_stateless_builtins(); i++ ) {
     477          18 :     if( stateless_builtins[i].core_bpf_migration_config && FD_FEATURE_ACTIVE_OFFSET( fd_bank_slot_get( bank ), fd_bank_features_query( bank ), stateless_builtins[i].core_bpf_migration_config->enable_feature_offset ) ) {
     478           0 :       FD_BASE58_ENCODE_32_BYTES( stateless_builtins[i].pubkey->key, pubkey_b58 );
     479           0 :       FD_LOG_DEBUG(( "Migrating stateless builtin program %s to core BPF", pubkey_b58 ));
     480           0 :       fd_migrate_builtin_to_core_bpf( bank, accdb, xid, runtime_stack, stateless_builtins[i].core_bpf_migration_config, capture_ctx );
     481           0 :     }
     482          18 :   }
     483             : 
     484             :   /* https://github.com/anza-xyz/agave/blob/c1080de464cfb578c301e975f498964b5d5313db/runtime/src/bank.rs#L6795-L6805 */
     485           9 :   fd_precompile_program_t const * precompiles = fd_precompiles();
     486          36 :   for( ulong i=0UL; i<fd_num_precompiles(); i++ ) {
     487          27 :     if( precompiles[i].feature_offset != NO_ENABLE_FEATURE_ID && FD_FEATURE_JUST_ACTIVATED_OFFSET( bank, precompiles[i].feature_offset ) ) {
     488           0 :       fd_write_builtin_account( bank, accdb, xid, capture_ctx, *precompiles[i].pubkey, "", 0 );
     489           0 :     }
     490          27 :   }
     491           9 : }
     492             : 
     493             : static void
     494             : fd_feature_activate( fd_bank_t *               bank,
     495             :                      fd_accdb_user_t *         accdb,
     496             :                      fd_funk_txn_xid_t const * xid,
     497             :                      fd_capture_ctx_t *        capture_ctx,
     498             :                      fd_feature_id_t const *   id,
     499        2277 :                      fd_pubkey_t const *       addr ) {
     500        2277 :   fd_features_t * features = fd_bank_features_modify( bank );
     501             : 
     502        2277 :   if( id->reverted==1 ) return;
     503             : 
     504        2187 :   fd_funk_t * funk = fd_accdb_user_v1_funk( accdb );
     505        2187 :   fd_txn_account_t acct_rec[1];
     506        2187 :   int err = fd_txn_account_init_from_funk_readonly( acct_rec, addr, funk, xid );
     507        2187 :   if( FD_UNLIKELY( err != FD_ACC_MGR_SUCCESS ) ) {
     508        2187 :     return;
     509        2187 :   }
     510             : 
     511           0 :   FD_BASE58_ENCODE_32_BYTES( addr->uc, addr_b58 );
     512           0 :   fd_feature_t feature[1];
     513           0 :   int decode_err = 0;
     514           0 :   if( FD_UNLIKELY( !fd_bincode_decode_static( feature, feature, fd_txn_account_get_data( acct_rec ), fd_txn_account_get_data_len( acct_rec ), &decode_err ) ) ) {
     515           0 :     FD_LOG_WARNING(( "Failed to decode feature account %s (%d)", addr_b58, decode_err ));
     516           0 :     return;
     517           0 :   }
     518             : 
     519           0 :   if( feature->has_activated_at ) {
     520           0 :     FD_LOG_DEBUG(( "feature already activated - acc: %s, slot: %lu", addr_b58, feature->activated_at ));
     521           0 :     fd_features_set( features, id, feature->activated_at);
     522           0 :   } else {
     523           0 :     FD_LOG_DEBUG(( "Feature %s not activated at %lu, activating", addr_b58, feature->activated_at ));
     524             : 
     525           0 :     fd_txn_account_t modify_acct_rec[1];
     526           0 :     fd_funk_rec_prepare_t modify_acct_prepare = {0};
     527           0 :     int ok = !!fd_txn_account_init_from_funk_mutable( modify_acct_rec, addr, accdb, xid, 0, 0UL, &modify_acct_prepare );
     528           0 :     if( FD_UNLIKELY( !ok ) ) return;
     529             : 
     530           0 :     fd_lthash_value_t prev_hash[1];
     531           0 :     fd_hashes_account_lthash(
     532           0 :       addr,
     533           0 :       fd_txn_account_get_meta( modify_acct_rec ),
     534           0 :       fd_txn_account_get_data( modify_acct_rec ),
     535           0 :       prev_hash );
     536             : 
     537           0 :     feature->has_activated_at = 1;
     538           0 :     feature->activated_at     = fd_bank_slot_get( bank );
     539           0 :     fd_bincode_encode_ctx_t encode_ctx = {
     540           0 :       .data    = fd_txn_account_get_data_mut( modify_acct_rec ),
     541           0 :       .dataend = fd_txn_account_get_data_mut( modify_acct_rec ) + fd_txn_account_get_data_len( modify_acct_rec ),
     542           0 :     };
     543           0 :     int encode_err = fd_feature_encode( feature, &encode_ctx );
     544           0 :     if( FD_UNLIKELY( encode_err != FD_BINCODE_SUCCESS ) ) {
     545           0 :       FD_LOG_ERR(( "Failed to encode feature account %s (%d)", addr_b58, decode_err ));
     546           0 :     }
     547             : 
     548           0 :     fd_hashes_update_lthash( modify_acct_rec->pubkey, modify_acct_rec->meta, prev_hash, bank, capture_ctx );
     549           0 :     fd_txn_account_mutable_fini( modify_acct_rec, accdb, &modify_acct_prepare );
     550           0 :   }
     551           0 : }
     552             : 
     553             : static void
     554             : fd_features_activate( fd_bank_t *               bank,
     555             :                       fd_accdb_user_t  *        accdb,
     556             :                       fd_funk_txn_xid_t const * xid,
     557           9 :                       fd_capture_ctx_t *        capture_ctx ) {
     558           9 :   for( fd_feature_id_t const * id = fd_feature_iter_init();
     559        2286 :                                    !fd_feature_iter_done( id );
     560        2277 :                                id = fd_feature_iter_next( id ) ) {
     561        2277 :     fd_feature_activate( bank, accdb, xid, capture_ctx, id, &id->id );
     562        2277 :   }
     563           9 : }
     564             : 
     565             : /* SIMD-0194: deprecate_rent_exemption_threshold
     566             :    https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5322-L5329 */
     567             : static void
     568             : deprecate_rent_exemption_threshold( fd_bank_t *               bank,
     569             :                                     fd_accdb_user_t *         accdb,
     570             :                                     fd_funk_txn_xid_t const * xid,
     571             :                                     fd_capture_ctx_t *        capture_ctx,
     572           3 :                                     fd_funk_t *               funk ) {
     573           3 :   fd_rent_t rent[1] = {0};
     574           3 :   if( FD_UNLIKELY( !fd_sysvar_rent_read( funk, xid, rent ) ) ) {
     575           0 :     FD_LOG_CRIT(( "fd_sysvar_rent_read failed" ));
     576           0 :   }
     577           3 :   rent->lamports_per_uint8_year = fd_rust_cast_double_to_ulong(
     578           3 :     (double)rent->lamports_per_uint8_year * rent->exemption_threshold );
     579           3 :   rent->exemption_threshold     = FD_SIMD_0194_NEW_RENT_EXEMPTION_THRESHOLD;
     580             : 
     581             :   /* We don't refresh the sysvar cache here. The cache is refreshed in
     582             :      fd_sysvar_cache_restore, which is called at the start of every block
     583             :      in fd_runtime_block_execute_prepare, after this function. */
     584           3 :   fd_sysvar_rent_write( bank, accdb, xid, capture_ctx, rent );
     585           3 :   fd_bank_rent_set( bank, *rent );
     586           3 : }
     587             : 
     588             : /* Starting a new epoch.
     589             :   New epoch:        T
     590             :   Just ended epoch: T-1
     591             :   Epoch before:     T-2
     592             : 
     593             :   In this function:
     594             :   - stakes in T-2 (vote_states_prev_prev) should be replaced by T-1 (vote_states_prev)
     595             :   - stakes at T-1 (vote_states_prev) should be replaced by updated stakes at T (vote_states)
     596             :   - leader schedule should be calculated using new T-2 stakes (vote_states_prev_prev)
     597             : 
     598             :   Invariant during an epoch T:
     599             :   vote_states_prev holds the stakes at T-1
     600             :   vote_states_prev_prev holds the stakes at T-2
     601             :  */
     602             : /* process for the start of a new epoch */
     603             : static void
     604             : fd_runtime_process_new_epoch( fd_banks_t *              banks,
     605             :                               fd_bank_t *               bank,
     606             :                               fd_accdb_user_t *         accdb,
     607             :                               fd_funk_txn_xid_t const * xid,
     608             :                               fd_capture_ctx_t *        capture_ctx,
     609             :                               ulong                     parent_epoch,
     610           9 :                               fd_runtime_stack_t *      runtime_stack ) {
     611             : 
     612           9 :   FD_LOG_NOTICE(( "fd_process_new_epoch start, epoch: %lu, slot: %lu", fd_bank_epoch_get( bank ), fd_bank_slot_get( bank ) ));
     613             : 
     614           9 :   runtime_stack->stakes.prev_vote_credits_used = 0;
     615             : 
     616           9 :   fd_stake_delegations_t const * stake_delegations = fd_bank_stake_delegations_frontier_query( banks, bank );
     617           9 :   if( FD_UNLIKELY( !stake_delegations ) ) {
     618           0 :     FD_LOG_CRIT(( "stake_delegations is NULL" ));
     619           0 :   }
     620             : 
     621           9 :   long start = fd_log_wallclock();
     622             : 
     623           9 :   ulong const slot = fd_bank_slot_get( bank );
     624             : 
     625             :   /* Activate new features
     626             :      https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6587-L6598 */
     627             : 
     628           9 :   fd_funk_t * funk = fd_accdb_user_v1_funk( accdb );
     629           9 :   fd_features_activate( bank, accdb, xid, capture_ctx );
     630           9 :   fd_features_restore( bank, funk, xid );
     631             : 
     632             :   /* SIMD-0194: deprecate_rent_exemption_threshold
     633             :      https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5322-L5329 */
     634           9 :   if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, deprecate_rent_exemption_threshold ) ) ) {
     635           3 :     deprecate_rent_exemption_threshold( bank, accdb, xid, capture_ctx, funk );
     636           3 :   }
     637             : 
     638             :   /* Apply builtin program feature transitions
     639             :      https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6621-L6624 */
     640             : 
     641           9 :   fd_apply_builtin_program_feature_transitions( bank, accdb, xid, runtime_stack, capture_ctx );
     642             : 
     643             :   /* Get the new rate activation epoch */
     644           9 :   int _err[1];
     645           9 :   ulong   new_rate_activation_epoch_val = 0UL;
     646           9 :   ulong * new_rate_activation_epoch     = &new_rate_activation_epoch_val;
     647           9 :   int is_some = fd_new_warmup_cooldown_rate_epoch(
     648           9 :       fd_bank_epoch_schedule_query( bank ),
     649           9 :       fd_bank_features_query( bank ),
     650           9 :       slot,
     651           9 :       new_rate_activation_epoch,
     652           9 :       _err );
     653           9 :   if( FD_UNLIKELY( !is_some ) ) {
     654           9 :     new_rate_activation_epoch = NULL;
     655           9 :   }
     656             : 
     657             :   /* Updates stake history sysvar accumulated values and recomputes
     658             :      stake delegations for vote accounts. */
     659             : 
     660           9 :   fd_stakes_activate_epoch( bank, accdb, xid, capture_ctx, stake_delegations, new_rate_activation_epoch );
     661             : 
     662             :   /* Distribute rewards.  This involves calculating the rewards for
     663             :      every vote and stake account. */
     664             : 
     665           9 :   fd_hash_t const * parent_blockhash = fd_blockhashes_peek_last_hash( fd_bank_block_hash_queue_query( bank ) );
     666           9 :   fd_begin_partitioned_rewards( bank,
     667           9 :                                 accdb,
     668           9 :                                 xid,
     669           9 :                                 runtime_stack,
     670           9 :                                 capture_ctx,
     671           9 :                                 stake_delegations,
     672           9 :                                 parent_blockhash,
     673           9 :                                 parent_epoch );
     674             : 
     675             :   /* The Agave client handles updating their stakes cache with a call to
     676             :      update_epoch_stakes() which keys stakes by the leader schedule
     677             :      epochs and retains up to 6 epochs of stakes.  However, to correctly
     678             :      calculate the leader schedule, we just need to maintain the vote
     679             :      states for the current epoch, the previous epoch, and the one
     680             :      before that.
     681             :      https://github.com/anza-xyz/agave/blob/v3.0.4/runtime/src/bank.rs#L2175
     682             :   */
     683             : 
     684             :   /* We want to cache the stake values for T-1 and T-2 in the forward
     685             :      looking vote states.  This is done as an optimization for tower
     686             :      calculations (T-1 stake) and clock calculation (T-2 stake).
     687             :      We use the current stake to populate the T-1 stake and the T-1
     688             :      stake to populate the T-2 stake. */
     689           9 :   fd_runtime_refresh_previous_stake_values( bank );
     690             : 
     691             :   /* Update vote_states_prev_prev with vote_states_prev */
     692             : 
     693           9 :   fd_runtime_update_vote_states_prev_prev( bank );
     694             : 
     695             :   /* Update vote_states_prev with vote_states */
     696             : 
     697           9 :   fd_runtime_update_vote_states_prev( bank );
     698             : 
     699             :   /* Now that our stakes caches have been updated, we can calculate the
     700             :      leader schedule for the upcoming epoch epoch using our new
     701             :      vote_states_prev_prev (stakes for T-2). */
     702             : 
     703           9 :   fd_runtime_update_leaders( bank, runtime_stack );
     704             : 
     705           9 :   long end = fd_log_wallclock();
     706           9 :   FD_LOG_NOTICE(("fd_process_new_epoch took %ld ns", end - start));
     707             : 
     708           9 : }
     709             : 
     710             : static void
     711             : fd_runtime_block_pre_execute_process_new_epoch( fd_banks_t *              banks,
     712             :                                                 fd_bank_t *               bank,
     713             :                                                 fd_accdb_user_t *         accdb,
     714             :                                                 fd_funk_txn_xid_t const * xid,
     715             :                                                 fd_capture_ctx_t *        capture_ctx,
     716             :                                                 fd_runtime_stack_t *      runtime_stack,
     717          27 :                                                 int *                     is_epoch_boundary ) {
     718             : 
     719          27 :   ulong const slot = fd_bank_slot_get( bank );
     720          27 :   if( slot != 0UL ) {
     721          27 :     fd_epoch_schedule_t const * epoch_schedule = fd_bank_epoch_schedule_query( bank );
     722             : 
     723          27 :     ulong prev_epoch = fd_slot_to_epoch( epoch_schedule, fd_bank_parent_slot_get( bank ), NULL );
     724          27 :     ulong slot_idx;
     725          27 :     ulong new_epoch  = fd_slot_to_epoch( epoch_schedule, slot, &slot_idx );
     726          27 :     if( FD_UNLIKELY( slot_idx==1UL && new_epoch==0UL ) ) {
     727             :       /* The block after genesis has a height of 1. */
     728           3 :       fd_bank_block_height_set( bank, 1UL );
     729           3 :     }
     730             : 
     731          27 :     if( FD_UNLIKELY( prev_epoch<new_epoch || !slot_idx ) ) {
     732           9 :       FD_LOG_DEBUG(( "Epoch boundary starting" ));
     733           9 :       fd_runtime_process_new_epoch( banks, bank, accdb, xid, capture_ctx, prev_epoch, runtime_stack );
     734           9 :       *is_epoch_boundary = 1;
     735           9 :     }
     736          27 :   } else {
     737           0 :     *is_epoch_boundary = 0;
     738           0 :   }
     739             : 
     740          27 :   if( FD_LIKELY( fd_bank_slot_get( bank )!=0UL ) ) {
     741          27 :     fd_distribute_partitioned_epoch_rewards( bank, accdb, xid, capture_ctx );
     742          27 :   }
     743          27 : }
     744             : 
     745             : 
     746             : static void
     747             : fd_runtime_block_sysvar_update_pre_execute( fd_bank_t *               bank,
     748             :                                             fd_accdb_user_t *         accdb,
     749             :                                             fd_funk_txn_xid_t const * xid,
     750             :                                             fd_runtime_stack_t *      runtime_stack,
     751          27 :                                             fd_capture_ctx_t *        capture_ctx ) {
     752             :   // let (fee_rate_governor, fee_components_time_us) = measure_us!(
     753             :   //     FeeRateGovernor::new_derived(&parent.fee_rate_governor, parent.signature_count())
     754             :   // );
     755             :   /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L1312-L1314 */
     756             : 
     757          27 :   fd_runtime_new_fee_rate_governor_derived( bank, fd_bank_parent_signature_cnt_get( bank ) );
     758             : 
     759          27 :   fd_epoch_schedule_t const * epoch_schedule = fd_bank_epoch_schedule_query( bank );
     760          27 :   ulong                       parent_epoch   = fd_slot_to_epoch( epoch_schedule, fd_bank_parent_slot_get( bank ), NULL );
     761          27 :   fd_sysvar_clock_update( bank, accdb, xid, capture_ctx, runtime_stack, &parent_epoch );
     762             : 
     763             :   // It has to go into the current txn previous info but is not in slot 0
     764          27 :   if( fd_bank_slot_get( bank ) != 0 ) {
     765          27 :     fd_sysvar_slot_hashes_update( bank, accdb, xid, capture_ctx );
     766          27 :   }
     767          27 :   fd_sysvar_last_restart_slot_update( bank, accdb, xid, capture_ctx, fd_bank_last_restart_slot_get( bank ).slot );
     768          27 : }
     769             : 
     770             : int
     771             : fd_runtime_load_txn_address_lookup_tables(
     772             :     fd_txn_t const *          txn,
     773             :     uchar const *             payload,
     774             :     fd_funk_t *               funk,
     775             :     fd_funk_txn_xid_t const * xid,
     776             :     ulong                     slot,
     777             :     fd_slot_hash_t const *    hashes, /* deque */
     778           0 :     fd_acct_addr_t *          out_accts_alt ) {
     779             : 
     780           0 :   if( FD_LIKELY( txn->transaction_version!=FD_TXN_V0 ) ) return FD_RUNTIME_EXECUTE_SUCCESS;
     781             : 
     782           0 :   fd_alut_interp_t interp[1];
     783           0 :   fd_alut_interp_new(
     784           0 :       interp,
     785           0 :       out_accts_alt,
     786           0 :       txn,
     787           0 :       payload,
     788           0 :       hashes,
     789           0 :       slot );
     790             : 
     791           0 :   fd_txn_acct_addr_lut_t const * addr_luts = fd_txn_get_address_tables_const( txn );
     792           0 :   for( ulong i=0UL; i<txn->addr_table_lookup_cnt; i++ ) {
     793           0 :     fd_txn_acct_addr_lut_t const * addr_lut = &addr_luts[i];
     794           0 :     fd_pubkey_t addr_lut_acc = FD_LOAD( fd_pubkey_t, payload+addr_lut->addr_off );
     795             : 
     796             :     /* https://github.com/anza-xyz/agave/blob/368ea563c423b0a85cc317891187e15c9a321521/accounts-db/src/accounts.rs#L90-L94 */
     797           0 :     fd_txn_account_t addr_lut_rec[1];
     798           0 :     int db_err = fd_txn_account_init_from_funk_readonly(
     799           0 :         addr_lut_rec, &addr_lut_acc, funk,  xid );
     800           0 :     if( FD_UNLIKELY( db_err!=FD_ACC_MGR_SUCCESS ) ) {
     801           0 :       return FD_RUNTIME_TXN_ERR_ADDRESS_LOOKUP_TABLE_NOT_FOUND;
     802           0 :     }
     803             : 
     804           0 :     int err = fd_alut_interp_next(
     805           0 :         interp,
     806           0 :         &addr_lut_acc,
     807           0 :         fd_txn_account_get_owner   ( addr_lut_rec ),
     808           0 :         fd_txn_account_get_data    ( addr_lut_rec ),
     809           0 :         fd_txn_account_get_data_len( addr_lut_rec ) );
     810           0 :     if( FD_UNLIKELY( err ) ) return err;
     811           0 :   }
     812             : 
     813           0 :   fd_alut_interp_delete( interp );
     814             : 
     815           0 :   return FD_RUNTIME_EXECUTE_SUCCESS;
     816           0 : }
     817             : 
     818             : void
     819             : fd_runtime_block_execute_prepare( fd_banks_t *         banks,
     820             :                                   fd_bank_t *          bank,
     821             :                                   fd_accdb_user_t  *   accdb,
     822             :                                   fd_runtime_stack_t * runtime_stack,
     823             :                                   fd_capture_ctx_t *   capture_ctx,
     824          27 :                                   int *                is_epoch_boundary ) {
     825             : 
     826          27 :   fd_funk_txn_xid_t const xid = { .ul = { fd_bank_slot_get( bank ), bank->idx } };
     827             : 
     828          27 :   fd_runtime_block_pre_execute_process_new_epoch( banks, bank, accdb, &xid, capture_ctx, runtime_stack, is_epoch_boundary );
     829             : 
     830          27 :   fd_bank_execution_fees_set( bank, 0UL );
     831          27 :   fd_bank_priority_fees_set( bank, 0UL );
     832          27 :   fd_bank_signature_count_set( bank, 0UL );
     833          27 :   fd_bank_total_compute_units_used_set( bank, 0UL );
     834             : 
     835          27 :   if( FD_LIKELY( fd_bank_slot_get( bank ) ) ) {
     836          27 :     fd_cost_tracker_t * cost_tracker = fd_bank_cost_tracker_locking_modify( bank );
     837          27 :     FD_TEST( cost_tracker );
     838          27 :     fd_cost_tracker_init( cost_tracker, fd_bank_features_query( bank ), fd_bank_slot_get( bank ) );
     839          27 :     fd_bank_cost_tracker_end_locking_modify( bank );
     840          27 :   }
     841             : 
     842          27 :   fd_runtime_block_sysvar_update_pre_execute( bank, accdb, &xid, runtime_stack, capture_ctx );
     843             : 
     844          27 :   fd_funk_t * funk = fd_accdb_user_v1_funk( accdb );
     845          27 :   if( FD_UNLIKELY( !fd_sysvar_cache_restore( bank, funk, &xid ) ) ) {
     846           0 :     FD_LOG_ERR(( "Failed to restore sysvar cache" ));
     847           0 :   }
     848          27 : }
     849             : 
     850             : static void
     851             : fd_runtime_update_bank_hash( fd_bank_t *        bank,
     852           0 :                              fd_capture_ctx_t * capture_ctx ) {
     853             :   /* Save the previous bank hash, and the parents signature count */
     854           0 :   fd_hash_t const * prev_bank_hash = NULL;
     855           0 :   if( FD_LIKELY( fd_bank_slot_get( bank )!=0UL ) ) {
     856           0 :     prev_bank_hash = fd_bank_bank_hash_query( bank );
     857           0 :     fd_bank_prev_bank_hash_set( bank, *prev_bank_hash );
     858           0 :   } else {
     859           0 :     prev_bank_hash = fd_bank_prev_bank_hash_query( bank );
     860           0 :   }
     861             : 
     862           0 :   fd_bank_parent_signature_cnt_set( bank, fd_bank_signature_count_get( bank ) );
     863             : 
     864             :   /* Compute the new bank hash */
     865           0 :   fd_lthash_value_t const * lthash = fd_bank_lthash_locking_query( bank );
     866           0 :   fd_hash_t new_bank_hash[1] = { 0 };
     867           0 :   fd_hashes_hash_bank(
     868           0 :       lthash,
     869           0 :       prev_bank_hash,
     870           0 :       (fd_hash_t *)fd_bank_poh_query( bank )->hash,
     871           0 :       fd_bank_signature_count_get( bank ),
     872           0 :       new_bank_hash );
     873             : 
     874             :   /* Update the bank hash */
     875           0 :   fd_bank_bank_hash_set( bank, *new_bank_hash );
     876             : 
     877           0 :   if( capture_ctx != NULL && capture_ctx->capture != NULL &&
     878           0 :     fd_bank_slot_get( bank )>=capture_ctx->solcap_start_slot ) {
     879             : 
     880           0 :     uchar lthash_hash[FD_HASH_FOOTPRINT];
     881           0 :     fd_blake3_hash(lthash->bytes, FD_LTHASH_LEN_BYTES, lthash_hash );
     882           0 :     fd_capture_link_write_bank_preimage(
     883           0 :       capture_ctx,
     884           0 :       fd_bank_slot_get( bank ),
     885           0 :       (fd_hash_t *)new_bank_hash->hash,
     886           0 :       (fd_hash_t *)fd_bank_prev_bank_hash_query( bank ),
     887           0 :       (fd_hash_t *)lthash_hash,
     888           0 :       (fd_hash_t *)fd_bank_poh_query( bank )->hash,
     889           0 :       fd_bank_signature_count_get( bank ) );
     890           0 :   }
     891             : 
     892           0 :   fd_bank_lthash_end_locking_query( bank );
     893           0 : }
     894             : 
     895             : /******************************************************************************/
     896             : /* Transaction Level Execution Management                                     */
     897             : /******************************************************************************/
     898             : 
     899             : /* fd_runtime_pre_execute_check is responsible for conducting many of the
     900             :    transaction sanitization checks. */
     901             : 
     902             : static inline int
     903             : fd_runtime_pre_execute_check( fd_runtime_t *      runtime,
     904             :                               fd_bank_t *         bank,
     905             :                               fd_txn_in_t const * txn_in,
     906           0 :                               fd_txn_out_t *      txn_out ) {
     907             : 
     908             :   /* Set up the core account keys. These are the account keys directly
     909             :      passed in via the serialized transaction, represented as an array.
     910             :      Note that this does not include additional keys referenced in
     911             :      address lookup tables. */
     912           0 :   fd_executor_setup_txn_account_keys( txn_in, txn_out );
     913             : 
     914           0 :   int err;
     915             : 
     916             :   /* https://github.com/anza-xyz/agave/blob/16de8b75ebcd57022409b422de557dd37b1de8db/sdk/src/transaction/sanitized.rs#L263-L275
     917             :      TODO: Agave's precompile verification is done at the slot level, before batching and executing transactions. This logic should probably
     918             :      be moved in the future. The Agave call heirarchy looks something like this:
     919             :             process_single_slot
     920             :                    v
     921             :             confirm_full_slot
     922             :                    v
     923             :             confirm_slot_entries --------------------------------------------------->
     924             :                    v                               v                                v
     925             :             verify_transaction    ComputeBudget::process_instruction         process_entries
     926             :                    v                                                                v
     927             :             verify_precompiles                                                process_batches
     928             :                                                                                     v
     929             :                                                                                    ...
     930             :                                                                                     v
     931             :                                                                         load_and_execute_transactions
     932             :                                                                                     v
     933             :                                                                                    ...
     934             :                                                                                     v
     935             :                                                                               load_accounts --> load_transaction_accounts
     936             :                                                                                     v
     937             :                                                                        general transaction execution
     938             : 
     939             :   */
     940             : 
     941           0 : # if FD_HAS_FLATCC
     942           0 :   uchar dump_txn = !!( runtime->log.capture_ctx &&
     943           0 :                        fd_bank_slot_get( bank ) >= runtime->log.capture_ctx->dump_proto_start_slot &&
     944           0 :                        runtime->log.capture_ctx->dump_txn_to_pb );
     945           0 :   if( FD_UNLIKELY( dump_txn ) ) {
     946           0 :     fd_dump_txn_to_protobuf( runtime, bank, txn_in, txn_out );
     947           0 :   }
     948           0 : # endif
     949             : 
     950             :   /* Verify the transaction. For now, this step only involves processing
     951             :      the compute budget instructions. */
     952           0 :   err = fd_executor_verify_transaction( bank, txn_in, txn_out );
     953           0 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     954           0 :     txn_out->err.is_committable = 0;
     955           0 :     return err;
     956           0 :   }
     957             : 
     958             :   /* Resolve and verify ALUT-referenced account keys, if applicable */
     959           0 :   err = fd_executor_setup_txn_alut_account_keys( runtime, bank, txn_in, txn_out );
     960           0 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     961           0 :     txn_out->err.is_committable = 0;
     962           0 :     return err;
     963           0 :   }
     964             : 
     965             :   /* Set up the transaction accounts and other txn ctx metadata */
     966           0 :   fd_executor_setup_accounts_for_txn( runtime, bank, txn_in, txn_out );
     967             : 
     968             :   /* Post-sanitization checks. Called from prepare_sanitized_batch()
     969             :      which, for now, only is used to lock the accounts and perform a
     970             :      couple basic validations.
     971             :      https://github.com/anza-xyz/agave/blob/838c1952595809a31520ff1603a13f2c9123aa51/accounts-db/src/account_locks.rs#L118 */
     972           0 :   err = fd_executor_validate_account_locks( bank, txn_out );
     973           0 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     974           0 :     txn_out->err.is_committable = 0;
     975           0 :     return err;
     976           0 :   }
     977             : 
     978             :   /* load_and_execute_transactions() -> check_transactions()
     979             :      https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/runtime/src/bank.rs#L3667-L3672 */
     980           0 :   err = fd_executor_check_transactions( runtime, bank, txn_in, txn_out );
     981           0 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     982           0 :     txn_out->err.is_committable = 0;
     983           0 :     return err;
     984           0 :   }
     985             : 
     986             :   /* load_and_execute_sanitized_transactions() -> validate_fees() ->
     987             :      validate_transaction_fee_payer()
     988             :      https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/svm/src/transaction_processor.rs#L236-L249 */
     989           0 :   err = fd_executor_validate_transaction_fee_payer( runtime, bank, txn_in, txn_out );
     990           0 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
     991           0 :     txn_out->err.is_committable = 0;
     992           0 :     return err;
     993           0 :   }
     994             : 
     995           0 :   txn_out->details.exec_start_timestamp = fd_tickcount();
     996             : 
     997             :   /* https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/svm/src/transaction_processor.rs#L284-L296 */
     998           0 :   err = fd_executor_load_transaction_accounts( runtime, bank, txn_in, txn_out );
     999           0 :   if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
    1000             :     /* Regardless of whether transaction accounts were loaded successfully, the transaction is
    1001             :        included in the block and transaction fees are collected.
    1002             :        https://github.com/anza-xyz/agave/blob/v2.1.6/svm/src/transaction_processor.rs#L341-L357 */
    1003           0 :     txn_out->err.is_fees_only = 1;
    1004             : 
    1005             :     /* If the transaction fails to load, the "rollback" accounts will include one of the following:
    1006             :         1. Nonce account only
    1007             :         2. Fee payer only
    1008             :         3. Nonce account + fee payer
    1009             : 
    1010             :         Because the cost tracker uses the loaded account data size in block cost calculations, we need to
    1011             :         make sure our calculated loaded accounts data size is conformant with Agave's.
    1012             :         https://github.com/anza-xyz/agave/blob/v2.1.14/runtime/src/bank.rs#L4116
    1013             : 
    1014             :         In any case, we should always add the dlen of the fee payer. */
    1015           0 :     txn_out->details.loaded_accounts_data_size = txn_out->accounts.metas[ FD_FEE_PAYER_TXN_IDX ]->dlen;
    1016             : 
    1017             :     /* Special case handling for if a nonce account is present in the transaction. */
    1018           0 :     if( txn_out->accounts.nonce_idx_in_txn!=ULONG_MAX ) {
    1019             :       /* If the nonce account is not the fee payer, then we separately add the dlen of the nonce account. Otherwise, we would
    1020             :           be double counting the dlen of the fee payer. */
    1021           0 :       if( txn_out->accounts.nonce_idx_in_txn!=FD_FEE_PAYER_TXN_IDX ) {
    1022           0 :         txn_out->details.loaded_accounts_data_size += txn_out->accounts.rollback_nonce->dlen;
    1023           0 :       }
    1024           0 :     }
    1025           0 :   }
    1026             : 
    1027             :   /*
    1028             :      The fee payer and the nonce account will be stored and hashed so
    1029             :      long as the transaction landed on chain, or, in Agave terminology,
    1030             :      the transaction was processed.
    1031             :      https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/account_saver.rs#L72
    1032             : 
    1033             :      A transaction lands on chain in one of two ways:
    1034             :      (1) Passed fee validation and loaded accounts.
    1035             :      (2) Passed fee validation and failed to load accounts and the enable_transaction_loading_failure_fees feature is enabled as per
    1036             :          SIMD-0082 https://github.com/anza-xyz/feature-gate-tracker/issues/52
    1037             : 
    1038             :      So, at this point, the transaction is committable.
    1039             :    */
    1040             : 
    1041           0 :   return err;
    1042           0 : }
    1043             : 
    1044             : /* fd_runtime_finalize_account is a helper used to commit the data from
    1045             :    a writable transaction account back into the accountsdb. */
    1046             : 
    1047             : static void
    1048             : fd_runtime_finalize_account( fd_accdb_user_t *         accdb,
    1049             :                              fd_funk_txn_xid_t const * xid,
    1050             :                              fd_pubkey_t const *       pubkey,
    1051           0 :                              fd_account_meta_t *       meta ) {
    1052             :   /* FIXME if account doesn't change according to LtHash, don't update
    1053             :            database record */
    1054             : 
    1055           0 :   fd_accdb_rw_t rw[1];
    1056           0 :   int rw_ok = !!fd_accdb_open_rw(
    1057           0 :       accdb,
    1058           0 :       rw,
    1059           0 :       xid,
    1060           0 :       pubkey,
    1061           0 :       meta->dlen,
    1062           0 :       FD_ACCDB_FLAG_CREATE|FD_ACCDB_FLAG_TRUNCATE );
    1063           0 :   if( FD_UNLIKELY( !rw_ok ) ) FD_LOG_CRIT(( "fd_accdb_open_rw failed" ));
    1064             : 
    1065           0 :   void const * data = fd_account_data( meta );
    1066           0 :   fd_accdb_ref_lamports_set( rw, meta->lamports   );
    1067           0 :   fd_accdb_ref_owner_set   ( rw, meta->owner      );
    1068           0 :   fd_accdb_ref_exec_bit_set( rw, meta->executable );
    1069           0 :   fd_accdb_ref_data_set    ( rw, data, meta->dlen );
    1070           0 :   fd_accdb_ref_slot_set    ( rw, xid->ul[0]    );
    1071             : 
    1072           0 :   fd_accdb_close_rw( accdb, rw );
    1073           0 : }
    1074             : 
    1075             : /* fd_runtime_save_account is a convenience wrapper that looks
    1076             :    up the previous account state from funk before updating the lthash
    1077             :    and saving the new version of the account to funk.
    1078             : 
    1079             :    TODO: We have to make a read request to the DB, so that we can calculate
    1080             :    the previous version of the accounts hash, to mix-out from the accumulated
    1081             :    lthash.  In future we should likely cache the previous version of the account
    1082             :    in transaction setup, so that we don't have to issue a read request here.
    1083             : 
    1084             :    funk is the funk database handle.  funk_txn is the transaction
    1085             :    context to query (NULL for root context).  account is the modified
    1086             :    account.  bank and capture_ctx are passed to fd_hashes_update_lthash.
    1087             : 
    1088             :    This function:
    1089             :    - Queries funk for the previous account version
    1090             :    - Computes the hash of the previous version (or uses zero for new)
    1091             :    - Calls fd_hashes_update_lthash with the computed previous hash
    1092             :    - Saves the new version of the account to Funk
    1093             :    - Notifies the replay tile that an account update has occurred, so it
    1094             :      can write the account to the solcap file.
    1095             : 
    1096             :    The function handles FD_ACC_MGR_ERR_UNKNOWN_ACCOUNT gracefully (uses
    1097             :    zero hash).  On other funk errors, the function will FD_LOG_ERR.
    1098             :    All non-optional pointers must be valid. */
    1099             : 
    1100             : static void
    1101             : fd_runtime_save_account( fd_accdb_user_t *         accdb,
    1102             :                          fd_funk_txn_xid_t const * xid,
    1103             :                          fd_pubkey_t const *       pubkey,
    1104             :                          fd_account_meta_t *       meta,
    1105             :                          fd_bank_t *               bank,
    1106           0 :                          fd_capture_ctx_t *        capture_ctx ) {
    1107             : 
    1108             :   /* Update LtHash
    1109             :      - Query old version of account and hash it
    1110             :      - Hash new version of account */
    1111           0 :   fd_lthash_value_t prev_hash[1];
    1112           0 :   fd_accdb_ro_t ro[1];
    1113           0 :   if( fd_accdb_open_ro( accdb, ro, xid, pubkey ) ) {
    1114           0 :     fd_hashes_account_lthash(
    1115           0 :       pubkey,
    1116           0 :       ro->meta,
    1117           0 :       fd_accdb_ref_data_const( ro ),
    1118           0 :       prev_hash );
    1119           0 :     fd_accdb_close_ro( accdb, ro );
    1120           0 :   } else {
    1121           0 :     fd_lthash_zero( prev_hash );
    1122           0 :   }
    1123             : 
    1124             :   /* Mix in the account hash into the bank hash */
    1125           0 :   fd_hashes_update_lthash( pubkey, meta, prev_hash, bank, capture_ctx );
    1126             : 
    1127             :   /* Save the new version of the account to Funk */
    1128           0 :   fd_runtime_finalize_account( accdb, xid, pubkey, meta );
    1129           0 : }
    1130             : 
    1131             : /* fd_runtime_commit_txn is a helper used by the non-tpool transaction
    1132             :    executor to finalize borrowed account changes back into funk. It also
    1133             :    handles txncache insertion and updates to the vote/stake cache.
    1134             :    TODO: This function should probably be moved to fd_executor.c. */
    1135             : 
    1136             : void
    1137             : fd_runtime_commit_txn( fd_runtime_t *      runtime,
    1138             :                        fd_bank_t *         bank,
    1139             :                        fd_txn_in_t const * txn_in,
    1140           0 :                        fd_txn_out_t *      txn_out ) {
    1141             : 
    1142           0 :   txn_out->details.commit_start_timestamp = fd_tickcount();
    1143             : 
    1144           0 :   fd_funk_txn_xid_t xid = { .ul = { fd_bank_slot_get( bank ), bank->idx } };
    1145             : 
    1146           0 :   if( FD_UNLIKELY( txn_out->err.txn_err ) ) {
    1147             : 
    1148             :     /* Save the fee_payer. Everything but the fee balance should be reset.
    1149             :        TODO: an optimization here could be to use a dirty flag in the
    1150             :        borrowed account. If the borrowed account data has been changed in
    1151             :        any way, then the full account can be rolled back as it is done now.
    1152             :        However, most of the time the account data is not changed, and only
    1153             :        the lamport balance has to change. */
    1154             : 
    1155             :     /* With nonce account rollbacks, there are three cases:
    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 nonce account may be the fee payer (case 2). */
    1161           0 :     if( txn_out->accounts.nonce_idx_in_txn!=ULONG_MAX ) {
    1162           0 :       fd_runtime_save_account( runtime->accdb,
    1163           0 :                                &xid,
    1164           0 :                                &txn_out->accounts.keys[txn_out->accounts.nonce_idx_in_txn],
    1165           0 :                                txn_out->accounts.rollback_nonce,
    1166           0 :                                bank,
    1167           0 :                                runtime->log.capture_ctx );
    1168           0 :     }
    1169             : 
    1170             :     /* Now, we must only save the fee payer if the nonce account was not the fee payer (because that was already saved above) */
    1171           0 :     if( FD_LIKELY( txn_out->accounts.nonce_idx_in_txn!=FD_FEE_PAYER_TXN_IDX ) ) {
    1172           0 :       fd_runtime_save_account( runtime->accdb,
    1173           0 :                                &xid,
    1174           0 :                                &txn_out->accounts.keys[FD_FEE_PAYER_TXN_IDX],
    1175           0 :                                txn_out->accounts.rollback_fee_payer,
    1176           0 :                                bank,
    1177           0 :                                runtime->log.capture_ctx );
    1178           0 :     }
    1179           0 :   } else {
    1180             : 
    1181           0 :     for( ushort i=0; i<txn_out->accounts.cnt; i++ ) {
    1182             :       /* We are only interested in saving writable accounts and the fee
    1183             :          payer account. */
    1184           0 :       if( !fd_runtime_account_is_writable_idx( txn_in, txn_out, bank, i ) && i!=FD_FEE_PAYER_TXN_IDX ) {
    1185           0 :         continue;
    1186           0 :       }
    1187             : 
    1188           0 :       fd_pubkey_t const * pubkey = &txn_out->accounts.keys[i];
    1189           0 :       fd_account_meta_t * meta   = txn_out->accounts.metas[i];
    1190             : 
    1191             :       /* Tips for bundles are collected in the bank: a user submitting a
    1192             :          bundle must include a instruction that transfers lamports to
    1193             :          a specific tip account.  Tips accumulated through the slot. */
    1194           0 :       if( fd_pack_tip_is_tip_account( fd_type_pun_const( pubkey->uc ) ) ) {
    1195           0 :         txn_out->details.tips += fd_ulong_sat_sub( meta->lamports, runtime->accounts.starting_lamports[i] );
    1196           0 :         FD_ATOMIC_FETCH_AND_ADD( fd_bank_tips_modify( bank ), txn_out->details.tips );
    1197           0 :       }
    1198             : 
    1199           0 :       if( 0==memcmp( meta->owner, &fd_solana_vote_program_id, sizeof(fd_pubkey_t) ) ) {
    1200           0 :         fd_stakes_update_vote_state( pubkey, meta, bank );
    1201           0 :       }
    1202             : 
    1203           0 :       if( 0==memcmp( meta->owner, &fd_solana_stake_program_id, sizeof(fd_pubkey_t) ) ) {
    1204           0 :         fd_stakes_update_stake_delegation( pubkey, meta, bank );
    1205           0 :       }
    1206             : 
    1207             :       /* Reclaim any accounts that have 0-lamports, now that any related
    1208             :          cache updates have been applied. */
    1209           0 :       fd_executor_reclaim_account( txn_out->accounts.metas[i], fd_bank_slot_get( bank ) );
    1210             : 
    1211           0 :       fd_runtime_save_account( runtime->accdb, &xid, pubkey, meta, bank, runtime->log.capture_ctx );
    1212           0 :     }
    1213             : 
    1214             :     /* We need to queue any existing program accounts that may have
    1215             :        been deployed / upgraded for reverification in the program
    1216             :        cache since their programdata may have changed. ELF / sBPF
    1217             :        metadata will need to be updated. */
    1218           0 :     ulong current_slot = fd_bank_slot_get( bank );
    1219           0 :     for( uchar i=0; i<txn_out->details.programs_to_reverify_cnt; i++ ) {
    1220           0 :       fd_pubkey_t const * program_key = &txn_out->details.programs_to_reverify[i];
    1221           0 :       fd_progcache_invalidate( runtime->progcache, &xid, program_key, current_slot );
    1222           0 :     }
    1223           0 :   }
    1224             : 
    1225             :   /* Accumulate block-level information to the bank. */
    1226             : 
    1227           0 :   FD_ATOMIC_FETCH_AND_ADD( fd_bank_txn_count_modify( bank ),       1UL );
    1228           0 :   FD_ATOMIC_FETCH_AND_ADD( fd_bank_execution_fees_modify( bank ),  txn_out->details.execution_fee );
    1229           0 :   FD_ATOMIC_FETCH_AND_ADD( fd_bank_priority_fees_modify( bank ),   txn_out->details.priority_fee );
    1230           0 :   FD_ATOMIC_FETCH_AND_ADD( fd_bank_signature_count_modify( bank ), txn_out->details.signature_count );
    1231             : 
    1232           0 :   int is_vote = fd_txn_is_simple_vote_transaction( TXN( txn_in->txn ), txn_in->txn->payload );
    1233           0 :   if( !is_vote ){
    1234           0 :     FD_ATOMIC_FETCH_AND_ADD( fd_bank_nonvote_txn_count_modify( bank ), 1 );
    1235           0 :     if( FD_UNLIKELY( txn_out->err.exec_err ) ) {
    1236           0 :       FD_ATOMIC_FETCH_AND_ADD( fd_bank_nonvote_failed_txn_count_modify( bank ), 1 );
    1237           0 :     }
    1238           0 :   }
    1239             : 
    1240           0 :   if( FD_UNLIKELY( txn_out->err.exec_err ) ) {
    1241           0 :     FD_ATOMIC_FETCH_AND_ADD( fd_bank_failed_txn_count_modify( bank ), 1 );
    1242           0 :   }
    1243             : 
    1244           0 :   FD_ATOMIC_FETCH_AND_ADD( fd_bank_total_compute_units_used_modify( bank ), txn_out->details.compute_budget.compute_unit_limit - txn_out->details.compute_budget.compute_meter );
    1245             : 
    1246             :   /* Update the cost tracker. */
    1247             : 
    1248           0 :   fd_cost_tracker_t * cost_tracker = fd_bank_cost_tracker_locking_modify( bank );
    1249           0 :   int res = fd_cost_tracker_calculate_cost_and_add( cost_tracker, bank, txn_in, txn_out );
    1250           0 :   if( FD_UNLIKELY( res!=FD_COST_TRACKER_SUCCESS ) ) {
    1251           0 :     FD_LOG_DEBUG(( "fd_runtime_commit_txn: transaction failed to fit into block %d", res ));
    1252           0 :     txn_out->err.is_committable = 0;
    1253           0 :   }
    1254           0 :   fd_bank_cost_tracker_end_locking_modify( bank );
    1255             : 
    1256           0 :   txn_out->details.loaded_accounts_data_size_cost = fd_cost_tracker_calculate_loaded_accounts_data_size_cost( txn_out );
    1257             : 
    1258             :   /* Finally, update the status cache. */
    1259             : 
    1260           0 :   if( FD_LIKELY( runtime->status_cache && txn_out->accounts.nonce_idx_in_txn==ULONG_MAX ) ) {
    1261             :     /* In Agave, durable nonce transactions are inserted to the status
    1262             :        cache the same as any others, but this is only to serve RPC
    1263             :        requests, they do not need to be in there for correctness as the
    1264             :        nonce mechanism itself prevents double spend.  We skip this logic
    1265             :        entirely to simplify and improve performance of the txn cache. */
    1266             : 
    1267           0 :     fd_hash_t * blockhash = (fd_hash_t *)((uchar *)txn_in->txn->payload + TXN( txn_in->txn )->recent_blockhash_off);
    1268           0 :     fd_txncache_insert( runtime->status_cache, bank->txncache_fork_id, blockhash->uc, txn_out->details.blake_txn_msg_hash.uc );
    1269           0 :   }
    1270           0 : }
    1271             : 
    1272             : void
    1273             : fd_runtime_prepare_and_execute_txn( fd_runtime_t *       runtime,
    1274             :                                     fd_bank_t *          bank,
    1275             :                                     fd_txn_in_t const *  txn_in,
    1276           0 :                                     fd_txn_out_t *       txn_out ) {
    1277             : 
    1278           0 :   txn_out->details.prep_start_timestamp   = fd_tickcount();
    1279           0 :   txn_out->details.load_start_timestamp   = LONG_MAX;
    1280           0 :   txn_out->details.exec_start_timestamp   = LONG_MAX;
    1281           0 :   txn_out->details.commit_start_timestamp = LONG_MAX;
    1282             : 
    1283           0 :   txn_out->accounts.cnt   = 0UL;
    1284             : 
    1285           0 :   txn_out->details.programs_to_reverify_cnt       = 0UL;
    1286           0 :   txn_out->details.loaded_accounts_data_size      = 0UL;
    1287           0 :   txn_out->details.loaded_accounts_data_size_cost = 0UL;
    1288           0 :   txn_out->details.accounts_resize_delta          = 0UL;
    1289           0 :   txn_out->details.return_data.len                = 0UL;
    1290           0 :   txn_out->details.tips                           = 0UL;
    1291           0 :   txn_out->details.execution_fee                  = 0UL;
    1292           0 :   txn_out->details.priority_fee                   = 0UL;
    1293           0 :   txn_out->details.signature_count                = TXN( txn_in->txn )->signature_cnt;
    1294           0 :   memset( txn_out->details.return_data.program_id.key, 0, sizeof(fd_pubkey_t) );
    1295           0 :   fd_compute_budget_details_new( &txn_out->details.compute_budget );
    1296             : 
    1297           0 :   runtime->accounts.executable_cnt = 0UL;
    1298           0 :   runtime->log.enable_log_collector = 0;
    1299           0 :   runtime->instr.trace_length = 0UL;
    1300           0 :   runtime->instr.current_idx  = 0;
    1301           0 :   runtime->instr.stack_sz     = 0;
    1302             : 
    1303           0 :   txn_out->err.is_committable = 1;
    1304           0 :   txn_out->err.is_fees_only   = 0;
    1305           0 :   txn_out->err.txn_err        = FD_RUNTIME_EXECUTE_SUCCESS;
    1306           0 :   txn_out->err.exec_err       = FD_EXECUTOR_INSTR_SUCCESS;
    1307           0 :   txn_out->err.exec_err_kind  = FD_EXECUTOR_ERR_KIND_NONE;
    1308           0 :   txn_out->err.exec_err_idx   = INT_MAX;
    1309             : 
    1310             :   /* Transaction sanitization.  If a transaction can't be commited or is
    1311             :      fees-only, we return early. */
    1312           0 :   txn_out->err.txn_err = fd_runtime_pre_execute_check( runtime, bank, txn_in, txn_out );
    1313             : 
    1314           0 :   txn_out->details.exec_start_timestamp = fd_tickcount();
    1315             : 
    1316             :   /* Execute the transaction. */
    1317           0 :   if( FD_LIKELY( txn_out->err.is_committable && !txn_out->err.is_fees_only ) ) {
    1318           0 :     txn_out->err.txn_err = fd_execute_txn( runtime, bank, txn_in, txn_out );
    1319           0 :   }
    1320           0 : }
    1321             : 
    1322             : /* fd_executor_txn_verify and fd_runtime_pre_execute_check are responisble
    1323             :    for the bulk of the pre-transaction execution checks in the runtime.
    1324             :    They aim to preserve the ordering present in the Agave client to match
    1325             :    parity in terms of error codes. Sigverify is kept separate from the rest
    1326             :    of the transaction checks for fuzzing convenience.
    1327             : 
    1328             :    For reference this is the general code path which contains all relevant
    1329             :    pre-transactions checks in the v2.0.x Agave client from upstream
    1330             :    to downstream is as follows:
    1331             : 
    1332             :    confirm_slot_entries() which calls verify_ticks() and
    1333             :    verify_transaction(). verify_transaction() calls verify_and_hash_message()
    1334             :    and verify_precompiles() which parallels fd_executor_txn_verify() and
    1335             :    fd_executor_verify_transaction().
    1336             : 
    1337             :    process_entries() contains a duplicate account check which is part of
    1338             :    agave account lock acquiring. This is checked inline in
    1339             :    fd_runtime_pre_execute_check().
    1340             : 
    1341             :    load_and_execute_transactions() contains the function check_transactions().
    1342             :    This contains check_age() and check_status_cache() which is paralleled by
    1343             :    fd_executor_check_transaction_age_and_compute_budget_limits() and
    1344             :    fd_executor_check_status_cache() respectively.
    1345             : 
    1346             :    load_and_execute_sanitized_transactions() contains validate_fees()
    1347             :    which is responsible for executing the compute budget instructions,
    1348             :    validating the fee payer and collecting the fee. This is mirrored in
    1349             :    firedancer with fd_executor_compute_budget_program_execute_instructions()
    1350             :    and fd_executor_collect_fees(). load_and_execute_sanitized_transactions()
    1351             :    also checks the total data size of the accounts in load_accounts() and
    1352             :    validates the program accounts in load_transaction_accounts(). This
    1353             :    is paralled by fd_executor_load_transaction_accounts(). */
    1354             : 
    1355             : 
    1356             : /******************************************************************************/
    1357             : /* Genesis                                                                    */
    1358             : /*******************************************************************************/
    1359             : 
    1360             : static void
    1361             : fd_runtime_genesis_init_program( fd_bank_t *               bank,
    1362             :                                  fd_accdb_user_t *         accdb,
    1363             :                                  fd_funk_txn_xid_t const * xid,
    1364           0 :                                  fd_capture_ctx_t *        capture_ctx ) {
    1365             : 
    1366           0 :   fd_sysvar_clock_init( bank, accdb, xid, capture_ctx );
    1367           0 :   fd_sysvar_rent_init( bank, accdb, xid, capture_ctx );
    1368             : 
    1369           0 :   fd_sysvar_slot_history_init( bank, accdb, xid, capture_ctx );
    1370           0 :   fd_sysvar_epoch_schedule_init( bank, accdb, xid, capture_ctx );
    1371           0 :   fd_sysvar_recent_hashes_init( bank, accdb, xid, capture_ctx );
    1372           0 :   fd_sysvar_stake_history_init( bank, accdb, xid, capture_ctx );
    1373           0 :   fd_sysvar_last_restart_slot_init( bank, accdb, xid, capture_ctx );
    1374             : 
    1375           0 :   fd_builtin_programs_init( bank, accdb, xid, capture_ctx );
    1376           0 :   fd_stake_program_config_init( accdb, xid );
    1377           0 : }
    1378             : 
    1379             : static void
    1380             : fd_runtime_init_bank_from_genesis( fd_banks_t *              banks,
    1381             :                                    fd_bank_t *               bank,
    1382             :                                    fd_funk_t *               funk,
    1383             :                                    fd_funk_txn_xid_t const * xid,
    1384             :                                    fd_genesis_t const *      genesis_block,
    1385           0 :                                    fd_hash_t const *         genesis_hash ) {
    1386             : 
    1387           0 :   fd_bank_poh_set( bank, *genesis_hash );
    1388             : 
    1389           0 :   fd_hash_t * bank_hash = fd_bank_bank_hash_modify( bank );
    1390           0 :   memset( bank_hash->hash, 0, FD_SHA256_HASH_SZ );
    1391             : 
    1392           0 :   uint128 target_tick_duration = (uint128)genesis_block->poh.tick_duration_secs * 1000000000UL + (uint128)genesis_block->poh.tick_duration_ns;
    1393             : 
    1394           0 :   fd_epoch_schedule_t * epoch_schedule = fd_bank_epoch_schedule_modify( bank );
    1395           0 :   epoch_schedule->leader_schedule_slot_offset = genesis_block->epoch_schedule.leader_schedule_slot_offset;
    1396           0 :   epoch_schedule->warmup                      = genesis_block->epoch_schedule.warmup;
    1397           0 :   epoch_schedule->first_normal_epoch          = genesis_block->epoch_schedule.first_normal_epoch;
    1398           0 :   epoch_schedule->first_normal_slot           = genesis_block->epoch_schedule.first_normal_slot;
    1399           0 :   epoch_schedule->slots_per_epoch             = genesis_block->epoch_schedule.slots_per_epoch;
    1400             : 
    1401           0 :   fd_rent_t * rent = fd_bank_rent_modify( bank );
    1402           0 :   rent->lamports_per_uint8_year = genesis_block->rent.lamports_per_uint8_year;
    1403           0 :   rent->exemption_threshold     = genesis_block->rent.exemption_threshold;
    1404           0 :   rent->burn_percent            = genesis_block->rent.burn_percent;
    1405             : 
    1406           0 :   fd_inflation_t * inflation = fd_bank_inflation_modify( bank );
    1407           0 :   inflation->initial         = genesis_block->inflation.initial;
    1408           0 :   inflation->terminal        = genesis_block->inflation.terminal;
    1409           0 :   inflation->taper           = genesis_block->inflation.taper;
    1410           0 :   inflation->foundation      = genesis_block->inflation.foundation;
    1411           0 :   inflation->foundation_term = genesis_block->inflation.foundation_term;
    1412           0 :   inflation->unused          = 0.0;
    1413             : 
    1414           0 :   fd_bank_block_height_set( bank, 0UL );
    1415             : 
    1416           0 :   {
    1417             :     /* FIXME Why is there a previous blockhash at genesis?  Why is the
    1418             :              last_hash field an option type in Agave, if even the first
    1419             :              real block has a previous blockhash? */
    1420             :     /* TODO: Use a real seed here. */
    1421           0 :     fd_blockhashes_t *    bhq  = fd_blockhashes_init( fd_bank_block_hash_queue_modify( bank ), 0UL );
    1422           0 :     fd_blockhash_info_t * info = fd_blockhashes_push_new( bhq, genesis_hash );
    1423           0 :     info->fee_calculator.lamports_per_signature = 0UL;
    1424           0 :   }
    1425             : 
    1426           0 :   fd_fee_rate_governor_t * fee_rate_governor = fd_bank_fee_rate_governor_modify( bank );
    1427           0 :   fee_rate_governor->target_lamports_per_signature = genesis_block->fee_rate_governor.target_lamports_per_signature;
    1428           0 :   fee_rate_governor->target_signatures_per_slot    = genesis_block->fee_rate_governor.target_signatures_per_slot;
    1429           0 :   fee_rate_governor->min_lamports_per_signature    = genesis_block->fee_rate_governor.min_lamports_per_signature;
    1430           0 :   fee_rate_governor->max_lamports_per_signature    = genesis_block->fee_rate_governor.max_lamports_per_signature;
    1431           0 :   fee_rate_governor->burn_percent                  = genesis_block->fee_rate_governor.burn_percent;
    1432             : 
    1433           0 :   fd_bank_max_tick_height_set( bank, genesis_block->poh.ticks_per_slot * (fd_bank_slot_get( bank ) + 1) );
    1434             : 
    1435           0 :   fd_bank_hashes_per_tick_set( bank, genesis_block->poh.hashes_per_tick );
    1436             : 
    1437           0 :   fd_bank_ns_per_slot_set( bank, (fd_w_u128_t) { .ud=target_tick_duration * genesis_block->poh.ticks_per_slot } );
    1438             : 
    1439           0 :   fd_bank_ticks_per_slot_set( bank, genesis_block->poh.ticks_per_slot );
    1440             : 
    1441           0 :   fd_bank_genesis_creation_time_set( bank, genesis_block->creation_time );
    1442             : 
    1443           0 :   fd_bank_slots_per_year_set( bank, SECONDS_PER_YEAR * (1000000000.0 / (double)target_tick_duration) / (double)genesis_block->poh.ticks_per_slot );
    1444             : 
    1445           0 :   fd_bank_signature_count_set( bank, 0UL );
    1446             : 
    1447             :   /* Derive epoch stakes */
    1448             : 
    1449           0 :   fd_stake_delegations_t * stake_delegations = fd_banks_stake_delegations_root_query( banks );
    1450           0 :   if( FD_UNLIKELY( !stake_delegations ) ) {
    1451           0 :     FD_LOG_CRIT(( "Failed to join and new a stake delegations" ));
    1452           0 :   }
    1453             : 
    1454           0 :   fd_vote_states_t * vote_states = fd_vote_states_join( fd_vote_states_new( fd_bank_vote_states_locking_modify( bank ), FD_RUNTIME_MAX_VOTE_ACCOUNTS, 999UL ) );
    1455           0 :   if( FD_UNLIKELY( !vote_states ) ) {
    1456           0 :     FD_LOG_CRIT(( "Failed to join and new a vote states" ));
    1457           0 :   }
    1458             : 
    1459           0 :   ulong capitalization = 0UL;
    1460             : 
    1461             : 
    1462           0 :   for( ulong i=0UL; i<genesis_block->accounts_len; i++ ) {
    1463           0 :     fd_genesis_account_t * account = fd_type_pun( (uchar *)genesis_block + genesis_block->accounts_off[ i ] );
    1464             : 
    1465           0 :     capitalization = fd_ulong_sat_add( capitalization, account->meta.lamports );
    1466             : 
    1467           0 :     uchar const * acc_data = account->data;
    1468             : 
    1469           0 :     if( !memcmp( account->meta.owner, fd_solana_vote_program_id.key, sizeof(fd_pubkey_t) ) ) {
    1470             :       /* This means that there is a vote account which should be
    1471             :          inserted into the vote states. Even after the vote account is
    1472             :          inserted, we still don't know the total amount of stake that is
    1473             :          delegated to the vote account. This must be calculated later. */
    1474           0 :       fd_vote_states_update_from_account( vote_states, fd_type_pun( account->pubkey ), acc_data, account->meta.dlen );
    1475           0 :     } else if( !memcmp( account->meta.owner, fd_solana_stake_program_id.key, sizeof(fd_pubkey_t) ) ) {
    1476             :       /* If an account is a stake account, then it must be added to the
    1477             :          stake delegations cache. We should only add stake accounts that
    1478             :          have a valid non-zero stake. */
    1479           0 :       fd_stake_state_v2_t stake_state = {0};
    1480           0 :       if( FD_UNLIKELY( !fd_bincode_decode_static(
    1481           0 :           stake_state_v2, &stake_state,
    1482           0 :           acc_data, account->meta.dlen,
    1483           0 :           NULL ) ) ) {
    1484           0 :         FD_BASE58_ENCODE_32_BYTES( account->pubkey, stake_b58 );
    1485           0 :         FD_LOG_ERR(( "Failed to deserialize genesis stake account %s", stake_b58 ));
    1486           0 :       }
    1487           0 :       if( !fd_stake_state_v2_is_stake( &stake_state )     ) continue;
    1488           0 :       if( !stake_state.inner.stake.stake.delegation.stake ) continue;
    1489             : 
    1490           0 :       fd_stake_delegations_update(
    1491           0 :           stake_delegations,
    1492           0 :           (fd_pubkey_t *)account->pubkey,
    1493           0 :           &stake_state.inner.stake.stake.delegation.voter_pubkey,
    1494           0 :           stake_state.inner.stake.stake.delegation.stake,
    1495           0 :           stake_state.inner.stake.stake.delegation.activation_epoch,
    1496           0 :           stake_state.inner.stake.stake.delegation.deactivation_epoch,
    1497           0 :           stake_state.inner.stake.stake.credits_observed,
    1498           0 :           stake_state.inner.stake.stake.delegation.warmup_cooldown_rate );
    1499             : 
    1500           0 :     } else if( !memcmp( account->meta.owner, fd_solana_feature_program_id.key, sizeof(fd_pubkey_t) ) ) {
    1501             :       /* Feature Account */
    1502             : 
    1503             :       /* Scan list of feature IDs to resolve address=>feature offset */
    1504           0 :       fd_feature_id_t const *found = NULL;
    1505           0 :       for( fd_feature_id_t const * id = fd_feature_iter_init();
    1506           0 :            !fd_feature_iter_done( id );
    1507           0 :            id = fd_feature_iter_next( id ) ) {
    1508           0 :         if( !memcmp( account->pubkey, id->id.key, sizeof(fd_pubkey_t) ) ) {
    1509           0 :           found = id;
    1510           0 :           break;
    1511           0 :         }
    1512           0 :       }
    1513             : 
    1514           0 :       if( found ) {
    1515             :         /* Load feature activation */
    1516           0 :         fd_feature_t feature[1];
    1517           0 :         FD_TEST( fd_bincode_decode_static( feature, feature, acc_data, account->meta.dlen, NULL ) );
    1518             : 
    1519           0 :         fd_features_t * features = fd_bank_features_modify( bank );
    1520           0 :         if( feature->has_activated_at ) {
    1521           0 :           FD_BASE58_ENCODE_32_BYTES( account->pubkey, pubkey_b58 );
    1522           0 :           FD_LOG_DEBUG(( "Feature %s activated at %lu (genesis)", pubkey_b58, feature->activated_at ));
    1523           0 :           fd_features_set( features, found, feature->activated_at );
    1524           0 :         } else {
    1525           0 :           FD_BASE58_ENCODE_32_BYTES( account->pubkey, pubkey_b58 );
    1526           0 :           FD_LOG_DEBUG(( "Feature %s not activated (genesis)", pubkey_b58 ));
    1527           0 :           fd_features_set( features, found, ULONG_MAX );
    1528           0 :         }
    1529           0 :       }
    1530           0 :     }
    1531           0 :   }
    1532           0 :   fd_bank_vote_states_end_locking_modify( bank );
    1533             : 
    1534             :   /* fd_refresh_vote_accounts is responsible for updating the vote
    1535             :      states with the total amount of active delegated stake. It does
    1536             :      this by iterating over all active stake delegations and summing up
    1537             :      the amount of stake that is delegated to each vote account. */
    1538             : 
    1539           0 :   ulong new_rate_activation_epoch = 0UL;
    1540             : 
    1541           0 :   fd_stake_history_t stake_history[1];
    1542           0 :   fd_sysvar_stake_history_read( funk, xid, stake_history );
    1543             : 
    1544           0 :   fd_refresh_vote_accounts(
    1545           0 :       bank,
    1546           0 :       stake_delegations,
    1547           0 :       stake_history,
    1548           0 :       &new_rate_activation_epoch );
    1549             : 
    1550             :   /* Now that the stake and vote delegations are updated correctly, we
    1551             :      will propagate the vote states to the vote states for the previous
    1552             :      epoch and the epoch before that.
    1553             : 
    1554             :      This is despite the fact we are booting off of genesis which means
    1555             :      that there is no previous or previous-previous epoch. This is done
    1556             :      to simplify edge cases around leader schedule and rewards
    1557             :      calculation.
    1558             : 
    1559             :      TODO: Each of the edge cases around this needs to be documented
    1560             :      much better where each case is clearly enumerated and explained. */
    1561             : 
    1562           0 :   vote_states = fd_bank_vote_states_locking_modify( bank );
    1563           0 :   for( ulong i=0UL; i<genesis_block->accounts_len; i++ ) {
    1564           0 :     fd_genesis_account_t * account = fd_type_pun( (uchar *)genesis_block + genesis_block->accounts_off[ i ] );
    1565             : 
    1566           0 :     if( !memcmp( account->meta.owner, fd_solana_vote_program_id.key, sizeof(fd_pubkey_t) ) ) {
    1567           0 :       fd_vote_state_ele_t * vote_state = fd_vote_states_query( vote_states, fd_type_pun( account->pubkey ) );
    1568             : 
    1569           0 :       vote_state->stake_t_1 = vote_state->stake;
    1570           0 :       vote_state->stake_t_2 = vote_state->stake;
    1571           0 :     }
    1572           0 :   }
    1573             : 
    1574           0 :   fd_vote_states_t * vote_states_prev_prev = fd_bank_vote_states_prev_prev_locking_modify( bank );
    1575           0 :   fd_memcpy( vote_states_prev_prev, vote_states, FD_VOTE_STATES_FOOTPRINT );
    1576           0 :   fd_bank_vote_states_prev_prev_end_locking_modify( bank );
    1577             : 
    1578           0 :   fd_vote_states_t * vote_states_prev = fd_bank_vote_states_prev_locking_modify( bank );
    1579           0 :   fd_memcpy( vote_states_prev, vote_states, FD_VOTE_STATES_FOOTPRINT );
    1580           0 :   fd_bank_vote_states_prev_end_locking_modify( bank );
    1581             : 
    1582           0 :   fd_bank_vote_states_end_locking_modify( bank );
    1583             : 
    1584           0 :   fd_bank_epoch_set( bank, 0UL );
    1585             : 
    1586           0 :   fd_bank_capitalization_set( bank, capitalization );
    1587           0 : }
    1588             : 
    1589             : static int
    1590             : fd_runtime_process_genesis_block( fd_bank_t *               bank,
    1591             :                                   fd_accdb_user_t *         accdb,
    1592             :                                   fd_funk_txn_xid_t const * xid,
    1593             :                                   fd_capture_ctx_t *        capture_ctx,
    1594           0 :                                   fd_runtime_stack_t *      runtime_stack ) {
    1595             : 
    1596           0 :   fd_hash_t * poh = fd_bank_poh_modify( bank );
    1597           0 :   ulong hashcnt_per_slot = fd_bank_hashes_per_tick_get( bank ) * fd_bank_ticks_per_slot_get( bank );
    1598           0 :   while( hashcnt_per_slot-- ) {
    1599           0 :     fd_sha256_hash( poh->hash, sizeof(fd_hash_t), poh->hash );
    1600           0 :   }
    1601             : 
    1602           0 :   fd_bank_execution_fees_set( bank, 0UL );
    1603             : 
    1604           0 :   fd_bank_priority_fees_set( bank, 0UL );
    1605             : 
    1606           0 :   fd_bank_signature_count_set( bank, 0UL );
    1607             : 
    1608           0 :   fd_bank_txn_count_set( bank, 0UL );
    1609             : 
    1610           0 :   fd_bank_failed_txn_count_set( bank, 0UL );
    1611             : 
    1612           0 :   fd_bank_nonvote_failed_txn_count_set( bank, 0UL );
    1613             : 
    1614           0 :   fd_bank_total_compute_units_used_set( bank, 0UL );
    1615             : 
    1616           0 :   fd_runtime_genesis_init_program( bank, accdb, xid, capture_ctx );
    1617             : 
    1618           0 :   fd_sysvar_slot_history_update( bank, accdb, xid, capture_ctx );
    1619             : 
    1620           0 :   fd_runtime_update_leaders( bank, runtime_stack );
    1621             : 
    1622           0 :   fd_runtime_freeze( bank, accdb, capture_ctx );
    1623             : 
    1624           0 :   fd_lthash_value_t const * lthash = fd_bank_lthash_locking_query( bank );
    1625             : 
    1626           0 :   fd_hash_t const * prev_bank_hash = fd_bank_bank_hash_query( bank );
    1627             : 
    1628           0 :   fd_hash_t * bank_hash = fd_bank_bank_hash_modify( bank );
    1629           0 :   fd_hashes_hash_bank(
    1630           0 :     lthash,
    1631           0 :     prev_bank_hash,
    1632           0 :     (fd_hash_t *)fd_bank_poh_query( bank )->hash,
    1633           0 :     0UL,
    1634           0 :     bank_hash );
    1635             : 
    1636           0 :   fd_bank_lthash_end_locking_query( bank );
    1637             : 
    1638           0 :   return FD_RUNTIME_EXECUTE_SUCCESS;
    1639           0 : }
    1640             : 
    1641             : void
    1642             : fd_runtime_read_genesis( fd_banks_t *              banks,
    1643             :                          fd_bank_t *               bank,
    1644             :                          fd_accdb_user_t *         accdb,
    1645             :                          fd_funk_txn_xid_t const * xid,
    1646             :                          fd_capture_ctx_t *        capture_ctx,
    1647             :                          fd_hash_t const *         genesis_hash,
    1648             :                          fd_lthash_value_t const * genesis_lthash,
    1649             :                          fd_genesis_t const *      genesis_block,
    1650           0 :                          fd_runtime_stack_t *      runtime_stack ) {
    1651             : 
    1652           0 :   fd_lthash_value_t * lthash = fd_bank_lthash_locking_modify( bank );
    1653           0 :   *lthash = *genesis_lthash;
    1654           0 :   fd_bank_lthash_end_locking_modify( bank );
    1655             : 
    1656             :   /* Once the accounts have been loaded from the genesis config into
    1657             :      the accounts db, we can initialize the bank state. This involves
    1658             :      setting some fields, and notably setting up the vote and stake
    1659             :      caches which are used for leader scheduling/rewards. */
    1660             : 
    1661           0 :   fd_funk_t * funk = fd_accdb_user_v1_funk( accdb );
    1662           0 :   fd_runtime_init_bank_from_genesis( banks, bank, funk, xid, genesis_block, genesis_hash );
    1663             : 
    1664             :   /* Write the native programs to the accounts db. */
    1665             : 
    1666           0 :   for( ulong i=0UL; i<genesis_block->builtin_len; i++ ) {
    1667           0 :     fd_genesis_account_t * account = fd_type_pun( (uchar *)genesis_block + genesis_block->builtin_off[ i ] );
    1668             : 
    1669           0 :     fd_pubkey_t pubkey;
    1670           0 :     fd_memcpy( pubkey.uc, account->pubkey, sizeof(fd_pubkey_t) );
    1671           0 :     fd_write_builtin_account( bank, accdb, xid, capture_ctx, pubkey, (const char *)account->data, account->meta.dlen );
    1672           0 :   }
    1673             : 
    1674           0 :   fd_features_restore( bank, funk, xid );
    1675             : 
    1676             :   /* At this point, state related to the bank and the accounts db
    1677             :      have been initialized and we are free to finish executing the
    1678             :      block. In practice, this updates some bank fields (notably the
    1679             :      poh and bank hash). */
    1680             : 
    1681           0 :   int err = fd_runtime_process_genesis_block( bank, accdb, xid, capture_ctx, runtime_stack );
    1682           0 :   if( FD_UNLIKELY( err ) ) FD_LOG_CRIT(( "genesis slot 0 execute failed with error %d", err ));
    1683           0 : }
    1684             : 
    1685             : void
    1686             : fd_runtime_block_execute_finalize( fd_bank_t *        bank,
    1687             :                                    fd_accdb_user_t *  accdb,
    1688           0 :                                    fd_capture_ctx_t * capture_ctx ) {
    1689             : 
    1690             :   /* This slot is now "frozen" and can't be changed anymore. */
    1691           0 :   fd_runtime_freeze( bank, accdb, capture_ctx );
    1692             : 
    1693           0 :   fd_runtime_update_bank_hash( bank, capture_ctx );
    1694           0 : }
    1695             : 
    1696             : 
    1697             : /* Mirrors Agave function solana_sdk::transaction_context::find_index_of_account
    1698             : 
    1699             :    Backward scan over transaction accounts.
    1700             :    Returns -1 if not found.
    1701             : 
    1702             :    https://github.com/anza-xyz/agave/blob/v2.1.14/sdk/src/transaction_context.rs#L233-L238 */
    1703             : 
    1704             : int
    1705             : fd_runtime_find_index_of_account( fd_txn_out_t const * txn_out,
    1706         132 :                                   fd_pubkey_t const *  pubkey ) {
    1707         312 :   for( ulong i=txn_out->accounts.cnt; i>0UL; i-- ) {
    1708         288 :     if( 0==memcmp( pubkey, &txn_out->accounts.keys[ i-1UL ], sizeof(fd_pubkey_t) ) ) {
    1709         108 :       return (int)(i-1UL);
    1710         108 :     }
    1711         288 :   }
    1712          24 :   return -1;
    1713         132 : }
    1714             : 
    1715             : int
    1716             : fd_runtime_get_account_at_index( fd_txn_in_t const *             txn_in,
    1717             :                                  fd_txn_out_t *                  txn_out,
    1718             :                                  ushort                          idx,
    1719         300 :                                  fd_txn_account_condition_fn_t * condition ) {
    1720         300 :   if( FD_UNLIKELY( idx>=txn_out->accounts.cnt ) ) {
    1721           0 :     return FD_ACC_MGR_ERR_UNKNOWN_ACCOUNT;
    1722           0 :   }
    1723             : 
    1724         300 :   if( FD_LIKELY( condition != NULL ) ) {
    1725           0 :     if( FD_UNLIKELY( !condition( txn_in, txn_out, idx ) ) ) {
    1726           0 :       return FD_ACC_MGR_ERR_UNKNOWN_ACCOUNT;
    1727           0 :     }
    1728           0 :   }
    1729             : 
    1730         300 :   return FD_ACC_MGR_SUCCESS;
    1731         300 : }
    1732             : 
    1733             : int
    1734             : fd_runtime_get_account_with_key( fd_txn_in_t const *             txn_in,
    1735             :                                  fd_txn_out_t *                  txn_out,
    1736             :                                  fd_pubkey_t const *             pubkey,
    1737             :                                  int *                           index_out,
    1738           0 :                                  fd_txn_account_condition_fn_t * condition ) {
    1739           0 :   int index = fd_runtime_find_index_of_account( txn_out, pubkey );
    1740           0 :   if( FD_UNLIKELY( index==-1 ) ) {
    1741           0 :     return FD_ACC_MGR_ERR_UNKNOWN_ACCOUNT;
    1742           0 :   }
    1743             : 
    1744           0 :   *index_out = index;
    1745             : 
    1746           0 :   return fd_runtime_get_account_at_index( txn_in,
    1747           0 :                                           txn_out,
    1748           0 :                                           (uchar)index,
    1749           0 :                                           condition );
    1750           0 : }
    1751             : 
    1752             : int
    1753             : fd_runtime_get_executable_account( fd_runtime_t *              runtime,
    1754             :                                    fd_txn_in_t const *         txn_in,
    1755             :                                    fd_txn_out_t *              txn_out,
    1756             :                                    fd_pubkey_t const *         pubkey,
    1757           0 :                                    fd_account_meta_t const * * meta ) {
    1758             :   /* First try to fetch the executable account from the existing
    1759             :      borrowed accounts.  If the pubkey is in the account keys, then we
    1760             :      want to re-use that borrowed account since it reflects changes from
    1761             :      prior instructions.  Referencing the read-only executable accounts
    1762             :      list is incorrect behavior when the program data account is written
    1763             :      to in a prior instruction (e.g. program upgrade + invoke within the
    1764             :      same txn) */
    1765             : 
    1766           0 :   fd_txn_account_condition_fn_t * condition = fd_runtime_account_check_exists;
    1767             : 
    1768           0 :   int index;
    1769           0 :   int err = fd_runtime_get_account_with_key( txn_in,
    1770           0 :                                              txn_out,
    1771           0 :                                              pubkey,
    1772           0 :                                              &index,
    1773           0 :                                              condition );
    1774           0 :   if( FD_UNLIKELY( err==FD_ACC_MGR_SUCCESS ) ) {
    1775           0 :     *meta = txn_out->accounts.metas[index];
    1776           0 :     return FD_ACC_MGR_SUCCESS;
    1777           0 :   }
    1778             : 
    1779           0 :   for( ushort i=0; i<runtime->accounts.executable_cnt; i++ ) {
    1780           0 :     if( memcmp( pubkey->uc, runtime->accounts.executable_pubkeys[i].uc, sizeof(fd_pubkey_t) )==0 ) {
    1781           0 :       *meta = runtime->accounts.executables_meta[i];
    1782           0 :       if( FD_UNLIKELY( !fd_account_meta_exists( *meta ) ) ) {
    1783           0 :         return FD_ACC_MGR_ERR_UNKNOWN_ACCOUNT;
    1784           0 :       }
    1785           0 :       return FD_ACC_MGR_SUCCESS;
    1786           0 :     }
    1787           0 :   }
    1788             : 
    1789           0 :   return FD_ACC_MGR_ERR_UNKNOWN_ACCOUNT;
    1790           0 : }
    1791             : 
    1792             : int
    1793             : fd_runtime_get_key_of_account_at_index( fd_txn_out_t *        txn_out,
    1794             :                                              ushort                idx,
    1795         264 :                                              fd_pubkey_t const * * key ) {
    1796             :   /* Return a NotEnoughAccountKeys error if idx is out of bounds.
    1797             :      https://github.com/anza-xyz/agave/blob/v2.1.14/sdk/src/transaction_context.rs#L218 */
    1798         264 :   if( FD_UNLIKELY( idx>=txn_out->accounts.cnt ) ) {
    1799           0 :     return FD_EXECUTOR_INSTR_ERR_MISSING_ACC;
    1800           0 :   }
    1801             : 
    1802         264 :   *key = &txn_out->accounts.keys[ idx ];
    1803         264 :   return FD_EXECUTOR_INSTR_SUCCESS;
    1804         264 : }
    1805             : 
    1806             : /* https://github.com/anza-xyz/agave/blob/v2.1.1/sdk/program/src/message/versions/v0/loaded.rs#L162 */
    1807             : int
    1808             : fd_txn_account_is_demotion( const int        idx,
    1809             :                             const fd_txn_t * txn_descriptor,
    1810           0 :                             const uint       bpf_upgradeable_in_txn ) {
    1811           0 :   uint is_program = 0U;
    1812           0 :   for( ulong j=0UL; j<txn_descriptor->instr_cnt; j++ ) {
    1813           0 :     if( txn_descriptor->instr[j].program_id == idx ) {
    1814           0 :       is_program = 1U;
    1815           0 :       break;
    1816           0 :     }
    1817           0 :   }
    1818             : 
    1819           0 :   return (is_program && !bpf_upgradeable_in_txn);
    1820           0 : }
    1821             : 
    1822             : uint
    1823             : fd_txn_account_has_bpf_loader_upgradeable( const fd_pubkey_t * account_keys,
    1824           0 :                                            const ulong         accounts_cnt ) {
    1825           0 :   for( ulong j=0; j<accounts_cnt; j++ ) {
    1826           0 :     const fd_pubkey_t * acc = &account_keys[j];
    1827           0 :     if ( memcmp( acc->uc, fd_solana_bpf_loader_upgradeable_program_id.key, sizeof(fd_pubkey_t) ) == 0 ) {
    1828           0 :       return 1U;
    1829           0 :     }
    1830           0 :   }
    1831           0 :   return 0U;
    1832           0 : }
    1833             : 
    1834             : static inline int
    1835             : fd_runtime_account_is_writable_idx_flat( const ulong           slot,
    1836             :                                          const ushort          idx,
    1837             :                                          const fd_pubkey_t *   addr_at_idx,
    1838             :                                          const fd_txn_t *      txn_descriptor,
    1839             :                                          const fd_features_t * features,
    1840           0 :                                          const uint            bpf_upgradeable_in_txn ) {
    1841             :   /* https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L43 */
    1842           0 :   if( !fd_txn_is_writable( txn_descriptor, idx ) ) {
    1843           0 :     return 0;
    1844           0 :   }
    1845             : 
    1846             :   /* See comments in fd_system_ids.h.
    1847             :      https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L44 */
    1848           0 :   if( fd_pubkey_is_active_reserved_key( addr_at_idx ) ||
    1849           0 :       fd_pubkey_is_pending_reserved_key( addr_at_idx ) ||
    1850           0 :       ( FD_FEATURE_ACTIVE( slot, features, enable_secp256r1_precompile ) &&
    1851           0 :                            fd_pubkey_is_secp256r1_key( addr_at_idx ) ) ) {
    1852             : 
    1853           0 :     return 0;
    1854           0 :   }
    1855             : 
    1856           0 :   if( fd_txn_account_is_demotion( idx, txn_descriptor, bpf_upgradeable_in_txn ) ) {
    1857           0 :     return 0;
    1858           0 :   }
    1859             : 
    1860           0 :   return 1;
    1861           0 : }
    1862             : 
    1863             : 
    1864             : /* This function aims to mimic the writable accounts check to populate the writable accounts cache, used
    1865             :    to determine if accounts are writable or not.
    1866             : 
    1867             :    https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L38-L47 */
    1868             : int
    1869             : fd_runtime_account_is_writable_idx( fd_txn_in_t const *  txn_in,
    1870             :                                     fd_txn_out_t const * txn_out,
    1871             :                                     fd_bank_t *          bank,
    1872           0 :                                     ushort               idx ) {
    1873           0 :   uint bpf_upgradeable = fd_txn_account_has_bpf_loader_upgradeable( txn_out->accounts.keys, txn_out->accounts.cnt );
    1874           0 :   return fd_runtime_account_is_writable_idx_flat( fd_bank_slot_get( bank ),
    1875           0 :                                                    idx,
    1876           0 :                                                    &txn_out->accounts.keys[idx],
    1877           0 :                                                    TXN( txn_in->txn ),
    1878           0 :                                                    fd_bank_features_query( bank ),
    1879           0 :                                                    bpf_upgradeable );
    1880           0 : }
    1881             : 
    1882             : /* Account pre-condition filtering functions */
    1883             : 
    1884             : int
    1885             : fd_runtime_account_check_exists( fd_txn_in_t const * txn_in,
    1886             :                                  fd_txn_out_t *      txn_out,
    1887           0 :                                  ushort              idx ) {
    1888           0 :   (void) txn_in;
    1889           0 :   return fd_account_meta_exists( txn_out->accounts.metas[idx] );
    1890           0 : }
    1891             : 
    1892             : int
    1893             : fd_runtime_account_check_fee_payer_writable( fd_txn_in_t const * txn_in,
    1894             :                                              fd_txn_out_t *      txn_out,
    1895           0 :                                              ushort              idx ) {
    1896           0 :   (void) txn_out;
    1897           0 :   return fd_txn_is_writable( TXN( txn_in->txn ), idx );
    1898           0 : }
    1899             : 
    1900             : 
    1901             : int
    1902           0 : fd_account_meta_checked_sub_lamports( fd_account_meta_t * meta, ulong lamports ) {
    1903           0 :   ulong balance_post = 0UL;
    1904           0 :   int err = fd_ulong_checked_sub( meta->lamports,
    1905           0 :                                   lamports,
    1906           0 :                                   &balance_post );
    1907           0 :   if( FD_UNLIKELY( err ) ) {
    1908           0 :     return FD_EXECUTOR_INSTR_ERR_ARITHMETIC_OVERFLOW;
    1909           0 :   }
    1910             : 
    1911           0 :   meta->lamports = balance_post;
    1912           0 :   return FD_EXECUTOR_INSTR_SUCCESS;
    1913           0 : }

Generated by: LCOV version 1.14