LCOV - code coverage report
Current view: top level - flamenco/runtime - fd_runtime.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 114 979 11.6 %
Date: 2025-10-27 04:40:00 Functions: 2 32 6.2 %

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

Generated by: LCOV version 1.14