LCOV - code coverage report
Current view: top level - flamenco/runtime/sysvar - fd_sysvar_clock.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 138 147 93.9 %
Date: 2026-08-25 04:35:19 Functions: 7 7 100.0 %

          Line data    Source code
       1             : #include "fd_sysvar_clock.h"
       2             : #include "fd_sysvar_epoch_schedule.h"
       3             : #include "../fd_runtime_stack.h"
       4             : #include "../fd_system_ids.h"
       5             : #include "../sysvar/fd_sysvar.h"
       6             : 
       7             : /* Syvar Clock Possible Values:
       8             :   slot:
       9             :   [0, ULONG_MAX]
      10             : 
      11             :   epoch:
      12             :   [0, slot/432000UL]
      13             : 
      14             :   epoch_start_timestamp:
      15             :   [0, ULONG_MAX]
      16             : 
      17             :   unix_timestamp:
      18             :   This value is bounded by the slot distance from the
      19             :   epoch_start_timestamp.
      20             :   The protocol allows for a maximum drift (either fast or slow) from the
      21             :   start of the epoch's timestamp.  The expected time is called the PoH
      22             :   offset.  This offset is calculated by (epoch_start_timestamp + slots
      23             :   since epoch * slot_duration). The drift is then bounded by the
      24             :   max_allowable_drift_{slow,fast}.  The stake weighted offset can be
      25             :   150% more than the PoH offset and 25% less than the PoH offset.
      26             :   So, the bounds for the unix_timestamp can be calculated by:
      27             :   upper bound = epoch_start_timestamp + (slots since epoch * slot_duration) * 2.5
      28             :   lower bound = epoch_start_timestamp + (slots since epoch * slot_duration) * 0.75
      29             : 
      30             :   leader_schedule_epoch:
      31             :   This is the value of the epoch used for the leader schedule.  It is
      32             :   computed based on the values of the epoch schedule (first_normal_slot,
      33             :   leader_schedule_slot_offset, slots_per_epoch).  It is always equal to
      34             :   ((slot - first_normal_slot) + leader_schedule_slot_offset) / schedule->slots_per_epoch
      35             : */
      36             : 
      37             : /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L14 */
      38        4041 : #define MAX_ALLOWABLE_DRIFT_FAST_PERCENT ( 25U )
      39             : 
      40             : /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L15 */
      41        4041 : #define MAX_ALLOWABLE_DRIFT_SLOW_PERCENT ( 150U )
      42             : 
      43             : /* Do all intermediate calculations at nanosecond precision, to mirror
      44             :    Solana's behavior. */
      45       15615 : #define NS_IN_S ((long)1e9)
      46             : 
      47             : /* FD_SYSVAR_CLOCK_STAKE_WEIGHTS_MAX specifies the max number of stake
      48             :    weights processed in a clock update. */
      49             : 
      50             : #define FD_SYSVAR_CLOCK_STAKE_WEIGHTS_MAX (10240UL)
      51             : 
      52             : /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/bank.rs#L2110-L2117 */
      53             : static inline long
      54           6 : unix_timestamp_from_genesis( fd_bank_t * bank ) {
      55             :   /* TODO: genesis_creation_time needs to be a long in the bank. */
      56           6 :   return fd_long_sat_add(
      57           6 :       (long)bank->f.genesis_creation_time,
      58           6 :       (long)( fd_uint128_sat_mul( bank->f.slot, bank->f.slot_params.ns_per_slot ) / NS_IN_S ) );
      59           6 : }
      60             : 
      61             : static void
      62             : fd_sysvar_clock_write( fd_bank_t *                   bank,
      63             :                        fd_accdb_t *                  accdb,
      64             :                        fd_capture_ctx_t *            capture_ctx,
      65        4476 :                        fd_sol_sysvar_clock_t const * clock ) {
      66        4476 :   fd_sysvar_account_update( bank, accdb, capture_ctx, &fd_sysvar_clock_id, clock, sizeof(fd_sol_sysvar_clock_t) );
      67        4476 : }
      68             : 
      69             : fd_sol_sysvar_clock_t *
      70             : fd_sysvar_clock_read( fd_accdb_t *            accdb,
      71             :                       fd_accdb_fork_id_t      fork_id,
      72        4485 :                       fd_sol_sysvar_clock_t * clock ) {
      73        4485 :   fd_acc_t acc = fd_accdb_read_one( accdb, fork_id, fd_sysvar_clock_id.uc );
      74        4485 :   if( FD_UNLIKELY( !acc.lamports || acc.data_len<sizeof(fd_sol_sysvar_clock_t) ) ) {
      75             :     /* This check is needed as a quirk of the fuzzer. If a sysvar
      76             :        account exists in the accounts database, but doesn't have any
      77             :        lamports, this means that the account does not exist.  This
      78             :        wouldn't happen in a real execution environment. */
      79           0 :     fd_accdb_unread_one( accdb, &acc );
      80           0 :     return NULL;
      81           0 :   }
      82             : 
      83        4485 :   fd_memcpy( clock, acc.data, sizeof(fd_sol_sysvar_clock_t) );
      84        4485 :   fd_accdb_unread_one( accdb, &acc );
      85        4485 :   return clock;
      86        4485 : }
      87             : 
      88             : void
      89             : fd_sysvar_clock_init( fd_bank_t *        bank,
      90             :                       fd_accdb_t *       accdb,
      91           6 :                       fd_capture_ctx_t * capture_ctx ) {
      92           6 :   long timestamp = unix_timestamp_from_genesis( bank );
      93             : 
      94           6 :   fd_sol_sysvar_clock_t clock = {
      95           6 :     .slot                  = bank->f.slot,
      96           6 :     .epoch                 = 0,
      97           6 :     .epoch_start_timestamp = timestamp,
      98           6 :     .leader_schedule_epoch = 1,
      99           6 :     .unix_timestamp        = timestamp,
     100           6 :   };
     101           6 :   fd_sysvar_clock_write( bank, accdb, capture_ctx, &clock );
     102           6 : }
     103             : 
     104             : #define SORT_NAME  sort_stake_ts
     105         534 : #define SORT_KEY_T ts_est_ele_t
     106         267 : #define SORT_BEFORE(a,b) ( (a).timestamp < (b).timestamp )
     107             : #include "../../../util/tmpl/fd_sort.c"
     108             : 
     109             : static void
     110             : accum_vote_stakes( fd_bank_t *          bank,
     111             :                    fd_runtime_stack_t * runtime_stack,
     112             :                    uint128 *            total_stake_out,
     113        4470 :                    ulong *              ts_ele_cnt_out ) {
     114             : 
     115        4470 :   ts_est_ele_t * ts_eles = runtime_stack->clock_ts.staked_ts;
     116        4470 :   ulong ts_ele_cnt = 0UL;
     117             : 
     118        4470 :   uint128 total_stake = 0UL;
     119             : 
     120        4470 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     121        4470 :   ulong                       current_slot   = bank->f.slot;
     122             : 
     123        4470 :   fd_vote_stakes_t * vote_stakes = fd_bank_vote_stakes( bank );
     124        4470 :   ulong              fork_id     = bank->vote_stakes_fork_id;
     125             : 
     126        4470 :   uchar __attribute__((aligned(FD_VOTE_STAKES_T_2_ITER_ALIGN))) iter_mem[ FD_VOTE_STAKES_T_2_ITER_FOOTPRINT ];
     127        4470 :   for( fd_vote_stakes_t_2_iter_t * iter = fd_vote_stakes_t_2_iter_init( vote_stakes, fork_id, iter_mem );
     128        9567 :        !fd_vote_stakes_t_2_iter_done( vote_stakes, fork_id, iter );
     129        5097 :        fd_vote_stakes_t_2_iter_next( vote_stakes, fork_id, iter ) ) {
     130        5097 :     fd_pubkey_t pubkey;
     131        5097 :     ulong       stake_t_2;
     132        5097 :     ulong       last_vote_slot;
     133        5097 :     long        last_vote_timestamp;
     134        5097 :     uchar       is_valid;
     135        5097 :     fd_vote_stakes_t_2_iter_ele( vote_stakes, fork_id, iter, &pubkey, NULL, &stake_t_2, &last_vote_slot, &last_vote_timestamp, NULL, &is_valid, NULL );
     136        5097 :     if( FD_UNLIKELY( !is_valid ) ) continue;
     137             : 
     138             :     /* https://github.com/anza-xyz/agave/blob/v3.0.0/runtime/src/bank.rs#L2445 */
     139        4911 :     if( FD_UNLIKELY( current_slot<last_vote_slot ) ) {
     140             :       /* Don't count vote accounts with a last vote slot that is greater
     141             :          than the current slot. */
     142           0 :       continue;
     143           0 :     }
     144        4911 :     ulong slot_delta = current_slot-last_vote_slot;
     145             : 
     146             :     /* Don't count vote accounts that haven't voted in the past 432k
     147             :         slots (length of an epoch).
     148             :         https://github.com/anza-xyz/agave/blob/v3.0.0/runtime/src/bank.rs#L2446-L2447 */
     149        4911 :     if( FD_UNLIKELY( slot_delta>epoch_schedule->slots_per_epoch ) ) {
     150         603 :       continue;
     151         603 :     }
     152             : 
     153             :     /* Calculate the timestamp estimate by taking the last vote
     154             :         timestamp and adding the estimated time since the last vote
     155             :         (delta from last vote slot to current slot * slot duration).
     156             :         https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L44-L45 */
     157        4308 :     ulong offset   = fd_slot_params_slot_range_duration_ns( bank, last_vote_slot+1UL, current_slot+1UL );
     158        4308 :     long  estimate = fd_long_sat_add( last_vote_timestamp, (long)(offset / NS_IN_S) );
     159             : 
     160             :     /* For each timestamp, accumulate the stake from E-2.  If the entry
     161             :         for the timestamp doesn't exist yet, insert it.  Otherwise,
     162             :         update the existing entry.
     163             :         https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L46-L53 */
     164        4308 :     ts_eles[ ts_ele_cnt ] = (ts_est_ele_t){
     165        4308 :       .timestamp = estimate,
     166        4308 :       .stake     = { .ud=stake_t_2 },
     167        4308 :     };
     168        4308 :     ts_ele_cnt++;
     169             : 
     170             :     /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L54 */
     171        4308 :     total_stake += stake_t_2;
     172        4308 :   }
     173             : 
     174        4470 :   *total_stake_out = total_stake;
     175        4470 :   *ts_ele_cnt_out  = ts_ele_cnt;
     176        4470 : }
     177             : 
     178             : /* get_timestamp_estimate calculates a timestamp estimate.  Does not
     179             :    modify the slot context.  Walks all cached vote accounts (from the
     180             :    "bank") and calculates a unix timestamp estimate. Returns the
     181             :    timestamp estimate.  spad is used for scratch allocations (allocates
     182             :    a treap of size FD_SYSVAR_CLOCK_STAKE_WEIGHTS_MAX). Crashes the
     183             :    process with FD_LOG_ERR on failure (e.g. too many vote accounts).
     184             : 
     185             :   https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/bank.rs#L2563-L2601 */
     186             : static long
     187             : get_timestamp_estimate( fd_bank_t *             bank,
     188             :                         fd_sol_sysvar_clock_t * clock,
     189             :                         fd_runtime_stack_t *    runtime_stack,
     190             :                         ulong const *           parent_epoch,
     191        4470 :                         int *                   out_estimate_present ) {
     192        4470 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     193        4470 :   ulong                       current_slot   = bank->f.slot;
     194             : 
     195        4470 :   ts_est_ele_t * ts_eles = runtime_stack->clock_ts.staked_ts;
     196             : 
     197             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L41 */
     198        4470 :   ulong  ts_ele_cnt   = 0UL;
     199        4470 :   uint128 total_stake = 0UL;
     200             : 
     201             :   /* A timestamp estimate is calculated at every slot using the most
     202             :      recent vote states of voting validators. This estimated is based on
     203             :      a stake weighted median using the stake as of the end of epoch E-2
     204             :      if we are currently in epoch E. We do not count vote accounts that
     205             :      have not voted in an epoch's worth of slots (432k). */
     206             : 
     207        4470 :   ulong curr_epoch = fd_slot_to_epoch( epoch_schedule, bank->f.slot, NULL );
     208             : 
     209        4470 :   accum_vote_stakes( bank, runtime_stack, &total_stake, &ts_ele_cnt );
     210             : 
     211             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L56-L58 */
     212        4470 :   if( FD_UNLIKELY( total_stake==0UL ) ) {
     213         429 :     *out_estimate_present = 0;
     214         429 :     return 0L;
     215         429 :   }
     216             : 
     217        4041 :   sort_stake_ts_inplace( ts_eles, ts_ele_cnt );
     218             : 
     219             :   /* Populate estimate with the stake-weighted median timestamp.
     220             :      https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L59-L68 */
     221        4041 :   uint128 stake_accumulator = 0;
     222        4041 :   long    estimate          = 0L;
     223        4308 :   for( ulong i=0UL; i<ts_ele_cnt; i++ ) {
     224        4308 :     stake_accumulator = fd_uint128_sat_add( stake_accumulator, ts_eles[i].stake.ud );
     225        4308 :     if( stake_accumulator>(total_stake/2UL) ) {
     226        4041 :       estimate = ts_eles[ i ].timestamp;
     227        4041 :       break;
     228        4041 :     }
     229        4308 :   }
     230             : 
     231             :   /* Bound estimate by `max_allowable_drift` since the start of the
     232             :      epoch.
     233             :      https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L69-L99 */
     234        4041 :   ulong epoch_for_start_slot  = parent_epoch ? *parent_epoch : curr_epoch;
     235        4041 :   ulong epoch_start_slot      = fd_epoch_slot0( epoch_schedule, epoch_for_start_slot );
     236        4041 :   long  epoch_start_timestamp = clock->epoch_start_timestamp;
     237             : 
     238             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L71-L72 */
     239        4041 :   ulong poh_estimate_offset = fd_slot_params_slot_range_duration_ns( bank, epoch_start_slot+1UL, current_slot+1UL );
     240             : 
     241             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L73-L77 */
     242        4041 :   ulong estimate_offset = fd_ulong_sat_mul( NS_IN_S, fd_ulong_sat_sub( (ulong)estimate, (ulong)epoch_start_timestamp ) );
     243             : 
     244             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L78-L81 */
     245        4041 :   ulong max_allowable_drift_fast = fd_ulong_sat_mul( poh_estimate_offset, MAX_ALLOWABLE_DRIFT_FAST_PERCENT ) / 100UL;
     246        4041 :   ulong max_allowable_drift_slow = fd_ulong_sat_mul( poh_estimate_offset, MAX_ALLOWABLE_DRIFT_SLOW_PERCENT ) / 100UL;
     247             : 
     248             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/stake_weighted_timestamp.rs#L82-L98 */
     249        4041 :   if( estimate_offset>poh_estimate_offset && fd_ulong_sat_sub( estimate_offset, poh_estimate_offset )>max_allowable_drift_slow ) {
     250          72 :     estimate = fd_long_sat_add(
     251          72 :         epoch_start_timestamp,
     252          72 :         fd_long_sat_add( (long)poh_estimate_offset / NS_IN_S, (long)max_allowable_drift_slow / NS_IN_S ) );
     253        3969 :   } else if( estimate_offset<poh_estimate_offset && fd_ulong_sat_sub( poh_estimate_offset, estimate_offset )>max_allowable_drift_fast ) {
     254        3558 :     estimate = fd_long_sat_sub(
     255        3558 :         fd_long_sat_add( epoch_start_timestamp, (long)poh_estimate_offset / NS_IN_S ),
     256        3558 :         (long)max_allowable_drift_fast / NS_IN_S );
     257        3558 :   }
     258             : 
     259        4041 :   *out_estimate_present = 1;
     260        4041 :   return estimate;
     261        4470 : }
     262             : 
     263             : /* TODO: This function should be called from genesis bootup as well with
     264             :    parent_epoch = NULL
     265             :    https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/bank.rs#L2158-L2215 */
     266             : void
     267             : fd_sysvar_clock_update( fd_bank_t *          bank,
     268             :                         fd_accdb_t *         accdb,
     269             :                         fd_capture_ctx_t *   capture_ctx,
     270             :                         fd_runtime_stack_t * runtime_stack,
     271        4470 :                         ulong const *        parent_epoch ) {
     272        4470 :   fd_sol_sysvar_clock_t clock_[1];
     273        4470 :   fd_sol_sysvar_clock_t * clock = fd_sysvar_clock_read( accdb, bank->accdb_fork_id, clock_ );
     274        4470 :   if( FD_UNLIKELY( !clock ) ) FD_LOG_ERR(( "fd_sysvar_clock_read failed" ));
     275             : 
     276        4470 :   fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
     277        4470 :   ulong                       current_slot   = bank->f.slot;
     278        4470 :   ulong                       current_epoch  = fd_slot_to_epoch( epoch_schedule, current_slot, NULL );
     279             : 
     280             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/bank.rs#L2159 */
     281        4470 :   long unix_timestamp = clock->unix_timestamp;
     282             : 
     283             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/bank.rs#L2175 */
     284        4470 :   long ancestor_timestamp = clock->unix_timestamp;
     285             : 
     286             :   /* TODO: Are we handling slot 0 correctly?
     287             :      https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/bank.rs#L2176-L2183 */
     288        4470 :   int  estimate_present   = 0;
     289        4470 :   long timestamp_estimate = get_timestamp_estimate( bank, clock, runtime_stack, parent_epoch, &estimate_present );
     290             : 
     291             :   /* If the timestamp was successfully calculated, use it. Otherwise,
     292             :      keep the old one. */
     293        4470 :   if( FD_LIKELY( estimate_present ) ) {
     294        4041 :     unix_timestamp = timestamp_estimate;
     295             : 
     296             :     /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/bank.rs#L2180-L2182 */
     297        4041 :     if( timestamp_estimate<ancestor_timestamp ) {
     298           3 :       unix_timestamp = ancestor_timestamp;
     299           3 :     }
     300        4041 :   }
     301             : 
     302             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/bank.rs#L2191-L2197 */
     303        4470 :   long epoch_start_timestamp = (parent_epoch!=NULL && *parent_epoch!=current_epoch) ?
     304         270 :       unix_timestamp :
     305        4470 :       clock->epoch_start_timestamp;
     306             : 
     307             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/bank.rs#L2198-L2201 */
     308        4470 :   if( FD_UNLIKELY( current_slot==0UL ) ) {
     309           0 :     long timestamp_from_genesis = unix_timestamp_from_genesis( bank );
     310           0 :     unix_timestamp              = timestamp_from_genesis;
     311           0 :     epoch_start_timestamp       = timestamp_from_genesis;
     312           0 :   }
     313             : 
     314             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/bank.rs#L2202-L2208 */
     315        4470 :   *clock = (fd_sol_sysvar_clock_t){
     316        4470 :     .slot                  = current_slot,
     317        4470 :     .epoch_start_timestamp = epoch_start_timestamp,
     318        4470 :     .epoch                 = current_epoch,
     319        4470 :     .leader_schedule_epoch = fd_slot_to_leader_schedule_epoch( epoch_schedule, current_slot ),
     320        4470 :     .unix_timestamp        = unix_timestamp,
     321        4470 :   };
     322             : 
     323             :   /* https://github.com/anza-xyz/agave/blob/v2.3.7/runtime/src/bank.rs#L2209-L2214 */
     324        4470 :   fd_sysvar_clock_write( bank, accdb, capture_ctx, clock );
     325        4470 : }

Generated by: LCOV version 1.14