LCOV - code coverage report
Current view: top level - discof/replay - fd_replay_tile.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 0 1539 0.0 %
Date: 2026-01-20 05:22:11 Functions: 0 43 0.0 %

          Line data    Source code
       1             : #include "fd_replay_tile.h"
       2             : #include "fd_sched.h"
       3             : #include "fd_exec.h"
       4             : #include "fd_vote_tracker.h"
       5             : #include "generated/fd_replay_tile_seccomp.h"
       6             : 
       7             : #include "../genesis/fd_genesi_tile.h"
       8             : #include "../poh/fd_poh.h"
       9             : #include "../poh/fd_poh_tile.h"
      10             : #include "../tower/fd_tower_tile.h"
      11             : #include "../resolv/fd_resolv_tile.h"
      12             : #include "../restore/utils/fd_ssload.h"
      13             : 
      14             : #include "../../disco/tiles.h"
      15             : #include "../../disco/fd_txn_m.h"
      16             : #include "../../disco/store/fd_store.h"
      17             : #include "../../disco/pack/fd_pack.h"
      18             : #include "../../discof/reasm/fd_reasm.h"
      19             : #include "../../disco/keyguard/fd_keyload.h"
      20             : #include "../../disco/genesis/fd_genesis_cluster.h"
      21             : #include "../../util/pod/fd_pod.h"
      22             : #include "../../flamenco/accdb/fd_accdb_admin_v1.h"
      23             : #include "../../flamenco/accdb/fd_accdb_impl_v1.h"
      24             : #include "../../flamenco/accdb/fd_accdb_impl_v2.h"
      25             : #include "../../flamenco/accdb/fd_accdb_sync.h"
      26             : #include "../../flamenco/accdb/fd_vinyl_req_pool.h"
      27             : #include "../../flamenco/rewards/fd_rewards.h"
      28             : #include "../../flamenco/leaders/fd_multi_epoch_leaders.h"
      29             : #include "../../flamenco/progcache/fd_progcache_admin.h"
      30             : #include "../../disco/metrics/fd_metrics.h"
      31             : 
      32             : #include "../../flamenco/runtime/fd_runtime.h"
      33             : #include "../../flamenco/runtime/fd_runtime_stack.h"
      34             : #include "../../flamenco/runtime/fd_genesis_parse.h"
      35             : #include "../../flamenco/fd_flamenco_base.h"
      36             : #include "../../flamenco/runtime/sysvar/fd_sysvar_epoch_schedule.h"
      37             : 
      38             : #include "../../flamenco/runtime/tests/fd_dump_pb.h"
      39             : 
      40             : #include <errno.h>
      41             : #include <stdio.h>
      42             : 
      43             : /* Replay concepts:
      44             : 
      45             :    - Blocks are aggregations of entries aka. microblocks which are
      46             :      groupings of txns and are constructed by the block producer (see
      47             :      fd_pack).
      48             : 
      49             :    - Entries are grouped into entry batches by the block producer (see
      50             :      fd_pack / fd_shredder).
      51             : 
      52             :    - Entry batches are divided into chunks known as shreds by the block
      53             :      producer (see fd_shredder).
      54             : 
      55             :    - Shreds are grouped into forward-error-correction sets (FEC sets) by
      56             :      the block producer (see fd_shredder).
      57             : 
      58             :    - Shreds are transmitted to the rest of the cluster via the Turbine
      59             :      protocol (see fd_shredder / fd_shred).
      60             : 
      61             :    - Once enough shreds within a FEC set are received to recover the
      62             :      entirety of the shred data encoded by that FEC set, the receiver
      63             :      can "complete" the FEC set (see fd_fec_resolver).
      64             : 
      65             :    - If shreds in the FEC set are missing such that it can't complete,
      66             :      the receiver can use the Repair protocol to request missing shreds
      67             :      in FEC set (see fd_repair).
      68             : 
      69             :   -  The current Repair protocol does not support requesting coding
      70             :      shreds.  As a result, some FEC sets might be actually complete
      71             :      (contain all data shreds).  Repair currently hacks around this by
      72             :      forcing completion but the long-term solution is to add support for
      73             :      fec_repairing coding shreds via Repair.
      74             : 
      75             :   - FEC sets are delivered in partial-order to the Replay tile by the
      76             :     Repair tile.  Currently Replay only supports replaying entry batches
      77             :     so FEC sets need to reassembled into an entry batch before they can
      78             :     be replayed.  The new Dispatcher will change this by taking a FEC
      79             :     set as input instead. */
      80             : 
      81           0 : #define IN_KIND_SNAP    ( 0)
      82           0 : #define IN_KIND_GENESIS ( 1)
      83           0 : #define IN_KIND_IPECHO  ( 2)
      84           0 : #define IN_KIND_TOWER   ( 3)
      85           0 : #define IN_KIND_RESOLV  ( 4)
      86           0 : #define IN_KIND_POH     ( 5)
      87           0 : #define IN_KIND_EXEC    ( 6)
      88           0 : #define IN_KIND_SHRED   ( 7)
      89           0 : #define IN_KIND_VTXN    ( 8)
      90           0 : #define IN_KIND_GUI     ( 9)
      91           0 : #define IN_KIND_RPC     (10)
      92             : 
      93             : #define DEBUG_LOGGING 0
      94             : 
      95             : /* The first bank that the replay tile produces either for genesis
      96             :    or the snapshot boot will always be at bank index 0. */
      97           0 : #define FD_REPLAY_BOOT_BANK_IDX (0UL)
      98             : 
      99             : struct fd_replay_in_link {
     100             :   fd_wksp_t * mem;
     101             :   ulong       chunk0;
     102             :   ulong       wmark;
     103             :   ulong       mtu;
     104             : };
     105             : 
     106             : typedef struct fd_replay_in_link fd_replay_in_link_t;
     107             : 
     108             : struct fd_replay_out_link {
     109             :   ulong       idx;
     110             :   fd_wksp_t * mem;
     111             :   ulong       chunk0;
     112             :   ulong       wmark;
     113             :   ulong       chunk;
     114             : };
     115             : 
     116             : typedef struct fd_replay_out_link fd_replay_out_link_t;
     117             : 
     118             : /* fd_block_id_map is a simple map of block-ids to bank indices.  The
     119             :    map sits on top of an array of fd_block_id_ele_t.  This serves as a
     120             :    translation layer between block ids to bank indices. */
     121             : 
     122             : struct fd_block_id_ele {
     123             :   fd_hash_t block_id;
     124             :   int       block_id_seen;
     125             :   ulong     slot;
     126             :   ulong     next_;
     127             : };
     128             : typedef struct fd_block_id_ele fd_block_id_ele_t;
     129             : 
     130             : #define MAP_NAME               fd_block_id_map
     131             : #define MAP_ELE_T              fd_block_id_ele_t
     132             : #define MAP_KEY_T              fd_hash_t
     133           0 : #define MAP_KEY                block_id
     134           0 : #define MAP_NEXT               next_
     135           0 : #define MAP_KEY_EQ(k0,k1)      (!memcmp((k0),(k1), sizeof(fd_hash_t)))
     136           0 : #define MAP_KEY_HASH(key,seed) (fd_hash((seed),(key),sizeof(fd_hash_t)))
     137             : #include "../../util/tmpl/fd_map_chain.c"
     138             : 
     139             : static inline ulong
     140           0 : fd_block_id_ele_get_idx( fd_block_id_ele_t * ele_arr, fd_block_id_ele_t * ele ) {
     141           0 :   return (ulong)(ele - ele_arr);
     142           0 : }
     143             : 
     144             : struct fd_replay_tile {
     145             :   fd_wksp_t * wksp;
     146             : 
     147             :   fd_accdb_admin_t     accdb_admin[1];
     148             :   fd_accdb_user_t      accdb[1];
     149             :   fd_progcache_admin_t progcache_admin[1];
     150             : 
     151             :   fd_txncache_t * txncache;
     152             :   fd_store_t *    store;
     153             :   fd_banks_t      banks[1];
     154             : 
     155             :   /* This flag is 1 If we have seen a vote signature that our node has
     156             :      sent out get rooted at least one time.  The value is 0 otherwise.
     157             :      We can't become leader and pack blocks until this flag has been
     158             :      set.  This parallels the Agave 'has_new_vote_been_rooted'.
     159             : 
     160             :      TODO: Add a flag to the toml to make this optional. */
     161             :   int has_identity_vote_rooted;
     162             : 
     163             :   ulong        reasm_seed;
     164             :   fd_reasm_t * reasm;
     165             : 
     166             :   /* Replay state machine. */
     167             :   fd_sched_t *         sched;
     168             :   ulong                exec_cnt;
     169             :   fd_replay_out_link_t exec_out[ 1 ]; /* Sending work down to exec tiles */
     170             : 
     171             :   ulong                vote_tracker_seed;
     172             :   fd_vote_tracker_t *  vote_tracker;
     173             : 
     174             :   int   has_genesis_hash;
     175             :   char  genesis_path[ PATH_MAX ];
     176             :   uchar genesis_hash[ 32UL ];
     177             :   ulong cluster_type;
     178             : 
     179             : #define FD_REPLAY_HARD_FORKS_MAX (64UL)
     180             :   ulong hard_forks_cnt;
     181             :   ulong hard_forks[ FD_REPLAY_HARD_FORKS_MAX ];
     182             : 
     183             :   ushort expected_shred_version;
     184             :   ushort ipecho_shred_version;
     185             : 
     186             :   /* A note on publishing ...
     187             : 
     188             :      The watermarks are used to publish our fork-aware structures.  For
     189             :      example, store, banks, and txncache need to be published to release
     190             :      resources occupied by rooted or dead blocks.  In general,
     191             :      publishing has the effect of pruning forks in those structures,
     192             :      indicating that it is ok to release the memory being occupied by
     193             :      the blocks on said forks.  Tower is responsible for informing us of
     194             :      the latest block on the consensus rooted fork.  As soon as we can,
     195             :      we should move the published root as close as possible to the
     196             :      latest consensus root, publishing/pruning everything on the fork
     197             :      tree along the way.  That is, all the blocks that directly descend
     198             :      from the current published root (inclusive) to the new published
     199             :      root (exclusive) on the rooted fork, as well as all the minority
     200             :      forks that branch from said blocks.
     201             : 
     202             :      Ideally, we'd move the published root to the consensus root
     203             :      immediately upon receiving a new consensus root.  However, that's
     204             :      not always safe to do.  One thing we need to be careful about is
     205             :      making sure that there are no more users/consumers of
     206             :      soon-to-be-pruned blocks, lest a use-after-free occurs.  This can
     207             :      be done by using a reference counter for each block.  Any
     208             :      concurrent activity, such as transaction execution in the exec
     209             :      tiles, should retain a refcnt on the block for as
     210             :      long as it needs access to the shared fork-aware structures related
     211             :      to that block.  Eventually, refcnt on a given block will drop down
     212             :      to 0 as the block either finishes replaying or gets marked as dead,
     213             :      and any other tile that has retained a refcnt on the block releases
     214             :      it.  At that point, it becomes a candidate for pruning.  The key to
     215             :      safe publishing then becomes figuring out how far we could advance
     216             :      the published root, such that every minority fork branching off of
     217             :      blocks in between the current published root (inclusive) and the
     218             :      new published root (exclusive) is safe to be pruned.  This is a
     219             :      straightforward tree traversal, where if a block B on the rooted
     220             :      fork has refcnt 0, and all minority forks branching off of B also
     221             :      have refcnt 0, then B is safe to be pruned.  We advance the
     222             :      published root to the farthest consecutively prunable block on the
     223             :      rooted fork.  Note that reasm presents the replay tile with a clean
     224             :      view of the world where every block is chained off of a parent
     225             :      block.  So there are no orpahned/dangling tree nodes to worry
     226             :      about.  The world is a nice single tree as far as replay is
     227             :      concerned.
     228             : 
     229             :      In the following fork tree, every node is a block and the number in
     230             :      parentheses is the refcnt on the block.  The chain marked with
     231             :      double slashes is the rooted fork.  Suppose the published root is
     232             :      at block P, and consensus root is at block T.  We can't publish
     233             :      past block P because Q has refcnt 1.
     234             : 
     235             : 
     236             :           P(0)
     237             :         /    \\
     238             :       Q(1)    A(0)
     239             :             / ||  \
     240             :         X(0) B(0)  C(0)
     241             :        /      || \
     242             :       Y(0)   M(0) R(0)
     243             :             / ||   /  \
     244             :         D(2) T(0) J(0) L(0)
     245             :               ||
     246             :               ..
     247             :               ..
     248             :               ..
     249             :               ||
     250             :       blocks we might be actively replaying
     251             : 
     252             : 
     253             :      When refcnt on Q drops to 0, we would be able to advance the
     254             :      published root to block M, because blocks P, A, and B, as well as
     255             :      all subtrees branching off of them, have refcnt 0, and therefore
     256             :      can be pruned.  Block M itself cannot be pruned yet because its
     257             :      child block D has refcnt 2.  After publishing/pruning, the fork
     258             :      tree would be:
     259             : 
     260             : 
     261             :              M(0)
     262             :             / ||
     263             :         D(2) T(0)
     264             :               ||
     265             :               ..
     266             :               ..
     267             :               ..
     268             :               ||
     269             :       blocks we might be actively replaying
     270             : 
     271             : 
     272             :      As a result, the shared fork-aware structures can free resources
     273             :      for blocks P, A, B, and all subtrees branching off of them.
     274             : 
     275             :      For the reference counting part, the replay tile is the sole entity
     276             :      that can update the refcnt.  This ensures that all refcnt increment
     277             :      and decrement attempts are serialized at the replay tile, and that
     278             :      there are no racy resurrection of a soon-to-be-pruned block.  If a
     279             :      refcnt increment request arrives after a block has been pruned,
     280             :      replay simply rejects the request.
     281             : 
     282             :      A note on the implementation of the above ...
     283             : 
     284             :      Upon receiving a new consensus root, we descend down the rooted
     285             :      fork from the current published root to the new consensus root.  On
     286             :      each node/block of the rooted fork, we do a summation of the refcnt
     287             :      on the block and all the minority fork blocks branching from the
     288             :      block.  If the summation is 0, the block is safe for pruning.  We
     289             :      advance the published root to the far end of the consecutive run of
     290             :      0 refcnt sums originating from the current published root.  On our
     291             :      descent down the minority forks, we also mark any block that hasn't
     292             :      finished replaying as dead, so we don't waste time executing them.
     293             :      No more transactions shall be dispatched for execution from dead
     294             :      blocks.
     295             : 
     296             :      Blocks start out with a refcnt of 0.  Other tiles may send a
     297             :      request to the replay tile for a reference on a block.  The
     298             :      transaction dispatcher is another source of refcnt updates.  On
     299             :      every dispatch of a transaction for block B, we increment the
     300             :      refcnt for B.  And on every transaction finalization, we decrement
     301             :      the refcnt for B.  This means that whenever the refcnt on a block
     302             :      is 0, there is no more reference on that block from the execution
     303             :      pipeline.  While it might be tempting to simply increment the
     304             :      refcnt once when we start replaying a block, and decrement the
     305             :      refcnt once when we finish a block, this more fine-grained refcnt
     306             :      update strategy allows for aborting and potentially immediate
     307             :      pruning of blocks under interleaved block replay.  Upon receiving a
     308             :      new consensus root, we can simply look at the refcnt on minority
     309             :      fork blocks, and a refcnt of 0 would imply that the block is safe
     310             :      for pruning, even if we haven't finished replaying it.  Without the
     311             :      fine-grained refcnt, we would need to first stop dispatching from
     312             :      the aborted block, and then wait for a full drain of the execution
     313             :      pipeline to know for sure that there are no more in-flight
     314             :      transactions executing on the aborted block.  Note that this will
     315             :      allow the refcnt on any block to transiently drop down to 0.  We
     316             :      will not mistakenly prune an actively replaying block, aka a leaf
     317             :      node, that is chaining off of the rooted fork, because the
     318             :      consensus root is always an ancestor of the actively replaying tip.
     319             :      */
     320             :   fd_hash_t consensus_root;          /* The most recent block to have reached max lockout in the tower. */
     321             :   ulong     consensus_root_slot;     /* slot number of the above. */
     322             :   ulong     consensus_root_bank_idx; /* bank index of the above. */
     323             :   ulong     published_root_slot;     /* slot number of the published root. */
     324             :   ulong     published_root_bank_idx; /* bank index of the published root. */
     325             : 
     326             :   /* We need to maintain a tile-local mapping of block-ids to bank index
     327             :      and vice versa.  This translation layer is needed for conversion
     328             :      since tower operates on block-ids and downstream consumers of FEC
     329             :      sets operate on bank indices.  This mapping must happen both ways:
     330             :      1. tower sends us block ids and we must map them to bank indices.
     331             :      2. when a block is completed, we must map the bank index to a block
     332             :         id to send a slot complete message to tower. */
     333             :   ulong               block_id_len;
     334             :   fd_block_id_ele_t * block_id_arr;
     335             :   ulong               block_id_map_seed;
     336             :   fd_block_id_map_t * block_id_map;
     337             : 
     338             :   /* Capture-related configs */
     339             :   fd_capture_ctx_t *     capture_ctx;
     340             :   FILE *                 capture_file;
     341             :   fd_capture_link_buf_t  cap_repl_out[1];
     342             : 
     343             :   /* Whether the runtime has been booted either from snapshot loading
     344             :      or from genesis. */
     345             :   int is_booted;
     346             : 
     347             :   /* Buffer to store vote towers that need to be published to the Tower
     348             :      tile. */
     349             : 
     350             :   fd_multi_epoch_leaders_t * mleaders;
     351             : 
     352             :   int larger_max_cost_per_block;
     353             : 
     354             :   fd_pubkey_t identity_pubkey[1]; /* TODO: Keyswitch */
     355             : 
     356             :   /* When we transition to becoming leader, we can only unbecome the
     357             :      leader if we have received a block id from the FEC reassembler, and
     358             :      a message from PoH that the leader slot has ended.  After both of
     359             :      these conditions are met, then we are free to unbecome the leader.
     360             :   */
     361             :   int         is_leader;
     362             :   int         recv_poh;
     363             :   ulong       next_leader_slot;
     364             :   long        next_leader_tickcount;
     365             :   ulong       highwater_leader_slot;
     366             :   ulong       reset_slot;
     367             :   fd_bank_t   reset_bank[1];
     368             :   fd_hash_t   reset_block_id;
     369             :   long        reset_timestamp_nanos;
     370             :   double      slot_duration_nanos;
     371             :   double      slot_duration_ticks;
     372             :   fd_bank_t   leader_bank[1];
     373             : 
     374             :   ulong  resolv_tile_cnt;
     375             : 
     376             :   int in_kind[ 64 ];
     377             :   fd_replay_in_link_t in[ 64 ];
     378             : 
     379             :   fd_replay_out_link_t replay_out[1];
     380             : 
     381             :   fd_replay_out_link_t stake_out[1];
     382             : 
     383             :   /* The gui tile needs to reliably own a reference to the most recent
     384             :      completed active bank.  Replay needs to know if the gui as a
     385             :      consumer is enabled so it can increment the bank's refcnt before
     386             :      publishing the bank_idx to the gui. */
     387             :   int gui_enabled;
     388             :   int rpc_enabled;
     389             : 
     390             : # if FD_HAS_FLATCC
     391             :   /* For dumping blocks to protobuf. For backtest only. */
     392             :   fd_block_dump_ctx_t * block_dump_ctx;
     393             : # endif
     394             : 
     395             :   /* We need a few pieces of information to compute the right addresses
     396             :      for bundle crank information that we need to send to pack. */
     397             :   struct {
     398             :     int                   enabled;
     399             :     fd_pubkey_t           vote_account;
     400             :     fd_bundle_crank_gen_t gen[1];
     401             :   } bundle;
     402             : 
     403             :   struct {
     404             :     fd_histf_t store_read_wait[ 1 ];
     405             :     fd_histf_t store_read_work[ 1 ];
     406             :     fd_histf_t store_publish_wait[ 1 ];
     407             :     fd_histf_t store_publish_work[ 1 ];
     408             :     fd_histf_t store_link_wait[ 1 ];
     409             :     fd_histf_t store_link_work[ 1 ];
     410             : 
     411             :     ulong slots_total;
     412             :     ulong transactions_total;
     413             : 
     414             :     ulong reasm_latest_slot;
     415             :     ulong reasm_latest_fec_idx;
     416             : 
     417             :     ulong sched_full;
     418             :     ulong reasm_empty;
     419             :     ulong leader_bid_wait;
     420             :     ulong banks_full;
     421             :     ulong storage_root_behind;
     422             :   } metrics;
     423             : 
     424             :   uchar __attribute__((aligned(FD_MULTI_EPOCH_LEADERS_ALIGN))) mleaders_mem[ FD_MULTI_EPOCH_LEADERS_FOOTPRINT ];
     425             : 
     426             :   fd_runtime_stack_t runtime_stack;
     427             : };
     428             : 
     429             : typedef struct fd_replay_tile fd_replay_tile_t;
     430             : 
     431             : FD_FN_CONST static inline ulong
     432           0 : scratch_align( void ) {
     433           0 :   return 128UL;
     434           0 : }
     435             : FD_FN_PURE static inline ulong
     436           0 : scratch_footprint( fd_topo_tile_t const * tile ) {
     437           0 :   ulong chain_cnt = fd_block_id_map_chain_cnt_est( tile->replay.max_live_slots );
     438             : 
     439           0 :   ulong l = FD_LAYOUT_INIT;
     440           0 :   l = FD_LAYOUT_APPEND( l, alignof(fd_replay_tile_t),  sizeof(fd_replay_tile_t) );
     441           0 :   l = FD_LAYOUT_APPEND( l, alignof(fd_block_id_ele_t), sizeof(fd_block_id_ele_t) * tile->replay.max_live_slots );
     442           0 :   l = FD_LAYOUT_APPEND( l, fd_block_id_map_align(),    fd_block_id_map_footprint( chain_cnt ) );
     443           0 :   l = FD_LAYOUT_APPEND( l, fd_txncache_align(),        fd_txncache_footprint( tile->replay.max_live_slots ) );
     444           0 :   l = FD_LAYOUT_APPEND( l, fd_reasm_align(),           fd_reasm_footprint( tile->replay.fec_max ) );
     445           0 :   l = FD_LAYOUT_APPEND( l, fd_sched_align(),           fd_sched_footprint( tile->replay.max_live_slots ) );
     446           0 :   l = FD_LAYOUT_APPEND( l, fd_vinyl_req_pool_align(),  fd_vinyl_req_pool_footprint( 1UL, 1UL ) );
     447           0 :   l = FD_LAYOUT_APPEND( l, fd_vote_tracker_align(),    fd_vote_tracker_footprint() );
     448           0 :   l = FD_LAYOUT_APPEND( l, fd_capture_ctx_align(),     fd_capture_ctx_footprint() );
     449             : 
     450           0 : # if FD_HAS_FLATCC
     451           0 :   if( FD_UNLIKELY( tile->replay.dump_block_to_pb ) ) {
     452           0 :     l = FD_LAYOUT_APPEND( l, fd_block_dump_context_align(), fd_block_dump_context_footprint() );
     453           0 :   }
     454           0 : # endif
     455             : 
     456           0 :   l = FD_LAYOUT_FINI( l, scratch_align() );
     457             : 
     458           0 :   return l;
     459           0 : }
     460             : 
     461             : static inline void
     462           0 : metrics_write( fd_replay_tile_t * ctx ) {
     463           0 :   FD_MHIST_COPY( REPLAY, STORE_LINK_WAIT,    ctx->metrics.store_link_wait );
     464           0 :   FD_MHIST_COPY( REPLAY, STORE_LINK_WORK,    ctx->metrics.store_link_work );
     465           0 :   FD_MHIST_COPY( REPLAY, STORE_READ_WAIT,    ctx->metrics.store_read_wait );
     466           0 :   FD_MHIST_COPY( REPLAY, STORE_READ_WORK,    ctx->metrics.store_read_work );
     467           0 :   FD_MHIST_COPY( REPLAY, STORE_PUBLISH_WAIT, ctx->metrics.store_publish_wait );
     468           0 :   FD_MHIST_COPY( REPLAY, STORE_PUBLISH_WORK, ctx->metrics.store_publish_work );
     469             : 
     470           0 :   FD_MGAUGE_SET( REPLAY, ROOT_SLOT, ctx->consensus_root_slot==ULONG_MAX ? 0UL : ctx->consensus_root_slot );
     471           0 :   ulong leader_slot = ctx->leader_bank->data ? fd_bank_slot_get( ctx->leader_bank ) : 0UL;
     472           0 :   FD_MGAUGE_SET( REPLAY, LEADER_SLOT, leader_slot );
     473             : 
     474           0 :   if( FD_LIKELY( ctx->leader_bank->data ) ) {
     475           0 :     FD_MGAUGE_SET( REPLAY, NEXT_LEADER_SLOT, leader_slot );
     476           0 :     FD_MGAUGE_SET( REPLAY, LEADER_SLOT, leader_slot );
     477           0 :   } else {
     478           0 :     FD_MGAUGE_SET( REPLAY, NEXT_LEADER_SLOT, ctx->next_leader_slot==ULONG_MAX ? 0UL : ctx->next_leader_slot );
     479           0 :     FD_MGAUGE_SET( REPLAY, LEADER_SLOT, 0UL );
     480           0 :   }
     481           0 :   FD_MGAUGE_SET( REPLAY, RESET_SLOT, ctx->reset_slot==ULONG_MAX ? 0UL : ctx->reset_slot );
     482             : 
     483           0 :   fd_bank_data_t * bank_pool = fd_banks_get_bank_pool( ctx->banks->data );
     484           0 :   ulong live_banks = fd_banks_pool_max( bank_pool ) - fd_banks_pool_free( bank_pool );
     485           0 :   FD_MGAUGE_SET( REPLAY, LIVE_BANKS, live_banks );
     486             : 
     487           0 :   ulong reasm_free = fd_reasm_free( ctx->reasm );
     488           0 :   FD_MGAUGE_SET( REPLAY, REASM_FREE, reasm_free );
     489             : 
     490           0 :   FD_MCNT_SET( REPLAY, SLOTS_TOTAL, ctx->metrics.slots_total );
     491           0 :   FD_MCNT_SET( REPLAY, TRANSACTIONS_TOTAL, ctx->metrics.transactions_total );
     492             : 
     493           0 :   FD_MGAUGE_SET( REPLAY, REASM_LATEST_SLOT,    ctx->metrics.reasm_latest_slot );
     494           0 :   FD_MGAUGE_SET( REPLAY, REASM_LATEST_FEC_IDX, ctx->metrics.reasm_latest_fec_idx );
     495             : 
     496           0 :   FD_MCNT_SET( REPLAY, SCHED_FULL,          ctx->metrics.sched_full );
     497           0 :   FD_MCNT_SET( REPLAY, REASM_EMPTY,         ctx->metrics.reasm_empty );
     498           0 :   FD_MCNT_SET( REPLAY, LEADER_BID_WAIT,     ctx->metrics.leader_bid_wait );
     499           0 :   FD_MCNT_SET( REPLAY, BANKS_FULL,          ctx->metrics.banks_full );
     500           0 :   FD_MCNT_SET( REPLAY, STORAGE_ROOT_BEHIND, ctx->metrics.storage_root_behind );
     501             : 
     502           0 :   FD_MCNT_SET( REPLAY, PROGCACHE_ROOTED,  ctx->progcache_admin->metrics.root_cnt );
     503           0 :   FD_MCNT_SET( REPLAY, PROGCACHE_GC_ROOT, ctx->progcache_admin->metrics.gc_root_cnt );
     504             : 
     505           0 :   FD_MCNT_SET( REPLAY, ACCDB_CREATED,   ctx->accdb->base.created_cnt       );
     506           0 :   FD_MCNT_SET( REPLAY, ACCDB_REVERTED,  ctx->accdb_admin->base.revert_cnt  );
     507           0 :   FD_MCNT_SET( REPLAY, ACCDB_ROOTED,    ctx->accdb_admin->base.root_cnt    );
     508           0 :   FD_MCNT_SET( REPLAY, ACCDB_GC_ROOT,   ctx->accdb_admin->base.gc_root_cnt );
     509           0 :   FD_MCNT_SET( REPLAY, ACCDB_RECLAIMED, ctx->accdb_admin->base.reclaim_cnt );
     510           0 : }
     511             : 
     512             : static inline ulong
     513             : generate_stake_weight_msg( ulong                       epoch,
     514             :                            fd_epoch_schedule_t const * epoch_schedule,
     515             :                            fd_vote_states_t const *    epoch_stakes,
     516           0 :                            ulong *                     stake_weight_msg_out ) {
     517           0 :   fd_stake_weight_msg_t *  stake_weight_msg = (fd_stake_weight_msg_t *)fd_type_pun( stake_weight_msg_out );
     518           0 :   fd_vote_stake_weight_t * stake_weights    = stake_weight_msg->weights;
     519             : 
     520           0 :   stake_weight_msg->epoch             = epoch;
     521           0 :   stake_weight_msg->start_slot        = fd_epoch_slot0( epoch_schedule, epoch );
     522           0 :   stake_weight_msg->slot_cnt          = epoch_schedule->slots_per_epoch;
     523           0 :   stake_weight_msg->excluded_stake    = 0UL;
     524           0 :   stake_weight_msg->vote_keyed_lsched = 1UL;
     525             : 
     526             :   /* FIXME: SIMD-0180 - hack to (de)activate in testnet vs mainnet.
     527             :      This code can be removed once the feature is active. */
     528           0 :   if( (1==epoch_schedule->warmup && epoch<FD_SIMD0180_ACTIVE_EPOCH_TESTNET) ||
     529           0 :       (0==epoch_schedule->warmup && epoch<FD_SIMD0180_ACTIVE_EPOCH_MAINNET) ) {
     530           0 :     stake_weight_msg->vote_keyed_lsched = 0UL;
     531           0 :   }
     532             : 
     533             :   /* epoch_stakes from manifest are already filtered (stake>0), but not sorted */
     534           0 :   fd_vote_states_iter_t iter_[1];
     535           0 :   ulong idx = 0UL;
     536           0 :   for( fd_vote_states_iter_t * iter = fd_vote_states_iter_init( iter_, epoch_stakes ); !fd_vote_states_iter_done( iter ); fd_vote_states_iter_next( iter ) ) {
     537           0 :     fd_vote_state_ele_t * vote_state = fd_vote_states_iter_ele( iter );
     538           0 :     if( FD_UNLIKELY( !vote_state->stake ) ) continue;
     539             : 
     540           0 :     stake_weights[ idx ].stake = vote_state->stake;
     541           0 :     memcpy( stake_weights[ idx ].id_key.uc, &vote_state->node_account, sizeof(fd_pubkey_t) );
     542           0 :     memcpy( stake_weights[ idx ].vote_key.uc, &vote_state->vote_account, sizeof(fd_pubkey_t) );
     543           0 :     idx++;
     544           0 :   }
     545           0 :   stake_weight_msg->staked_cnt = idx;
     546           0 :   sort_vote_weights_by_stake_vote_inplace( stake_weights, idx );
     547             : 
     548           0 :   return fd_stake_weight_msg_sz( idx );
     549           0 : }
     550             : 
     551             : static void
     552             : publish_stake_weights( fd_replay_tile_t *   ctx,
     553             :                        fd_stem_context_t *  stem,
     554             :                        fd_bank_t *          bank,
     555           0 :                        int                  current_epoch ) {
     556           0 :   fd_epoch_schedule_t const * schedule = fd_bank_epoch_schedule_query( bank );
     557           0 :   ulong epoch = fd_slot_to_epoch( schedule, fd_bank_slot_get( bank ), NULL );
     558             : 
     559           0 :   fd_vote_states_t const * vote_states_prev;
     560           0 :   if( FD_LIKELY( current_epoch ) ) vote_states_prev = fd_bank_vote_states_prev_query( bank );
     561           0 :   else                             vote_states_prev = fd_bank_vote_states_prev_prev_query( bank );
     562             : 
     563           0 :   ulong * stake_weights_msg = fd_chunk_to_laddr( ctx->stake_out->mem, ctx->stake_out->chunk );
     564           0 :   ulong stake_weights_sz = generate_stake_weight_msg( epoch+fd_ulong_if( current_epoch, 1UL, 0UL), schedule, vote_states_prev, stake_weights_msg );
     565           0 :   ulong stake_weights_sig = 4UL;
     566           0 :   fd_stem_publish( stem, ctx->stake_out->idx, stake_weights_sig, ctx->stake_out->chunk, stake_weights_sz, 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
     567           0 :   ctx->stake_out->chunk = fd_dcache_compact_next( ctx->stake_out->chunk, stake_weights_sz, ctx->stake_out->chunk0, ctx->stake_out->wmark );
     568             : 
     569           0 :   fd_multi_epoch_leaders_stake_msg_init( ctx->mleaders, fd_type_pun_const( stake_weights_msg ) );
     570           0 :   fd_multi_epoch_leaders_stake_msg_fini( ctx->mleaders );
     571           0 : }
     572             : 
     573             : /**********************************************************************/
     574             : /* Transaction execution state machine helpers                        */
     575             : /**********************************************************************/
     576             : 
     577             : static void
     578             : replay_block_start( fd_replay_tile_t *  ctx,
     579             :                     fd_stem_context_t * stem,
     580             :                     ulong               bank_idx,
     581             :                     ulong               parent_bank_idx,
     582           0 :                     ulong               slot ) {
     583           0 :   long before = fd_log_wallclock();
     584             : 
     585           0 :   fd_bank_t bank[1];
     586           0 :   if( FD_UNLIKELY( !fd_banks_bank_query( bank, ctx->banks, bank_idx ) ) ) {
     587           0 :     FD_LOG_CRIT(( "invariant violation: bank is NULL for bank index %lu", bank_idx ));
     588           0 :   }
     589           0 :   if( FD_UNLIKELY( bank->data->flags!=FD_BANK_FLAGS_INIT ) ) {
     590           0 :     FD_LOG_CRIT(( "invariant violation: bank is not in correct state for bank index %lu", bank_idx ));
     591           0 :   }
     592             : 
     593           0 :   bank->data->preparation_begin_nanos = before;
     594             : 
     595           0 :   fd_bank_t parent_bank[1];
     596           0 :   if( FD_UNLIKELY( !fd_banks_bank_query( parent_bank, ctx->banks, parent_bank_idx ) ) ) {
     597           0 :     FD_LOG_CRIT(( "invariant violation: parent bank is NULL for bank index %lu", parent_bank_idx ));
     598           0 :   }
     599           0 :   ulong parent_slot = fd_bank_slot_get( parent_bank );
     600             : 
     601             :   /* Clone the bank from the parent.  We must special case the first
     602             :      slot that is executed as the snapshot does not provide a parent
     603             :      block id. */
     604             : 
     605           0 :   if( FD_UNLIKELY( !fd_banks_clone_from_parent( bank, ctx->banks, bank_idx ) ) ) {
     606           0 :     FD_LOG_CRIT(( "invariant violation: bank is NULL for bank index %lu", bank_idx ));
     607           0 :   }
     608           0 :   fd_bank_slot_set( bank, slot );
     609           0 :   fd_bank_parent_slot_set( bank, parent_slot );
     610           0 :   bank->data->txncache_fork_id = fd_txncache_attach_child( ctx->txncache, parent_bank->data->txncache_fork_id );
     611             : 
     612             :   /* Create a new funk txn for the block. */
     613             : 
     614           0 :   fd_funk_txn_xid_t xid        = { .ul = { slot, bank_idx } };
     615           0 :   fd_funk_txn_xid_t parent_xid = { .ul = { parent_slot, parent_bank_idx } };
     616           0 :   fd_accdb_attach_child( ctx->accdb_admin, &parent_xid, &xid );
     617           0 :   fd_progcache_txn_attach_child( ctx->progcache_admin, &parent_xid, &xid );
     618             : 
     619             :   /* Update any required runtime state and handle any potential epoch
     620             :      boundary change. */
     621             : 
     622           0 :   fd_bank_shred_cnt_set( bank, 0UL );
     623           0 :   fd_bank_execution_fees_set( bank, 0UL );
     624           0 :   fd_bank_priority_fees_set( bank, 0UL );
     625           0 :   fd_bank_tips_set( bank, 0UL );
     626             : 
     627           0 :   fd_bank_has_identity_vote_set( bank, 0 );
     628             : 
     629             :   /* Set the tick height. */
     630           0 :   fd_bank_tick_height_set( bank, fd_bank_max_tick_height_get( bank ) );
     631             : 
     632             :   /* Update block height. */
     633           0 :   fd_bank_block_height_set( bank, fd_bank_block_height_get( bank ) + 1UL );
     634             : 
     635           0 :   ulong * max_tick_height = fd_bank_max_tick_height_modify( bank );
     636           0 :   ulong   ticks_per_slot  = fd_bank_ticks_per_slot_get( bank );
     637           0 :   if( FD_UNLIKELY( FD_RUNTIME_EXECUTE_SUCCESS != fd_runtime_compute_max_tick_height( ticks_per_slot, slot, max_tick_height ) ) ) {
     638           0 :     FD_LOG_CRIT(( "couldn't compute tick height/max tick height slot %lu ticks_per_slot %lu", slot, ticks_per_slot ));
     639           0 :   }
     640             : 
     641           0 :   int is_epoch_boundary = 0;
     642           0 :   fd_runtime_block_execute_prepare( ctx->banks, bank, ctx->accdb, &ctx->runtime_stack, ctx->capture_ctx, &is_epoch_boundary );
     643           0 :   if( FD_UNLIKELY( is_epoch_boundary ) ) publish_stake_weights( ctx, stem, bank, 1 );
     644             : 
     645           0 : }
     646             : 
     647             : static void
     648           0 : cost_tracker_snap( fd_bank_t * bank, fd_replay_slot_completed_t * slot_info ) {
     649           0 :   if( bank->data->cost_tracker_pool_idx!=fd_bank_cost_tracker_pool_idx_null( fd_bank_get_cost_tracker_pool( bank->data ) ) ) {
     650           0 :     fd_cost_tracker_t const * cost_tracker = fd_bank_cost_tracker_locking_query( bank );
     651           0 :     slot_info->cost_tracker.block_cost                   = cost_tracker->block_cost;
     652           0 :     slot_info->cost_tracker.vote_cost                    = cost_tracker->vote_cost;
     653           0 :     slot_info->cost_tracker.allocated_accounts_data_size = cost_tracker->allocated_accounts_data_size;
     654           0 :     slot_info->cost_tracker.block_cost_limit             = cost_tracker->block_cost_limit;
     655           0 :     slot_info->cost_tracker.vote_cost_limit              = cost_tracker->vote_cost_limit;
     656           0 :     slot_info->cost_tracker.account_cost_limit           = cost_tracker->account_cost_limit;
     657           0 :     fd_bank_cost_tracker_end_locking_query( bank );
     658           0 :   } else {
     659           0 :     memset( &slot_info->cost_tracker, 0, sizeof(slot_info->cost_tracker) );
     660           0 :   }
     661           0 : }
     662             : 
     663             : static ulong
     664           0 : get_identity_balance( fd_replay_tile_t * ctx, fd_funk_txn_xid_t xid ) {
     665           0 :   ulong identity_balance = ULONG_MAX;
     666           0 :   fd_accdb_ro_t identity_acc[1];
     667           0 :   if( FD_LIKELY( fd_accdb_open_ro( ctx->accdb, identity_acc, &xid, ctx->identity_pubkey ) ) ) {
     668           0 :     identity_balance = identity_acc->meta->lamports;
     669           0 :     fd_accdb_close_ro( ctx->accdb, identity_acc );
     670           0 :   }
     671           0 :   return identity_balance;
     672           0 : }
     673             : 
     674             : static void
     675             : publish_slot_completed( fd_replay_tile_t *  ctx,
     676             :                         fd_stem_context_t * stem,
     677             :                         fd_bank_t *         bank,
     678             :                         int                 is_initial,
     679           0 :                         int                 is_leader ) {
     680             : 
     681           0 :   ulong slot = fd_bank_slot_get( bank );
     682             : 
     683           0 :   fd_block_id_ele_t * block_id_ele = &ctx->block_id_arr[ bank->data->idx ];
     684             : 
     685             :   /* HACKY: hacky way of checking if we should send a null parent block
     686             :      id */
     687           0 :   fd_hash_t parent_block_id = {0};
     688           0 :   if( FD_UNLIKELY( !is_initial ) ) {
     689           0 :     parent_block_id = ctx->block_id_arr[ bank->data->parent_idx ].block_id;
     690           0 :   }
     691             : 
     692           0 :   fd_hash_t const * bank_hash  = fd_bank_bank_hash_query( bank );
     693           0 :   fd_hash_t const * block_hash = fd_blockhashes_peek_last_hash( fd_bank_block_hash_queue_query( bank ) );
     694           0 :   FD_TEST( bank_hash  );
     695           0 :   FD_TEST( block_hash );
     696             : 
     697           0 :   if( FD_LIKELY( !is_initial ) ) fd_txncache_finalize_fork( ctx->txncache, bank->data->txncache_fork_id, 0UL, block_hash->uc );
     698             : 
     699           0 :   fd_epoch_schedule_t const * epoch_schedule = fd_bank_epoch_schedule_query( bank );
     700           0 :   ulong slot_idx;
     701           0 :   ulong epoch = fd_slot_to_epoch( epoch_schedule, slot, &slot_idx );
     702             : 
     703           0 :   ctx->metrics.slots_total++;
     704           0 :   ctx->metrics.transactions_total = fd_bank_txn_count_get( bank );
     705             : 
     706           0 :   fd_replay_slot_completed_t * slot_info = fd_chunk_to_laddr( ctx->replay_out->mem, ctx->replay_out->chunk );
     707           0 :   slot_info->slot                  = slot;
     708           0 :   slot_info->root_slot             = ctx->consensus_root_slot;
     709           0 :   slot_info->storage_slot          = ctx->published_root_slot;
     710           0 :   slot_info->epoch                 = epoch;
     711           0 :   slot_info->slot_in_epoch         = slot_idx;
     712           0 :   slot_info->block_height          = fd_bank_block_height_get( bank );
     713           0 :   slot_info->parent_slot           = fd_bank_parent_slot_get( bank );
     714           0 :   slot_info->block_id              = block_id_ele->block_id;
     715           0 :   slot_info->parent_block_id       = parent_block_id;
     716           0 :   slot_info->bank_hash             = *bank_hash;
     717           0 :   slot_info->block_hash            = *block_hash;
     718           0 :   slot_info->transaction_count     = fd_bank_txn_count_get( bank );
     719             : 
     720           0 :   fd_inflation_t inflation = fd_bank_inflation_get( bank );
     721           0 :   slot_info->inflation.foundation      = inflation.foundation;
     722           0 :   slot_info->inflation.foundation_term = inflation.foundation_term;
     723           0 :   slot_info->inflation.terminal        = inflation.terminal;
     724           0 :   slot_info->inflation.initial         = inflation.initial;
     725           0 :   slot_info->inflation.taper           = inflation.taper;
     726             : 
     727           0 :   fd_rent_t rent = fd_bank_rent_get( bank );
     728           0 :   slot_info->rent.burn_percent            = rent.burn_percent;
     729           0 :   slot_info->rent.lamports_per_uint8_year = rent.lamports_per_uint8_year;
     730           0 :   slot_info->rent.exemption_threshold     = rent.exemption_threshold;
     731             : 
     732           0 :   slot_info->first_fec_set_received_nanos      = bank->data->first_fec_set_received_nanos;
     733           0 :   slot_info->preparation_begin_nanos           = bank->data->preparation_begin_nanos;
     734           0 :   slot_info->first_transaction_scheduled_nanos = bank->data->first_transaction_scheduled_nanos;
     735           0 :   slot_info->last_transaction_finished_nanos   = bank->data->last_transaction_finished_nanos;
     736           0 :   slot_info->completion_time_nanos             = fd_log_wallclock();
     737             : 
     738             :   /* refcnt should be incremented by 1 for each consumer that uses
     739             :      `bank_idx`.  Each consumer should decrement the bank's refcnt once
     740             :      they are done using the bank. */
     741           0 :   bank->data->refcnt++; /* tower_tile */
     742           0 :   if( FD_LIKELY( ctx->gui_enabled ) ) bank->data->refcnt++; /* gui tile */
     743           0 :   slot_info->bank_idx = bank->data->idx;
     744           0 :   FD_LOG_DEBUG(( "bank (idx=%lu, slot=%lu) refcnt incremented to %lu", bank->data->idx, slot, bank->data->refcnt ));
     745             : 
     746           0 :   slot_info->parent_bank_idx = ULONG_MAX;
     747           0 :   fd_bank_t parent_bank[1];
     748           0 :   if( FD_LIKELY( fd_banks_get_parent( parent_bank, ctx->banks, bank ) && ctx->gui_enabled ) ) {
     749           0 :     parent_bank->data->refcnt++;
     750           0 :     FD_LOG_DEBUG(( "bank (idx=%lu, slot=%lu) refcnt incremented to %lu", parent_bank->data->idx, slot, parent_bank->data->refcnt ));
     751           0 :     slot_info->parent_bank_idx = parent_bank->data->idx;
     752           0 :   }
     753             : 
     754           0 :   slot_info->is_leader = is_leader;
     755             : 
     756           0 :   FD_BASE58_ENCODE_32_BYTES( ctx->block_id_arr[ bank->data->idx ].block_id.uc, block_id_cstr );
     757           0 :   FD_BASE58_ENCODE_32_BYTES( fd_bank_bank_hash_query( bank )->uc, bank_hash_cstr );
     758           0 :   FD_LOG_DEBUG(( "publish_slot_completed: bank_idx=%lu slot=%lu bank_hash=%s block_id=%s", bank->data->idx, slot, bank_hash_cstr, block_id_cstr ));
     759             : 
     760           0 :   fd_stem_publish( stem, ctx->replay_out->idx, REPLAY_SIG_SLOT_COMPLETED, ctx->replay_out->chunk, sizeof(fd_replay_slot_completed_t), 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
     761           0 :   ctx->replay_out->chunk = fd_dcache_compact_next( ctx->replay_out->chunk, sizeof(fd_replay_slot_completed_t), ctx->replay_out->chunk0, ctx->replay_out->wmark );
     762           0 : }
     763             : 
     764             : static void
     765             : publish_slot_dead( fd_replay_tile_t *  ctx,
     766             :                    fd_stem_context_t * stem,
     767           0 :                    fd_bank_t *         bank ) {
     768           0 :   FD_TEST( ctx->block_id_arr[ bank->data->idx ].block_id_seen );
     769           0 :   fd_replay_slot_dead_t * slot_dead = fd_chunk_to_laddr( ctx->replay_out->mem, ctx->replay_out->chunk );
     770           0 :   slot_dead->slot                   = fd_bank_slot_get( bank );
     771           0 :   slot_dead->block_id               = ctx->block_id_arr[ bank->data->idx ].block_id;
     772           0 :   fd_stem_publish( stem, ctx->replay_out->idx, REPLAY_SIG_SLOT_DEAD, ctx->replay_out->chunk, sizeof(fd_replay_slot_dead_t), 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
     773           0 :   ctx->replay_out->chunk = fd_dcache_compact_next( ctx->replay_out->chunk, sizeof(fd_replay_slot_dead_t), ctx->replay_out->chunk0, ctx->replay_out->wmark );
     774           0 : }
     775             : 
     776             : static void
     777             : replay_block_finalize( fd_replay_tile_t *  ctx,
     778             :                        fd_stem_context_t * stem,
     779           0 :                        fd_bank_t *         bank ) {
     780           0 :   bank->data->last_transaction_finished_nanos = fd_log_wallclock();
     781             : 
     782           0 :   FD_TEST( !(bank->data->flags&FD_BANK_FLAGS_FROZEN) );
     783             : 
     784             :   /* Set poh hash in bank. */
     785           0 :   fd_hash_t * poh = fd_sched_get_poh( ctx->sched, bank->data->idx );
     786           0 :   fd_bank_poh_set( bank, *poh );
     787             : 
     788             :   /* Set shred count in bank. */
     789           0 :   fd_bank_shred_cnt_set( bank, fd_sched_get_shred_cnt( ctx->sched, bank->data->idx ) );
     790             : 
     791             :   /* Do hashing and other end-of-block processing. */
     792           0 :   fd_runtime_block_execute_finalize( bank, ctx->accdb, ctx->capture_ctx );
     793             : 
     794             :   /* Copy out cost tracker fields before freezing */
     795           0 :   fd_replay_slot_completed_t * slot_info = fd_chunk_to_laddr( ctx->replay_out->mem, ctx->replay_out->chunk );
     796           0 :   cost_tracker_snap( bank, slot_info );
     797             : 
     798             :   /* fetch identity / vote balance updates infrequently */
     799           0 :   ulong slot = fd_bank_slot_get( bank );
     800           0 :   fd_funk_txn_xid_t xid = { .ul = { slot, bank->data->idx } };
     801           0 :   slot_info->identity_balance = FD_UNLIKELY( slot%4096==0UL ) ? get_identity_balance( ctx, xid ) : ULONG_MAX;
     802             : 
     803             :   /* Mark the bank as frozen. */
     804           0 :   fd_banks_mark_bank_frozen( ctx->banks, bank );
     805             : 
     806             :   /**********************************************************************/
     807             :   /* Bank hash comparison, and halt if there's a mismatch after replay  */
     808             :   /**********************************************************************/
     809             : 
     810           0 :   fd_hash_t const * bank_hash = fd_bank_bank_hash_query( bank );
     811           0 :   FD_TEST( bank_hash );
     812             : 
     813             :   /* Must be last so we can measure completion time correctly, even
     814             :      though we could technically do this before the hash cmp and vote
     815             :      tower stuff. */
     816           0 :   publish_slot_completed( ctx, stem, bank, 0, 0 /* is_leader */ );
     817             : 
     818           0 : # if FD_HAS_FLATCC
     819             :   /* If enabled, dump the block to a file and reset the dumping
     820             :      context state */
     821           0 :   if( FD_UNLIKELY( ctx->capture_ctx && ctx->capture_ctx->dump_block_to_pb ) ) {
     822           0 :     fd_dump_block_to_protobuf( ctx->block_dump_ctx, ctx->banks, bank, ctx->accdb, ctx->capture_ctx );
     823           0 :     fd_block_dump_context_reset( ctx->block_dump_ctx );
     824           0 :   }
     825           0 : # endif
     826           0 : }
     827             : 
     828             : /**********************************************************************/
     829             : /* Leader bank management                                             */
     830             : /**********************************************************************/
     831             : 
     832             : static fd_bank_t *
     833             : prepare_leader_bank( fd_replay_tile_t *  ctx,
     834             :                      ulong               slot,
     835             :                      long                now,
     836             :                      fd_hash_t const *   parent_block_id,
     837           0 :                      fd_stem_context_t * stem ) {
     838           0 :   long before = fd_log_wallclock();
     839             : 
     840             :   /* Make sure that we are not already leader. */
     841           0 :   FD_TEST( ctx->leader_bank->data==NULL );
     842             : 
     843           0 :   fd_block_id_ele_t * parent_ele = fd_block_id_map_ele_query( ctx->block_id_map, parent_block_id, NULL, ctx->block_id_arr );
     844           0 :   if( FD_UNLIKELY( !parent_ele ) ) {
     845           0 :     FD_BASE58_ENCODE_32_BYTES( parent_block_id->key, parent_block_id_b58 );
     846           0 :     FD_LOG_CRIT(( "invariant violation: parent bank index not found for merkle root %s", parent_block_id_b58 ));
     847           0 :   }
     848           0 :   ulong parent_bank_idx = fd_block_id_ele_get_idx( ctx->block_id_arr, parent_ele );
     849             : 
     850           0 :   fd_bank_t parent_bank[1];
     851           0 :   if( FD_UNLIKELY( !fd_banks_bank_query( parent_bank, ctx->banks, parent_bank_idx ) ) ) {
     852           0 :     FD_LOG_CRIT(( "invariant violation: parent bank not found for bank index %lu", parent_bank_idx ));
     853           0 :   }
     854           0 :   ulong parent_slot = fd_bank_slot_get( parent_bank );
     855             : 
     856           0 :   if( FD_UNLIKELY( !fd_banks_new_bank( ctx->leader_bank, ctx->banks, parent_bank_idx, now ) ) ) {
     857           0 :     FD_LOG_CRIT(( "invariant violation: leader bank is NULL for slot %lu", slot ));
     858           0 :   }
     859             : 
     860           0 :   if( FD_UNLIKELY( !fd_banks_clone_from_parent( ctx->leader_bank, ctx->banks, ctx->leader_bank->data->idx ) ) ) {
     861           0 :     FD_LOG_CRIT(( "invariant violation: bank is NULL for slot %lu", slot ));
     862           0 :   }
     863             : 
     864             :   /* At this point we want to remove any stale block id map entry that
     865             :      corresponds to this bank. */
     866           0 :   fd_block_id_ele_t * block_id_ele = &ctx->block_id_arr[ ctx->leader_bank->data->idx ];
     867           0 :   if( FD_LIKELY( fd_block_id_map_ele_query( ctx->block_id_map, &block_id_ele->block_id, NULL, ctx->block_id_arr )==block_id_ele ) ) {
     868           0 :     FD_TEST( fd_block_id_map_ele_remove( ctx->block_id_map, &block_id_ele->block_id, NULL, ctx->block_id_arr ) );
     869           0 :   }
     870           0 :   block_id_ele->block_id_seen = 0;
     871           0 :   block_id_ele->slot          = slot;
     872             : 
     873           0 :   ctx->leader_bank->data->preparation_begin_nanos = before;
     874             : 
     875           0 :   fd_bank_slot_set( ctx->leader_bank, slot );
     876           0 :   fd_bank_parent_slot_set( ctx->leader_bank, parent_slot );
     877           0 :   ctx->leader_bank->data->txncache_fork_id = fd_txncache_attach_child( ctx->txncache, parent_bank->data->txncache_fork_id );
     878             :   /* prepare the funk transaction for the leader bank */
     879           0 :   fd_funk_txn_xid_t xid        = { .ul = { slot, ctx->leader_bank->data->idx } };
     880           0 :   fd_funk_txn_xid_t parent_xid = { .ul = { parent_slot, parent_bank_idx } };
     881           0 :   fd_accdb_attach_child( ctx->accdb_admin, &parent_xid, &xid );
     882           0 :   fd_progcache_txn_attach_child( ctx->progcache_admin, &parent_xid, &xid );
     883             : 
     884           0 :   fd_bank_execution_fees_set( ctx->leader_bank, 0UL );
     885           0 :   fd_bank_priority_fees_set( ctx->leader_bank, 0UL );
     886           0 :   fd_bank_shred_cnt_set( ctx->leader_bank, 0UL );
     887           0 :   fd_bank_tips_set( ctx->leader_bank, 0UL );
     888             : 
     889             :   /* Set the tick height. */
     890           0 :   fd_bank_tick_height_set( ctx->leader_bank, fd_bank_max_tick_height_get( ctx->leader_bank ) );
     891             : 
     892             :   /* Update block height. */
     893           0 :   fd_bank_block_height_set( ctx->leader_bank, fd_bank_block_height_get( ctx->leader_bank ) + 1UL );
     894             : 
     895           0 :   ulong * max_tick_height = fd_bank_max_tick_height_modify( ctx->leader_bank );
     896           0 :   ulong   ticks_per_slot  = fd_bank_ticks_per_slot_get( ctx->leader_bank );
     897           0 :   if( FD_UNLIKELY( FD_RUNTIME_EXECUTE_SUCCESS != fd_runtime_compute_max_tick_height( ticks_per_slot, slot, max_tick_height ) ) ) {
     898           0 :     FD_LOG_CRIT(( "couldn't compute tick height/max tick height slot %lu ticks_per_slot %lu", slot, ticks_per_slot ));
     899           0 :   }
     900             : 
     901           0 :   int is_epoch_boundary = 0;
     902           0 :   fd_runtime_block_execute_prepare( ctx->banks, ctx->leader_bank, ctx->accdb, &ctx->runtime_stack, ctx->capture_ctx, &is_epoch_boundary );
     903           0 :   if( FD_UNLIKELY( is_epoch_boundary ) ) publish_stake_weights( ctx, stem, ctx->leader_bank, 1 );
     904             : 
     905             :   /* Now that a bank has been created for the leader slot, increment the
     906             :      reference count until we are done with the leader slot. */
     907           0 :   ctx->leader_bank->data->refcnt++;
     908             : 
     909           0 :   return ctx->leader_bank;
     910           0 : }
     911             : 
     912             : static void
     913             : fini_leader_bank( fd_replay_tile_t *  ctx,
     914           0 :                   fd_stem_context_t * stem ) {
     915             : 
     916           0 :   FD_TEST( ctx->leader_bank->data!=NULL );
     917           0 :   FD_TEST( ctx->is_leader );
     918           0 :   FD_TEST( ctx->block_id_arr[ ctx->leader_bank->data->idx ].block_id_seen );
     919           0 :   FD_TEST( ctx->recv_poh );
     920             : 
     921           0 :   ctx->leader_bank->data->last_transaction_finished_nanos = fd_log_wallclock();
     922             : 
     923           0 :   ulong curr_slot = fd_bank_slot_get( ctx->leader_bank );
     924             : 
     925           0 :   fd_sched_block_add_done( ctx->sched, ctx->leader_bank->data->idx, ctx->leader_bank->data->parent_idx, curr_slot );
     926             : 
     927           0 :   fd_runtime_block_execute_finalize( ctx->leader_bank, ctx->accdb, ctx->capture_ctx );
     928             : 
     929           0 :   fd_replay_slot_completed_t * slot_info = fd_chunk_to_laddr( ctx->replay_out->mem, ctx->replay_out->chunk );
     930           0 :   cost_tracker_snap( ctx->leader_bank, slot_info );
     931           0 :   fd_funk_txn_xid_t xid = { .ul = { curr_slot, ctx->leader_bank->data->idx } };
     932           0 :   slot_info->identity_balance = FD_UNLIKELY( curr_slot%4096==0UL ) ? get_identity_balance( ctx, xid ) : ULONG_MAX;
     933             : 
     934           0 :   fd_banks_mark_bank_frozen( ctx->banks, ctx->leader_bank );
     935             : 
     936           0 :   fd_hash_t const * bank_hash  = fd_bank_bank_hash_query( ctx->leader_bank );
     937           0 :   FD_TEST( bank_hash );
     938             : 
     939           0 :   publish_slot_completed( ctx, stem, ctx->leader_bank, 0, 1 /* is_leader */ );
     940             : 
     941             :   /* The reference on the bank is finally no longer needed. */
     942           0 :   ctx->leader_bank->data->refcnt--;
     943             : 
     944             :   /* We are no longer leader so we can clear the bank index we use for
     945             :      being the leader. */
     946           0 :   ctx->leader_bank->data = NULL;
     947           0 :   ctx->recv_poh          = 0;
     948           0 :   ctx->is_leader         = 0;
     949           0 : }
     950             : 
     951             : static void
     952             : publish_root_advanced( fd_replay_tile_t *  ctx,
     953           0 :                        fd_stem_context_t * stem ) {
     954             : 
     955             :   /* FIXME: for now we want to send the child of the consensus root to
     956             :      avoid data races with funk root advancing.  This is a temporary
     957             :      hack because currently it is not safe to query against the xid for
     958             :      the root that is being advanced in funk.  This doesn't eliminate
     959             :      the data race that exists in funk, but reduces how often it occurs.
     960             : 
     961             :      Case that causes a data race:
     962             :      replay: we are advancing the root from slot A->B
     963             :      resolv: we are resolving ALUTs against slot B */
     964             : 
     965           0 :   fd_bank_t consensus_root_bank[1];
     966           0 :   if( FD_UNLIKELY( !fd_banks_bank_query( consensus_root_bank, ctx->banks, ctx->consensus_root_bank_idx ) ) ) {
     967           0 :     FD_LOG_CRIT(( "invariant violation: consensus root bank is NULL at bank index %lu", ctx->consensus_root_bank_idx ));
     968           0 :   }
     969             : 
     970           0 :   if( FD_UNLIKELY( consensus_root_bank->data->child_idx==ULONG_MAX ) ) {
     971           0 :     return;
     972           0 :   }
     973             : 
     974           0 :   fd_bank_t bank[1];
     975           0 :   if( FD_UNLIKELY( !fd_banks_bank_query( bank, ctx->banks, consensus_root_bank->data->child_idx ) ) ) {
     976           0 :     FD_LOG_CRIT(( "invariant violation: consensus root bank child is NULL at bank index %lu", consensus_root_bank->data->child_idx ));
     977           0 :   }
     978             : 
     979             :   /* Increment the reference count on the consensus root bank to account
     980             :      for the number of exec tiles that are waiting on it. */
     981           0 :   bank->data->refcnt += ctx->resolv_tile_cnt;
     982             : 
     983           0 :   fd_replay_root_advanced_t * msg = fd_chunk_to_laddr( ctx->replay_out->mem, ctx->replay_out->chunk );
     984           0 :   msg->bank_idx = bank->data->idx;
     985             : 
     986           0 :   fd_stem_publish( stem, ctx->replay_out->idx, REPLAY_SIG_ROOT_ADVANCED, ctx->replay_out->chunk, sizeof(fd_replay_root_advanced_t), 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
     987           0 :   ctx->replay_out->chunk = fd_dcache_compact_next( ctx->replay_out->chunk, sizeof(fd_replay_root_advanced_t), ctx->replay_out->chunk0, ctx->replay_out->wmark );
     988           0 : }
     989             : 
     990             : /* init_funk performs pre-flight checks for the account database and
     991             :    program cache.  Ensures that the account database was set up
     992             :    correctly by bootstrap components (e.g. genesis or snapshot loader).
     993             :    Mirrors the account database's fork tree down to the program cache. */
     994             : 
     995             : static void
     996             : init_funk( fd_replay_tile_t * ctx,
     997           0 :            ulong              bank_slot ) {
     998             :   /* Ensure that the loaded bank root corresponds to the account
     999             :      database's root. */
    1000           0 :   fd_funk_t * funk = fd_accdb_user_v1_funk( ctx->accdb );
    1001           0 :   if( FD_UNLIKELY( !funk->shmem ) ) {
    1002           0 :     FD_LOG_CRIT(( "failed to initialize account database: replay tile is not joined to database shared memory objects" ));
    1003           0 :   }
    1004           0 :   fd_funk_txn_xid_t const * accdb_pub = fd_funk_last_publish( funk );
    1005           0 :   if( FD_UNLIKELY( accdb_pub->ul[0]!=bank_slot ) ) {
    1006           0 :     FD_LOG_CRIT(( "failed to initialize account database: accdb is at slot %lu, but chain state is at slot %lu\n"
    1007           0 :                   "This is a bug in startup components.",
    1008           0 :                   accdb_pub->ul[0], bank_slot ));
    1009           0 :   }
    1010           0 :   if( FD_UNLIKELY( fd_funk_last_publish_is_frozen( funk ) ) ) {
    1011           0 :     FD_LOG_CRIT(( "failed to initialize account database: accdb fork graph is not clean.\n"
    1012           0 :                   "The account database should only contain state for the root slot at this point,\n"
    1013           0 :                   "but there are incomplete database transactions leftover.\n"
    1014           0 :                   "This is a bug in startup components."  ));
    1015           0 :   }
    1016             : 
    1017             :   /* The program cache tracks the account database's fork graph at all
    1018             :      times.  Perform initial synchronization: pivot from funk 'root' (a
    1019             :      sentinel XID) to 'last publish' (the bootstrap root slot). */
    1020           0 :   if( FD_UNLIKELY( !ctx->progcache_admin->funk->shmem ) ) {
    1021           0 :     FD_LOG_CRIT(( "failed to initialize account database: replay tile is not joined to program cache" ));
    1022           0 :   }
    1023           0 :   fd_progcache_clear( ctx->progcache_admin );
    1024             : 
    1025           0 :   fd_funk_txn_xid_t last_publish = fd_accdb_root_get( ctx->accdb_admin );
    1026           0 :   fd_progcache_txn_attach_child( ctx->progcache_admin, fd_funk_root( ctx->progcache_admin->funk ), &last_publish );
    1027           0 :   fd_progcache_txn_advance_root( ctx->progcache_admin,                                             &last_publish );
    1028           0 : }
    1029             : 
    1030             : static void
    1031           0 : init_after_snapshot( fd_replay_tile_t * ctx ) {
    1032             :   /* Now that the snapshot has been loaded in, we have to refresh the
    1033             :      stake delegations since the manifest does not contain the full set
    1034             :      of data required for the stake delegations. See
    1035             :      fd_stake_delegations.h for why this is required. */
    1036             : 
    1037           0 :   fd_bank_t bank[1];
    1038           0 :   if( FD_UNLIKELY( !fd_banks_bank_query( bank, ctx->banks, FD_REPLAY_BOOT_BANK_IDX ) ) ) {
    1039           0 :     FD_LOG_CRIT(( "invariant violation: replay bank is NULL at bank index %lu", FD_REPLAY_BOOT_BANK_IDX ));
    1040           0 :   }
    1041             : 
    1042           0 :   fd_funk_txn_xid_t xid = { .ul = { fd_bank_slot_get( bank ), bank->data->idx } };
    1043           0 :   init_funk( ctx, fd_bank_slot_get( bank ) );
    1044             : 
    1045           0 :   fd_stake_delegations_t * root_delegations = fd_banks_stake_delegations_root_query( ctx->banks );
    1046             : 
    1047           0 :   fd_stake_delegations_refresh( root_delegations, ctx->accdb, &xid );
    1048             : 
    1049             :   /* We want to clear out any stale vote states that may have been
    1050             :     included in the snapshot manifest.  If an agave snapshot is created
    1051             :     shortly after a vote state is removed from the stakes cache (Agave
    1052             :     equivalent of vote states), then the vote state will be included in
    1053             :     the snapshot manifest. */
    1054             : 
    1055           0 :     fd_vote_states_t * vote_states = fd_bank_vote_states_locking_modify( bank );
    1056           0 :     fd_vote_states_iter_t iter_[1];
    1057             : 
    1058           0 :     ulong stale_vote_acc_cnt = 0UL;
    1059           0 :     for( fd_vote_states_iter_t * iter = fd_vote_states_iter_init( iter_, vote_states );
    1060           0 :         !fd_vote_states_iter_done( iter );
    1061           0 :         fd_vote_states_iter_next( iter ) ) {
    1062           0 :       fd_vote_state_ele_t * vote_state = fd_vote_states_iter_ele( iter );
    1063           0 :       fd_accdb_ro_t ro[1];
    1064           0 :       if( FD_UNLIKELY( !fd_accdb_open_ro( ctx->accdb, ro, &xid, &vote_state->vote_account ) ) ) {
    1065           0 :         ctx->runtime_stack.vote_accounts.stale_accs[ stale_vote_acc_cnt++ ] = vote_state->vote_account;
    1066           0 :         FD_BASE58_ENCODE_32_BYTES( vote_state->vote_account.uc, acc_cstr );
    1067           0 :         FD_LOG_DEBUG(( "vote account %s from manifest is stale", acc_cstr ));
    1068           0 :       } else {
    1069           0 :         fd_accdb_close_ro( ctx->accdb, ro );
    1070           0 :       }
    1071           0 :     }
    1072             : 
    1073           0 :     for( ulong i=0UL; i<stale_vote_acc_cnt; i++ ) {
    1074           0 :       fd_vote_states_remove( vote_states, &ctx->runtime_stack.vote_accounts.stale_accs[ i ] );
    1075           0 :     }
    1076           0 :     fd_bank_vote_states_end_locking_modify( bank );
    1077             : 
    1078             :   /* After both snapshots have been loaded in, we can determine if we should
    1079             :      start distributing rewards. */
    1080             : 
    1081           0 :   fd_rewards_recalculate_partitioned_rewards( ctx->banks, bank, ctx->accdb, &xid, &ctx->runtime_stack, ctx->capture_ctx );
    1082             : 
    1083           0 :   ulong snapshot_slot = fd_bank_slot_get( bank );
    1084           0 :   if( FD_UNLIKELY( !snapshot_slot ) ) {
    1085             :     /* Genesis-specific setup. */
    1086             :     /* FIXME: This branch does not set up a new block exec ctx
    1087             :        properly. Needs to do whatever prepare_new_block_execution
    1088             :        does, but just hacking that in breaks stuff. */
    1089           0 :     fd_runtime_update_leaders( bank, &ctx->runtime_stack );
    1090             : 
    1091           0 :     ulong hashcnt_per_slot = fd_bank_hashes_per_tick_get( bank ) * fd_bank_ticks_per_slot_get( bank );
    1092           0 :     fd_hash_t * poh = fd_bank_poh_modify( bank );
    1093           0 :     while( hashcnt_per_slot-- ) {
    1094           0 :       fd_sha256_hash( poh->hash, 32UL, poh->hash );
    1095           0 :     }
    1096             : 
    1097           0 :     int is_epoch_boundary = 0;
    1098           0 :     fd_runtime_block_execute_prepare( ctx->banks, bank, ctx->accdb, &ctx->runtime_stack, ctx->capture_ctx, &is_epoch_boundary );
    1099           0 :     FD_TEST( !is_epoch_boundary );
    1100           0 :     fd_runtime_block_execute_finalize( bank, ctx->accdb, ctx->capture_ctx );
    1101             : 
    1102           0 :     snapshot_slot = 0UL;
    1103           0 :   }
    1104             : 
    1105           0 : }
    1106             : 
    1107             : static inline int
    1108             : maybe_become_leader( fd_replay_tile_t *  ctx,
    1109           0 :                      fd_stem_context_t * stem ) {
    1110           0 :   FD_TEST( ctx->is_booted );
    1111           0 :   if( FD_LIKELY( ctx->next_leader_slot==ULONG_MAX || ctx->is_leader || !ctx->has_identity_vote_rooted || ctx->replay_out->idx==ULONG_MAX ) ) return 0;
    1112             : 
    1113           0 :   FD_TEST( ctx->next_leader_slot>ctx->reset_slot );
    1114           0 :   long now = fd_tickcount();
    1115           0 :   if( FD_LIKELY( now<ctx->next_leader_tickcount ) ) return 0;
    1116             : 
    1117             :   /* TODO:
    1118             :   if( FD_UNLIKELY( ctx->halted_switching_key ) ) return 0; */
    1119             : 
    1120             :   /* If a prior leader is still in the process of publishing their slot,
    1121             :      delay ours to let them finish ... unless they are so delayed that
    1122             :      we risk getting skipped by the leader following us.  1.2 seconds
    1123             :      is a reasonable default here, although any value between 0 and 1.6
    1124             :      seconds could be considered reasonable.  This is arbitrary and
    1125             :      chosen due to intuition. */
    1126           0 :   if( FD_UNLIKELY( now<ctx->next_leader_tickcount+(long)(3.0*ctx->slot_duration_ticks) ) ) {
    1127           0 :     FD_TEST( ctx->reset_bank->data );
    1128             : 
    1129             :     /* TODO: Make the max_active_descendant calculation more efficient
    1130             :        by caching it in the bank structure and updating it as banks are
    1131             :        created and completed. */
    1132           0 :     ulong max_active_descendant = 0UL;
    1133           0 :     ulong child_idx = ctx->reset_bank->data->child_idx;
    1134           0 :     while( child_idx!=ULONG_MAX ) {
    1135           0 :       fd_bank_t child_bank[1];
    1136           0 :       fd_banks_bank_query( child_bank, ctx->banks, child_idx );
    1137           0 :       max_active_descendant = fd_ulong_max( max_active_descendant, fd_bank_slot_get( child_bank ) );
    1138           0 :       child_idx = child_bank->data->sibling_idx;
    1139           0 :     }
    1140             : 
    1141             :     /* If the max_active_descendant is >= next_leader_slot, we waited
    1142             :        too long and a leader after us started publishing to try and skip
    1143             :        us.  Just start our leader slot immediately, we might win ... */
    1144           0 :     if( FD_LIKELY( max_active_descendant>=ctx->reset_slot && max_active_descendant<ctx->next_leader_slot ) ) {
    1145             :       /* If one of the leaders between the reset slot and our leader
    1146             :          slot is in the process of publishing (they have a descendant
    1147             :          bank that is in progress of being replayed), then keep waiting.
    1148             :          We probably wouldn't get a leader slot out before they
    1149             :          finished.
    1150             : 
    1151             :          Unless... we are past the deadline to start our slot by more
    1152             :          than 1.2 seconds, in which case we should probably start it to
    1153             :          avoid getting skipped by the leader behind us. */
    1154           0 :       return 0;
    1155           0 :     }
    1156           0 :   }
    1157             : 
    1158           0 :   long now_nanos = fd_log_wallclock();
    1159             : 
    1160           0 :   ctx->is_leader = 1;
    1161           0 :   ctx->recv_poh  = 0;
    1162             : 
    1163           0 :   FD_TEST( ctx->highwater_leader_slot==ULONG_MAX || ctx->highwater_leader_slot<ctx->next_leader_slot );
    1164           0 :   ctx->highwater_leader_slot = ctx->next_leader_slot;
    1165             : 
    1166           0 :   FD_LOG_INFO(( "becoming leader for slot %lu, parent slot is %lu", ctx->next_leader_slot, ctx->reset_slot ));
    1167             : 
    1168             :   /* Acquires bank, sets up initial state, and refcnts it. */
    1169           0 :   fd_bank_t *       bank = prepare_leader_bank( ctx, ctx->next_leader_slot, now_nanos, &ctx->reset_block_id, stem );
    1170           0 :   fd_funk_txn_xid_t xid  = { .ul = { ctx->next_leader_slot, ctx->leader_bank->data->idx } };
    1171             : 
    1172           0 :   fd_bundle_crank_tip_payment_config_t config[1] = { 0 };
    1173           0 :   fd_pubkey_t tip_receiver_owner = {0};
    1174             : 
    1175           0 :   if( FD_UNLIKELY( ctx->bundle.enabled ) ) {
    1176           0 :     fd_acct_addr_t tip_payment_config[1];
    1177           0 :     fd_acct_addr_t tip_receiver[1];
    1178           0 :     fd_bundle_crank_get_addresses( ctx->bundle.gen, fd_bank_epoch_get( bank ), tip_payment_config, tip_receiver );
    1179             : 
    1180           0 :     fd_accdb_ro_t tip_config_acc[1];
    1181           0 :     if( FD_UNLIKELY( !fd_accdb_open_ro( ctx->accdb, tip_config_acc, &xid, tip_payment_config ) ) ) {
    1182             :       /* FIXME This should not crash the validator */
    1183           0 :       FD_BASE58_ENCODE_32_BYTES( tip_payment_config->b, tip_config_acc_b58 );
    1184           0 :       FD_LOG_CRIT(( "tip payment config account %s does not exist", tip_config_acc_b58 ));
    1185           0 :     }
    1186           0 :     ulong tip_cfg_sz = fd_accdb_ref_data_sz( tip_config_acc );
    1187           0 :     if( FD_UNLIKELY( tip_cfg_sz < sizeof(fd_bundle_crank_tip_payment_config_t) ) ) {
    1188             :       /* FIXME This should not crash the validator */
    1189           0 :       FD_LOG_HEXDUMP_CRIT(( "invalid tip payment config account data", fd_accdb_ref_data_const( tip_config_acc ), tip_cfg_sz ));
    1190           0 :     }
    1191           0 :     memcpy( config, fd_accdb_ref_data_const( tip_config_acc ), sizeof(fd_bundle_crank_tip_payment_config_t) );
    1192           0 :     fd_accdb_close_ro( ctx->accdb, tip_config_acc );
    1193             : 
    1194             :     /* It is possible that the tip receiver account does not exist yet
    1195             :        if it is the first time in an epoch. */
    1196           0 :     fd_accdb_ro_t tip_receiver_acc[1];
    1197           0 :     if( FD_LIKELY( fd_accdb_open_ro( ctx->accdb, tip_receiver_acc, &xid, tip_receiver ) ) ) {
    1198           0 :       tip_receiver_owner = FD_LOAD( fd_pubkey_t, fd_accdb_ref_owner( tip_receiver_acc ) );
    1199           0 :       fd_accdb_close_ro( ctx->accdb, tip_receiver_acc );
    1200           0 :     }
    1201           0 :   }
    1202             : 
    1203             : 
    1204           0 :   fd_became_leader_t * msg = fd_chunk_to_laddr( ctx->replay_out->mem, ctx->replay_out->chunk );
    1205           0 :   msg->slot = ctx->next_leader_slot;
    1206           0 :   msg->slot_start_ns = now_nanos;
    1207           0 :   msg->slot_end_ns   = now_nanos+(long)ctx->slot_duration_nanos;
    1208           0 :   msg->bank = NULL;
    1209           0 :   msg->bank_idx = bank->data->idx;
    1210           0 :   msg->ticks_per_slot = fd_bank_ticks_per_slot_get( bank );
    1211           0 :   msg->hashcnt_per_tick = fd_bank_hashes_per_tick_get( bank );
    1212           0 :   msg->tick_duration_ns = (ulong)(ctx->slot_duration_nanos/(double)msg->ticks_per_slot);
    1213           0 :   msg->bundle->config[0]       = config[0];
    1214           0 :   memcpy( msg->bundle->last_blockhash,     fd_bank_poh_query( bank )->hash, sizeof(fd_hash_t)   );
    1215           0 :   memcpy( msg->bundle->tip_receiver_owner, tip_receiver_owner.uc,           sizeof(fd_pubkey_t) );
    1216             : 
    1217           0 :   if( FD_UNLIKELY( msg->hashcnt_per_tick==1UL ) ) {
    1218             :     /* Low power producer, maximum of one microblock per tick in the slot */
    1219           0 :     msg->max_microblocks_in_slot = msg->ticks_per_slot;
    1220           0 :   } else {
    1221             :     /* See the long comment in after_credit for this limit */
    1222           0 :     msg->max_microblocks_in_slot = fd_ulong_min( MAX_MICROBLOCKS_PER_SLOT, msg->ticks_per_slot*(msg->hashcnt_per_tick-1UL) );
    1223           0 :   }
    1224             : 
    1225           0 :   msg->total_skipped_ticks = msg->ticks_per_slot*(ctx->next_leader_slot-ctx->reset_slot);
    1226           0 :   msg->epoch = fd_slot_to_epoch( fd_bank_epoch_schedule_query( bank ), ctx->next_leader_slot, NULL );
    1227             : 
    1228           0 :   fd_cost_tracker_t const * cost_tracker = fd_bank_cost_tracker_locking_query( bank );
    1229             : 
    1230           0 :   msg->limits.slot_max_cost = ctx->larger_max_cost_per_block ? LARGER_MAX_COST_PER_BLOCK : cost_tracker->block_cost_limit;
    1231           0 :   msg->limits.slot_max_vote_cost = cost_tracker->vote_cost_limit;
    1232           0 :   msg->limits.slot_max_write_cost_per_acct = cost_tracker->account_cost_limit;
    1233             : 
    1234           0 :   fd_bank_cost_tracker_end_locking_query( bank );
    1235             : 
    1236           0 :   if( FD_UNLIKELY( msg->ticks_per_slot+msg->total_skipped_ticks>USHORT_MAX ) ) {
    1237             :     /* There can be at most USHORT_MAX skipped ticks, because the
    1238             :        parent_offset field in the shred data is only 2 bytes wide. */
    1239           0 :     FD_LOG_ERR(( "too many skipped ticks %lu for slot %lu, chain must halt", msg->ticks_per_slot+msg->total_skipped_ticks, ctx->next_leader_slot ));
    1240           0 :   }
    1241             : 
    1242           0 :   fd_stem_publish( stem, ctx->replay_out->idx, REPLAY_SIG_BECAME_LEADER, ctx->replay_out->chunk, sizeof(fd_became_leader_t), 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
    1243           0 :   ctx->replay_out->chunk = fd_dcache_compact_next( ctx->replay_out->chunk, sizeof(fd_became_leader_t), ctx->replay_out->chunk0, ctx->replay_out->wmark );
    1244             : 
    1245           0 :   ctx->next_leader_slot = ULONG_MAX;
    1246           0 :   ctx->next_leader_tickcount = LONG_MAX;
    1247             : 
    1248           0 :   return 1;
    1249           0 : }
    1250             : 
    1251             : static void
    1252             : process_poh_message( fd_replay_tile_t *                 ctx,
    1253           0 :                      fd_poh_leader_slot_ended_t const * slot_ended ) {
    1254             : 
    1255           0 :   FD_TEST( ctx->is_booted );
    1256           0 :   FD_TEST( ctx->is_leader );
    1257           0 :   FD_TEST( ctx->leader_bank->data!=NULL );
    1258             : 
    1259           0 :   FD_TEST( ctx->highwater_leader_slot>=slot_ended->slot );
    1260           0 :   FD_TEST( ctx->next_leader_slot>ctx->highwater_leader_slot );
    1261             : 
    1262             :   /* Update the poh hash in the bank.  We will want to maintain a refcnt
    1263             :      on the bank until we have recieved the block id for the block after
    1264             :      it has been shredded. */
    1265             : 
    1266           0 :   memcpy( fd_bank_poh_modify( ctx->leader_bank ), slot_ended->blockhash, sizeof(fd_hash_t) );
    1267             : 
    1268           0 :   ctx->recv_poh = 1;
    1269           0 : }
    1270             : 
    1271             : static void
    1272             : publish_reset( fd_replay_tile_t *  ctx,
    1273             :                fd_stem_context_t * stem,
    1274           0 :                fd_bank_t *         bank ) {
    1275           0 :   if( FD_UNLIKELY( ctx->replay_out->idx==ULONG_MAX ) ) return;
    1276             : 
    1277           0 :   fd_hash_t const * block_hash = fd_blockhashes_peek_last_hash( fd_bank_block_hash_queue_query( bank ) );
    1278           0 :   FD_TEST( block_hash );
    1279             : 
    1280           0 :   fd_poh_reset_t * reset = fd_chunk_to_laddr( ctx->replay_out->mem, ctx->replay_out->chunk );
    1281             : 
    1282           0 :   reset->bank_idx         = bank->data->idx;
    1283           0 :   reset->timestamp        = fd_log_wallclock();
    1284           0 :   reset->completed_slot   = fd_bank_slot_get( bank );
    1285           0 :   reset->hashcnt_per_tick = fd_bank_hashes_per_tick_get( bank );
    1286           0 :   reset->ticks_per_slot   = fd_bank_ticks_per_slot_get( bank );
    1287           0 :   reset->tick_duration_ns = (ulong)(ctx->slot_duration_nanos/(double)reset->ticks_per_slot);
    1288           0 :   fd_memcpy( reset->completed_blockhash, block_hash->uc, sizeof(fd_hash_t) );
    1289             : 
    1290           0 :   ulong ticks_per_slot = fd_bank_ticks_per_slot_get( bank );
    1291           0 :   if( FD_UNLIKELY( reset->hashcnt_per_tick==1UL ) ) {
    1292             :     /* Low power producer, maximum of one microblock per tick in the slot */
    1293           0 :     reset->max_microblocks_in_slot = ticks_per_slot;
    1294           0 :   } else {
    1295             :     /* See the long comment in after_credit for this limit */
    1296           0 :     reset->max_microblocks_in_slot = fd_ulong_min( MAX_MICROBLOCKS_PER_SLOT, ticks_per_slot*(reset->hashcnt_per_tick-1UL) );
    1297           0 :   }
    1298           0 :   reset->next_leader_slot = ctx->next_leader_slot;
    1299             : 
    1300           0 :   if( FD_LIKELY( ctx->rpc_enabled ) ) bank->data->refcnt++;
    1301           0 :   FD_LOG_DEBUG(( "bank (idx=%lu, slot=%lu) refcnt incremented to %lu", bank->data->idx, reset->completed_slot, bank->data->refcnt ));
    1302             : 
    1303           0 :   fd_stem_publish( stem, ctx->replay_out->idx, REPLAY_SIG_RESET, ctx->replay_out->chunk, sizeof(fd_poh_reset_t), 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
    1304           0 :   ctx->replay_out->chunk = fd_dcache_compact_next( ctx->replay_out->chunk, sizeof(fd_poh_reset_t), ctx->replay_out->chunk0, ctx->replay_out->wmark );
    1305           0 : }
    1306             : 
    1307             : static void
    1308             : boot_genesis( fd_replay_tile_t *  ctx,
    1309             :               fd_stem_context_t * stem,
    1310             :               ulong               in_idx,
    1311           0 :               ulong               chunk ) {
    1312             :   /* If we are bootstrapping, we can't wait to wait for our identity
    1313             :      vote to be rooted as this creates a circular dependency. */
    1314           0 :   ctx->has_identity_vote_rooted = 1;
    1315             : 
    1316           0 :   uchar const * lthash       = (uchar*)fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk );
    1317           0 :   uchar const * genesis_hash = (uchar*)fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk )+sizeof(fd_lthash_value_t);
    1318             : 
    1319           0 :   fd_genesis_t const * genesis = fd_type_pun( (uchar*)fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk )+sizeof(fd_hash_t)+sizeof(fd_lthash_value_t) );
    1320             : 
    1321           0 :   fd_bank_t bank[1];
    1322           0 :   FD_TEST( fd_banks_bank_query( bank, ctx->banks, FD_REPLAY_BOOT_BANK_IDX ) );
    1323           0 :   fd_funk_txn_xid_t xid = { .ul = { 0UL, FD_REPLAY_BOOT_BANK_IDX } };
    1324             : 
    1325             :   /* Do genesis-related processing in a non-rooted transaction */
    1326           0 :   fd_funk_txn_xid_t root_xid = { .ul = { LONG_MAX, LONG_MAX } };
    1327           0 :   fd_funk_txn_xid_t target_xid = { .ul = { 0UL, 0UL } };
    1328           0 :   fd_accdb_attach_child( ctx->accdb_admin, &root_xid, &target_xid );
    1329           0 :   fd_runtime_read_genesis( ctx->banks, bank, ctx->accdb, &xid, NULL, fd_type_pun_const( genesis_hash ), fd_type_pun_const( lthash ), genesis, &ctx->runtime_stack );
    1330           0 :   fd_accdb_advance_root( ctx->accdb_admin, &target_xid );
    1331             : 
    1332           0 :   static const fd_txncache_fork_id_t txncache_root = { .val = USHORT_MAX };
    1333           0 :   bank->data->txncache_fork_id = fd_txncache_attach_child( ctx->txncache, txncache_root );
    1334             : 
    1335           0 :   fd_hash_t const * block_hash = fd_blockhashes_peek_last_hash( fd_bank_block_hash_queue_query( bank ) );
    1336           0 :   fd_txncache_finalize_fork( ctx->txncache, bank->data->txncache_fork_id, 0UL, block_hash->uc );
    1337             : 
    1338           0 :   publish_stake_weights( ctx, stem, bank, 0 );
    1339           0 :   publish_stake_weights( ctx, stem, bank, 1 );
    1340             : 
    1341             :   /* We call this after fd_runtime_read_genesis, which sets up the
    1342             :      slot_bank needed in blockstore_init. */
    1343           0 :   init_after_snapshot( ctx );
    1344             : 
    1345             :   /* Initialize store for genesis case, similar to snapshot case */
    1346           0 :   fd_hash_t genesis_block_id = { .ul[0] = FD_RUNTIME_INITIAL_BLOCK_ID };
    1347           0 :   fd_store_exacq( ctx->store );
    1348           0 :   if( FD_UNLIKELY( fd_store_root( ctx->store ) ) ) {
    1349           0 :     FD_LOG_CRIT(( "invariant violation: store root is not 0 for genesis" ));
    1350           0 :   }
    1351           0 :   fd_store_insert( ctx->store, 0, &genesis_block_id );
    1352           0 :   ctx->store->slot0 = 0UL; /* Genesis slot */
    1353           0 :   fd_store_exrel( ctx->store );
    1354             : 
    1355           0 :   ctx->published_root_slot = 0UL;
    1356           0 :   fd_sched_block_add_done( ctx->sched, bank->data->idx, ULONG_MAX, 0UL );
    1357             : 
    1358           0 :   fd_bank_block_height_set( bank, 1UL );
    1359             : 
    1360           0 :   ctx->consensus_root          = (fd_hash_t){ .ul[0] = FD_RUNTIME_INITIAL_BLOCK_ID };
    1361           0 :   ctx->consensus_root_slot     = 0UL;
    1362           0 :   ctx->consensus_root_bank_idx = 0UL;
    1363           0 :   ctx->published_root_slot     = 0UL;
    1364           0 :   ctx->published_root_bank_idx = 0UL;
    1365             : 
    1366           0 :   ctx->reset_slot            = 0UL;
    1367           0 :   fd_memcpy( ctx->reset_bank, bank, sizeof(fd_bank_t) );
    1368           0 :   ctx->reset_timestamp_nanos = fd_log_wallclock();
    1369           0 :   ctx->next_leader_slot      = fd_multi_epoch_leaders_get_next_slot( ctx->mleaders, 1UL, ctx->identity_pubkey );
    1370           0 :   if( FD_LIKELY( ctx->next_leader_slot != ULONG_MAX ) ) {
    1371           0 :     ctx->next_leader_tickcount = (long)((double)(ctx->next_leader_slot-ctx->reset_slot-1UL)*ctx->slot_duration_ticks) + fd_tickcount();
    1372           0 :   } else {
    1373           0 :     ctx->next_leader_tickcount = LONG_MAX;
    1374           0 :   }
    1375             : 
    1376           0 :   ctx->is_booted = 1;
    1377           0 :   maybe_become_leader( ctx, stem );
    1378             : 
    1379           0 :   fd_hash_t initial_block_id = { .ul = { FD_RUNTIME_INITIAL_BLOCK_ID } };
    1380           0 :   fd_reasm_fec_t * fec       = fd_reasm_insert( ctx->reasm, &initial_block_id, NULL, 0 /* genesis slot */, 0, 0, 0, 0, 1, 0 ); /* FIXME manifest block_id */
    1381           0 :   fec->bank_idx              = 0UL;
    1382             : 
    1383             : 
    1384           0 :   fd_block_id_ele_t * block_id_ele = &ctx->block_id_arr[ 0 ];
    1385           0 :   FD_TEST( block_id_ele );
    1386           0 :   block_id_ele->block_id = initial_block_id;
    1387           0 :   block_id_ele->slot     = 0UL;
    1388             : 
    1389           0 :   FD_TEST( fd_block_id_map_ele_insert( ctx->block_id_map, block_id_ele, ctx->block_id_arr ) );
    1390             : 
    1391           0 :   fd_replay_slot_completed_t * slot_info = fd_chunk_to_laddr( ctx->replay_out->mem, ctx->replay_out->chunk );
    1392           0 :   slot_info->identity_balance = get_identity_balance( ctx, xid );
    1393             : 
    1394           0 :   publish_slot_completed( ctx, stem, bank, 1, 0 /* is_leader */ );
    1395           0 :   publish_root_advanced( ctx, stem );
    1396           0 :   publish_reset( ctx, stem, bank );
    1397           0 : }
    1398             : 
    1399             : static inline void
    1400           0 : maybe_verify_cluster_type( fd_replay_tile_t * ctx ) {
    1401           0 :   if( FD_UNLIKELY( !ctx->is_booted || !ctx->has_genesis_hash ) ) {
    1402           0 :     return;
    1403           0 :   }
    1404             : 
    1405           0 :   FD_BASE58_ENCODE_32_BYTES( ctx->genesis_hash, hash_cstr );
    1406           0 :   ulong cluster = fd_genesis_cluster_identify( hash_cstr );
    1407             :   /* Map pyth-related clusters to unkwown. */
    1408           0 :   switch( cluster ) {
    1409           0 :     case FD_CLUSTER_PYTHNET:
    1410           0 :     case FD_CLUSTER_PYTHTEST:
    1411           0 :       cluster = FD_CLUSTER_UNKNOWN;
    1412           0 :   }
    1413             : 
    1414           0 :   if( FD_UNLIKELY( cluster!=ctx->cluster_type ) ) {
    1415           0 :     FD_LOG_ERR(( "Your genesis.bin file at `%s` has a genesis hash of `%s` which means the cluster is %s "
    1416           0 :                  "but the snapshot you loaded is for a different cluster %s. If you are trying to join the "
    1417           0 :                  "%s cluster, you can delete the genesis.bin file and restart the node to download the correct "
    1418           0 :                  "genesis file automatically.",
    1419           0 :                  ctx->genesis_path,
    1420           0 :                  hash_cstr,
    1421           0 :                  fd_genesis_cluster_name( cluster ),
    1422           0 :                  fd_genesis_cluster_name( ctx->cluster_type ),
    1423           0 :                  fd_genesis_cluster_name( cluster ) ));
    1424           0 :   }
    1425           0 : }
    1426             : 
    1427             : static void
    1428             : on_snapshot_message( fd_replay_tile_t *  ctx,
    1429             :                      fd_stem_context_t * stem,
    1430             :                      ulong               in_idx,
    1431             :                      ulong               chunk,
    1432           0 :                      ulong               sig ) {
    1433           0 :   ulong msg = fd_ssmsg_sig_message( sig );
    1434           0 :   if( FD_LIKELY( msg==FD_SSMSG_DONE ) ) {
    1435             :     /* An end of message notification indicates the snapshot is loaded.
    1436             :        Replay is able to start executing from this point onwards. */
    1437             :     /* TODO: replay should finish booting. Could make replay a
    1438             :        state machine and set the state here accordingly. */
    1439           0 :     ctx->is_booted = 1;
    1440             : 
    1441           0 :     fd_bank_t bank[1];
    1442           0 :     if( FD_UNLIKELY( !fd_banks_bank_query( bank, ctx->banks, FD_REPLAY_BOOT_BANK_IDX ) ) ) {
    1443           0 :       FD_LOG_CRIT(( "invariant violation: bank is NULL for bank index %lu", FD_REPLAY_BOOT_BANK_IDX ));
    1444           0 :     }
    1445             : 
    1446           0 :     ulong snapshot_slot = fd_bank_slot_get( bank );
    1447             :     /* FIXME: This is a hack because the block id of the snapshot slot
    1448             :        is not provided in the snapshot.  A possible solution is to get
    1449             :        the block id of the snapshot slot from repair. */
    1450           0 :     fd_hash_t manifest_block_id = { .ul = { FD_RUNTIME_INITIAL_BLOCK_ID } };
    1451             : 
    1452           0 :     fd_store_exacq( ctx->store );
    1453           0 :     FD_TEST( !fd_store_root( ctx->store ) );
    1454           0 :     fd_store_insert( ctx->store, 0, &manifest_block_id );
    1455           0 :     ctx->store->slot0 = snapshot_slot; /* FIXME manifest_block_id */
    1456           0 :     fd_store_exrel( ctx->store );
    1457             : 
    1458             :     /* Typically, when we cross an epoch boundary during normal
    1459             :        operation, we publish the stake weights for the new epoch.  But
    1460             :        since we are starting from a snapshot, we need to publish two
    1461             :        epochs worth of stake weights: the previous epoch (which is
    1462             :        needed for voting on the current epoch), and the current epoch
    1463             :        (which is needed for voting on the next epoch). */
    1464           0 :     publish_stake_weights( ctx, stem, bank, 0 );
    1465           0 :     publish_stake_weights( ctx, stem, bank, 1 );
    1466             : 
    1467           0 :     ctx->consensus_root          = manifest_block_id;
    1468           0 :     ctx->consensus_root_slot     = snapshot_slot;
    1469           0 :     ctx->consensus_root_bank_idx = 0UL;
    1470           0 :     ctx->published_root_slot     = ctx->consensus_root_slot;
    1471           0 :     ctx->published_root_bank_idx = 0UL;
    1472             : 
    1473           0 :     ctx->reset_slot            = snapshot_slot;
    1474           0 :     fd_memcpy( ctx->reset_bank, bank, sizeof(fd_bank_t) );
    1475           0 :     ctx->reset_timestamp_nanos = fd_log_wallclock();
    1476           0 :     ctx->next_leader_slot      = fd_multi_epoch_leaders_get_next_slot( ctx->mleaders, 1UL, ctx->identity_pubkey );
    1477           0 :     if( FD_LIKELY( ctx->next_leader_slot != ULONG_MAX ) ) {
    1478           0 :       ctx->next_leader_tickcount = (long)((double)(ctx->next_leader_slot-ctx->reset_slot-1UL)*ctx->slot_duration_ticks) + fd_tickcount();
    1479           0 :     } else {
    1480           0 :       ctx->next_leader_tickcount = LONG_MAX;
    1481           0 :     }
    1482             : 
    1483           0 :     fd_sched_block_add_done( ctx->sched, bank->data->idx, ULONG_MAX, snapshot_slot );
    1484           0 :     FD_TEST( bank->data->idx==0UL );
    1485             : 
    1486           0 :     fd_funk_txn_xid_t xid = { .ul = { snapshot_slot, FD_REPLAY_BOOT_BANK_IDX } };
    1487             : 
    1488           0 :     fd_features_restore( bank, ctx->accdb, &xid );
    1489             : 
    1490           0 :     fd_runtime_update_leaders( bank, &ctx->runtime_stack );
    1491             : 
    1492           0 :     fd_block_id_ele_t * block_id_ele = &ctx->block_id_arr[ 0 ];
    1493           0 :     FD_TEST( block_id_ele );
    1494           0 :     block_id_ele->block_id = manifest_block_id;
    1495           0 :     block_id_ele->slot     = snapshot_slot;
    1496           0 :     FD_TEST( fd_block_id_map_ele_insert( ctx->block_id_map, block_id_ele, ctx->block_id_arr ) );
    1497             : 
    1498             :     /* We call this after fd_runtime_read_genesis, which sets up the
    1499             :        slot_bank needed in blockstore_init. */
    1500           0 :     init_after_snapshot( ctx );
    1501             : 
    1502           0 :     fd_replay_slot_completed_t * slot_info = fd_chunk_to_laddr( ctx->replay_out->mem, ctx->replay_out->chunk );
    1503           0 :     slot_info->identity_balance = get_identity_balance( ctx, xid );
    1504             : 
    1505           0 :     publish_slot_completed( ctx, stem, bank, 1, 0 /* is_leader */ );
    1506           0 :     publish_root_advanced( ctx, stem );
    1507             : 
    1508           0 :     fd_reasm_fec_t * fec = fd_reasm_insert( ctx->reasm, &manifest_block_id, NULL, snapshot_slot, 0, 0, 0, 0, 1, 0 ); /* FIXME manifest block_id */
    1509           0 :     fec->bank_idx        = 0UL;
    1510             : 
    1511           0 :     ctx->cluster_type = fd_bank_cluster_type_get( bank );
    1512             : 
    1513           0 :     maybe_verify_cluster_type( ctx );
    1514             : 
    1515           0 :     return;
    1516           0 :   }
    1517             : 
    1518           0 :   switch( msg ) {
    1519           0 :     case FD_SSMSG_MANIFEST_FULL:
    1520           0 :     case FD_SSMSG_MANIFEST_INCREMENTAL: {
    1521             :       /* We may either receive a full snapshot manifest or an
    1522             :          incremental snapshot manifest.  Note that this external message
    1523             :          id is only used temporarily because replay cannot yet receive
    1524             :          the firedancer-internal snapshot manifest message. */
    1525           0 :       if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark ) )
    1526           0 :         FD_LOG_ERR(( "chunk %lu from in %d corrupt, not in range [%lu,%lu]", chunk, ctx->in_kind[ in_idx ], ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark ));
    1527             : 
    1528           0 :       fd_bank_t bank[1];
    1529           0 :       fd_ssload_recover( fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk ),
    1530           0 :                          ctx->banks,
    1531           0 :                          fd_banks_bank_query( bank, ctx->banks, FD_REPLAY_BOOT_BANK_IDX ),
    1532           0 :                          ctx->runtime_stack.stakes.vote_credits,
    1533           0 :                          msg==FD_SSMSG_MANIFEST_INCREMENTAL );
    1534             : 
    1535           0 :       fd_snapshot_manifest_t const * manifest = fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk );
    1536           0 :       ctx->hard_forks_cnt = manifest->hard_forks_len;
    1537           0 :       for( ulong i=0UL; i<manifest->hard_forks_len; i++ ) ctx->hard_forks[ i ] = manifest->hard_forks[ i ];
    1538           0 :       break;
    1539           0 :     }
    1540           0 :     default: {
    1541           0 :       FD_LOG_ERR(( "Received unknown snapshot message with msg %lu", msg ));
    1542           0 :       return;
    1543           0 :     }
    1544           0 :   }
    1545             : 
    1546           0 :   return;
    1547           0 : }
    1548             : 
    1549             : static void
    1550             : dispatch_task( fd_replay_tile_t *  ctx,
    1551             :                fd_stem_context_t * stem,
    1552           0 :                fd_sched_task_t *   task ) {
    1553             : 
    1554           0 :   switch( task->task_type ) {
    1555           0 :     case FD_SCHED_TT_TXN_EXEC: {
    1556           0 :       fd_txn_p_t * txn_p = fd_sched_get_txn( ctx->sched, task->txn_exec->txn_idx );
    1557             : 
    1558             :       /* FIXME: this should be done during txn parsing so that we don't
    1559             :          have to loop over all accounts a second time. */
    1560             :       /* Insert or reverify invoked programs for this epoch, if needed. */
    1561           0 :       fd_bank_t bank[1];
    1562           0 :       FD_TEST( fd_banks_bank_query( bank, ctx->banks, task->txn_exec->bank_idx ) );
    1563             : 
    1564           0 : #     if FD_HAS_FLATCC
    1565             :       /* Add the transaction to the block dumper if necessary. This
    1566             :          logic doesn't need to be fork-aware since it's only meant to
    1567             :          be used in backtest. */
    1568           0 :       if( FD_UNLIKELY( ctx->capture_ctx && ctx->capture_ctx->dump_block_to_pb ) ) {
    1569           0 :         fd_dump_block_to_protobuf_collect_tx( ctx->block_dump_ctx, txn_p );
    1570           0 :       }
    1571           0 : #     endif
    1572             : 
    1573           0 :       bank->data->refcnt++;
    1574             : 
    1575           0 :       if( FD_UNLIKELY( !bank->data->first_transaction_scheduled_nanos ) ) bank->data->first_transaction_scheduled_nanos = fd_log_wallclock();
    1576             : 
    1577           0 :       fd_replay_out_link_t *   exec_out = ctx->exec_out;
    1578           0 :       fd_exec_txn_exec_msg_t * exec_msg = fd_chunk_to_laddr( exec_out->mem, exec_out->chunk );
    1579           0 :       memcpy( &exec_msg->txn, txn_p, sizeof(fd_txn_p_t) );
    1580           0 :       exec_msg->bank_idx = task->txn_exec->bank_idx;
    1581           0 :       exec_msg->txn_idx  = task->txn_exec->txn_idx;
    1582           0 :       if( FD_UNLIKELY( ctx->capture_ctx ) ) {
    1583           0 :         exec_msg->capture_txn_idx = ctx->capture_ctx->current_txn_idx++;
    1584           0 :       }
    1585           0 :       fd_stem_publish( stem, exec_out->idx, (FD_EXEC_TT_TXN_EXEC<<32) | task->txn_exec->exec_idx, exec_out->chunk, sizeof(*exec_msg), 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
    1586           0 :       exec_out->chunk = fd_dcache_compact_next( exec_out->chunk, sizeof(*exec_msg), exec_out->chunk0, exec_out->wmark );
    1587           0 :       break;
    1588           0 :     }
    1589           0 :     case FD_SCHED_TT_TXN_SIGVERIFY: {
    1590           0 :       fd_txn_p_t * txn_p = fd_sched_get_txn( ctx->sched, task->txn_sigverify->txn_idx );
    1591             : 
    1592           0 :       fd_bank_t bank[1];
    1593           0 :       FD_TEST( fd_banks_bank_query( bank, ctx->banks, task->txn_sigverify->bank_idx ) );
    1594           0 :       bank->data->refcnt++;
    1595             : 
    1596           0 :       fd_replay_out_link_t *        exec_out = ctx->exec_out;
    1597           0 :       fd_exec_txn_sigverify_msg_t * exec_msg = fd_chunk_to_laddr( exec_out->mem, exec_out->chunk );
    1598           0 :       memcpy( &exec_msg->txn, txn_p, sizeof(fd_txn_p_t) );
    1599           0 :       exec_msg->bank_idx = task->txn_sigverify->bank_idx;
    1600           0 :       exec_msg->txn_idx  = task->txn_sigverify->txn_idx;
    1601           0 :       fd_stem_publish( stem, exec_out->idx, (FD_EXEC_TT_TXN_SIGVERIFY<<32) | task->txn_sigverify->exec_idx, exec_out->chunk, sizeof(*exec_msg), 0UL, 0UL, 0UL );
    1602           0 :       exec_out->chunk = fd_dcache_compact_next( exec_out->chunk, sizeof(*exec_msg), exec_out->chunk0, exec_out->wmark );
    1603           0 :       break;
    1604           0 :     };
    1605           0 :     default: {
    1606           0 :       FD_LOG_CRIT(( "unexpected task type %lu", task->task_type ));
    1607           0 :     }
    1608           0 :   }
    1609           0 : }
    1610             : 
    1611             : /* Returns 1 if charge_busy. */
    1612             : static int
    1613             : replay( fd_replay_tile_t *  ctx,
    1614           0 :         fd_stem_context_t * stem ) {
    1615             : 
    1616           0 :   if( FD_UNLIKELY( !ctx->is_booted ) ) return 0;
    1617             : 
    1618           0 :   int charge_busy = 0;
    1619           0 :   fd_sched_task_t task[ 1 ];
    1620           0 :   if( FD_UNLIKELY( !fd_sched_task_next_ready( ctx->sched, task ) ) ) {
    1621           0 :     return charge_busy; /* Nothing to execute or do. */
    1622           0 :   }
    1623             : 
    1624           0 :   charge_busy = 1;
    1625             : 
    1626           0 :   switch( task->task_type ) {
    1627           0 :     case FD_SCHED_TT_BLOCK_START: {
    1628           0 :       replay_block_start( ctx, stem, task->block_start->bank_idx, task->block_start->parent_bank_idx, task->block_start->slot );
    1629           0 :       fd_sched_task_done( ctx->sched, FD_SCHED_TT_BLOCK_START, ULONG_MAX, ULONG_MAX );
    1630           0 :       break;
    1631           0 :     }
    1632           0 :     case FD_SCHED_TT_BLOCK_END: {
    1633           0 :       fd_bank_t bank[1];
    1634           0 :       fd_banks_bank_query( bank, ctx->banks, task->block_end->bank_idx );
    1635           0 :       if( FD_LIKELY( !(bank->data->flags&FD_BANK_FLAGS_DEAD) ) ) replay_block_finalize( ctx, stem, bank );
    1636           0 :       fd_sched_task_done( ctx->sched, FD_SCHED_TT_BLOCK_END, ULONG_MAX, ULONG_MAX );
    1637           0 :       break;
    1638           0 :     }
    1639           0 :     case FD_SCHED_TT_TXN_EXEC:
    1640           0 :     case FD_SCHED_TT_TXN_SIGVERIFY: {
    1641             :       /* Likely/common case: we have a transaction we actually need to
    1642             :          execute. */
    1643           0 :       dispatch_task( ctx, stem, task );
    1644           0 :       break;
    1645           0 :     }
    1646           0 :     default: {
    1647           0 :       FD_LOG_CRIT(( "unexpected task type %lu", task->task_type ));
    1648           0 :     }
    1649           0 :   }
    1650             : 
    1651           0 :   return charge_busy;
    1652           0 : }
    1653             : 
    1654             : static int
    1655           0 : can_process_fec( fd_replay_tile_t * ctx ) {
    1656           0 :   fd_reasm_fec_t * fec;
    1657           0 :   if( FD_UNLIKELY( !fd_sched_can_ingest( ctx->sched, 1UL ) ) ) {
    1658           0 :     ctx->metrics.sched_full++;
    1659           0 :     return 0;
    1660           0 :   }
    1661             : 
    1662           0 :   if( FD_UNLIKELY( (fec = fd_reasm_peek( ctx->reasm ))==NULL ) ) {
    1663           0 :     ctx->metrics.reasm_empty++;
    1664           0 :     return 0;
    1665           0 :   }
    1666             : 
    1667           0 :   ctx->metrics.reasm_latest_slot    = fec->slot;
    1668           0 :   ctx->metrics.reasm_latest_fec_idx = fec->fec_set_idx;
    1669             : 
    1670           0 :   if( FD_UNLIKELY( ctx->is_leader && fec->fec_set_idx==0U && fd_reasm_parent( ctx->reasm, fec )->bank_idx==ctx->leader_bank->data->idx ) ) {
    1671             :     /* There's a race that's exceedingly rare, where we receive the
    1672             :        FEC set for the slot right after our leader rotation before we
    1673             :        freeze the bank for the last slot in our leader rotation.
    1674             :        Leader slot freezing happens only after if we've received the
    1675             :        final PoH hash from the poh tile as well as the final FEC set
    1676             :        for the leader slot.  So the race happens when FEC sets are
    1677             :        delivered and processed sooner than the PoH hash, aka when the
    1678             :        poh=>shred=>replay path for the block id somehow beats the
    1679             :        poh=>replay path for the poh hash.  To mitigate this race,
    1680             :        we must block on ingesting the FEC set for the ensuing slot
    1681             :        before the leader bank freezes, because that would violate
    1682             :        ordering invariants in banks and sched. */
    1683           0 :     FD_TEST( ctx->block_id_arr[ ctx->leader_bank->data->idx ].block_id_seen );
    1684           0 :     FD_TEST( !ctx->recv_poh );
    1685           0 :     ctx->metrics.leader_bid_wait++;
    1686           0 :     return 0;
    1687           0 :   }
    1688             : 
    1689             :   /* If fec_set_idx is 0, we need a new bank for a new slot.  Banks must
    1690             :      not be full in this case. */
    1691           0 :   if( FD_UNLIKELY( fd_banks_is_full( ctx->banks ) && fec->fec_set_idx==0 ) ) {
    1692           0 :     ctx->metrics.banks_full++;
    1693           0 :     return 0;
    1694           0 :   }
    1695             : 
    1696             :   /* Otherwise, banks may not be full, so we can always create a new
    1697             :      bank if needed.  Or, if banks are full, the current fec set's
    1698             :      ancestor (idx 0) already created a bank for this slot.*/
    1699           0 :   return 1;
    1700           0 : }
    1701             : 
    1702             : static void
    1703             : process_fec_set( fd_replay_tile_t *  ctx,
    1704             :                  fd_stem_context_t * stem,
    1705           0 :                  fd_reasm_fec_t *    reasm_fec ) {
    1706           0 :   long now = fd_log_wallclock();
    1707             : 
    1708             :   /* Linking only requires a shared lock because the fields that are
    1709             :      modified are only read on publish which uses exclusive lock. */
    1710             : 
    1711           0 :   long shacq_start, shacq_end, shrel_end;
    1712             : 
    1713           0 :   FD_STORE_SHARED_LOCK( ctx->store, shacq_start, shacq_end, shrel_end ) {
    1714           0 :     if( FD_UNLIKELY( !fd_store_link( ctx->store, &reasm_fec->key, &reasm_fec->cmr ) ) ) {
    1715           0 :       FD_BASE58_ENCODE_32_BYTES( reasm_fec->key.key, key_b58 );
    1716           0 :       FD_BASE58_ENCODE_32_BYTES( reasm_fec->cmr.key, cmr_b58 );
    1717           0 :       FD_LOG_WARNING(( "failed to link %s %s. slot %lu fec_set_idx %u", key_b58, cmr_b58, reasm_fec->slot, reasm_fec->fec_set_idx ));
    1718           0 :     }
    1719           0 :   } FD_STORE_SHARED_LOCK_END;
    1720           0 :   fd_histf_sample( ctx->metrics.store_link_wait, (ulong)fd_long_max( shacq_end - shacq_start, 0L ) );
    1721           0 :   fd_histf_sample( ctx->metrics.store_link_work, (ulong)fd_long_max( shrel_end - shacq_end,   0L ) );
    1722             : 
    1723             :   /* Update the reasm_fec with the correct bank index and parent bank
    1724             :      index.  If the FEC belongs to a leader, we have already allocated
    1725             :      a bank index for the FEC and it just needs to be propagated to the
    1726             :      reasm_fec. */
    1727             : 
    1728           0 :   reasm_fec->parent_bank_idx = fd_reasm_parent( ctx->reasm, reasm_fec )->bank_idx;
    1729             : 
    1730           0 :   if( FD_UNLIKELY( reasm_fec->leader ) ) {
    1731             :     /* If we are the leader we just need to copy in the bank index that
    1732             :        the leader slot is using. */
    1733           0 :     FD_TEST( ctx->leader_bank->data!=NULL );
    1734           0 :     reasm_fec->bank_idx = ctx->leader_bank->data->idx;
    1735           0 :   } else if( FD_UNLIKELY( reasm_fec->fec_set_idx==0U ) ) {
    1736             :     /* If we are seeing a FEC with fec set idx 0, this means that we are
    1737             :        starting a new slot, and we need a new bank index. */
    1738           0 :     fd_bank_t bank[1];
    1739           0 :     reasm_fec->bank_idx = fd_banks_new_bank( bank, ctx->banks, reasm_fec->parent_bank_idx, now )->data->idx;
    1740             :     /* At this point remove any stale entry in the block id map if it
    1741             :        exists and set the block id as not having been seen yet.  This is
    1742             :        safe because we know that the old entry for this bank index has
    1743             :        already been pruned away. */
    1744           0 :     fd_block_id_ele_t * block_id_ele = &ctx->block_id_arr[ reasm_fec->bank_idx ];
    1745           0 :     if( FD_LIKELY( fd_block_id_map_ele_query( ctx->block_id_map, &block_id_ele->block_id, NULL, ctx->block_id_arr )==block_id_ele ) ) {
    1746           0 :       FD_TEST( fd_block_id_map_ele_remove( ctx->block_id_map, &block_id_ele->block_id, NULL, ctx->block_id_arr ) );
    1747           0 :     }
    1748           0 :     block_id_ele->block_id_seen = 0;
    1749           0 :     block_id_ele->slot          = reasm_fec->slot;
    1750           0 :   } else {
    1751             :     /* We are continuing to execute through a slot that we already have
    1752             :        a bank index for. */
    1753           0 :     reasm_fec->bank_idx = reasm_fec->parent_bank_idx;
    1754           0 :   }
    1755             : 
    1756           0 :   if( FD_UNLIKELY( reasm_fec->slot_complete ) ) {
    1757           0 :     fd_block_id_ele_t * block_id_ele = &ctx->block_id_arr[ reasm_fec->bank_idx ];
    1758           0 :     FD_TEST( block_id_ele );
    1759             : 
    1760           0 :     block_id_ele->block_id_seen = 1;
    1761           0 :     block_id_ele->block_id      = reasm_fec->key;
    1762           0 :     FD_TEST( fd_block_id_map_ele_insert( ctx->block_id_map, block_id_ele, ctx->block_id_arr ) );
    1763           0 :   }
    1764             : 
    1765           0 :   if( FD_UNLIKELY( reasm_fec->leader ) ) {
    1766             :     /* If we are the leader, we don't need to process the FEC set any
    1767             :        further. */
    1768           0 :     return;
    1769           0 :   }
    1770             : 
    1771             :   /* Forks form a partial ordering over FEC sets. The Repair tile
    1772             :      delivers FEC sets in-order per fork, but FEC set ordering across
    1773             :      forks is arbitrary */
    1774           0 :   fd_sched_fec_t sched_fec[ 1 ];
    1775             : 
    1776             : # if DEBUG_LOGGING
    1777             :   FD_BASE58_ENCODE_32_BYTES( reasm_fec->key.key, key_b58 );
    1778             :   FD_BASE58_ENCODE_32_BYTES( reasm_fec->cmr.key, cmr_b58 );
    1779             :   FD_LOG_INFO(( "replay processing FEC set for slot %lu fec_set_idx %u, mr %s cmr %s", reasm_fec->slot, reasm_fec->fec_set_idx, key_b58, cmr_b58 ));
    1780             : # endif
    1781             : 
    1782             :   /* Read FEC set from the store.  This should happen before we try to
    1783             :      ingest the FEC set.  This allows us to filter out frags that were
    1784             :      in-flight when we published away minority forks that the frags land
    1785             :      on.  These frags would have no bank to execute against, because
    1786             :      their corresponding banks, or parent banks, have also been pruned
    1787             :      during publishing.  A query against store will rightfully tell us
    1788             :      that the underlying data is not found, implying that this is for a
    1789             :      minority fork that we can safely ignore. */
    1790           0 :   FD_STORE_SHARED_LOCK( ctx->store, shacq_start, shacq_end, shrel_end ) {
    1791           0 :     fd_store_fec_t * store_fec = fd_store_query( ctx->store, &reasm_fec->key );
    1792           0 :     if( FD_UNLIKELY( !store_fec ) ) {
    1793             :       /* The only case in which a FEC is not found in the store after
    1794             :          repair has notified is if the FEC was on a minority fork that
    1795             :          has already been published away.  In this case we abandon the
    1796             :          entire slice because it is no longer relevant.  */
    1797           0 :       FD_BASE58_ENCODE_32_BYTES( reasm_fec->key.key, key_b58 );
    1798           0 :       FD_LOG_WARNING(( "store fec for slot: %lu is on minority fork already pruned by publish. abandoning slice. root: %lu. pruned merkle: %s", reasm_fec->slot, ctx->consensus_root_slot, key_b58 ));
    1799           0 :       return;
    1800           0 :     }
    1801           0 :     FD_TEST( store_fec );
    1802           0 :     sched_fec->fec       = store_fec;
    1803           0 :     sched_fec->shred_cnt = reasm_fec->data_cnt;
    1804           0 :   } FD_STORE_SHARED_LOCK_END;
    1805             : 
    1806           0 :   fd_histf_sample( ctx->metrics.store_read_wait, (ulong)fd_long_max( shacq_end - shacq_start, 0UL ) );
    1807           0 :   fd_histf_sample( ctx->metrics.store_read_work, (ulong)fd_long_max( shrel_end - shacq_end,   0UL ) );
    1808             : 
    1809           0 :   sched_fec->is_last_in_batch       = !!reasm_fec->data_complete;
    1810           0 :   sched_fec->is_last_in_block       = !!reasm_fec->slot_complete;
    1811           0 :   sched_fec->bank_idx               = reasm_fec->bank_idx;
    1812           0 :   sched_fec->parent_bank_idx        = reasm_fec->parent_bank_idx;
    1813           0 :   sched_fec->slot                   = reasm_fec->slot;
    1814           0 :   sched_fec->parent_slot            = reasm_fec->slot - reasm_fec->parent_off;
    1815           0 :   sched_fec->is_first_in_block      = reasm_fec->fec_set_idx==0U;
    1816           0 :   fd_funk_txn_xid_t const root = fd_accdb_root_get( ctx->accdb_admin );
    1817           0 :   fd_funk_txn_xid_copy( sched_fec->alut_ctx->xid, &root );
    1818           0 :   sched_fec->alut_ctx->accdb[0]     = ctx->accdb[0];
    1819           0 :   sched_fec->alut_ctx->els          = ctx->published_root_slot;
    1820             : 
    1821           0 :   fd_bank_t bank[1];
    1822           0 :   fd_banks_bank_query( bank, ctx->banks, sched_fec->bank_idx );
    1823           0 :   if( FD_UNLIKELY( bank->data->flags&FD_BANK_FLAGS_DEAD ) ) {
    1824           0 :     if( FD_UNLIKELY( reasm_fec->slot_complete ) ) publish_slot_dead( ctx, stem, bank );
    1825           0 :     return;
    1826           0 :   }
    1827             : 
    1828           0 :   if( FD_UNLIKELY( !fd_sched_fec_ingest( ctx->sched, sched_fec ) ) ) {
    1829           0 :     fd_banks_mark_bank_dead( ctx->banks, bank );
    1830           0 :   }
    1831           0 : }
    1832             : 
    1833             : static void
    1834             : funk_publish( fd_replay_tile_t * ctx,
    1835             :               ulong              slot,
    1836           0 :               ulong              bank_idx ) {
    1837           0 :   fd_funk_txn_xid_t xid = { .ul[0] = slot, .ul[1] = bank_idx };
    1838           0 :   FD_LOG_DEBUG(( "publishing slot=%lu", slot ));
    1839             : 
    1840             :   /* This is the standard case.  Publish all transactions up to and
    1841             :      including the watermark.  This will publish any in-prep ancestors
    1842             :      of root_txn as well. */
    1843           0 :   fd_accdb_advance_root( ctx->accdb_admin, &xid );
    1844           0 :   fd_progcache_txn_advance_root( ctx->progcache_admin, &xid );
    1845           0 : }
    1846             : 
    1847             : static int
    1848           0 : advance_published_root( fd_replay_tile_t * ctx ) {
    1849             : 
    1850           0 :   fd_block_id_ele_t * block_id_ele = fd_block_id_map_ele_query( ctx->block_id_map, &ctx->consensus_root, NULL, ctx->block_id_arr );
    1851           0 :   if( FD_UNLIKELY( !block_id_ele ) ) {
    1852           0 :     FD_BASE58_ENCODE_32_BYTES( ctx->consensus_root.key, consensus_root_b58 );
    1853           0 :     FD_LOG_CRIT(( "invariant violation: block id ele not found for consensus root %s", consensus_root_b58 ));
    1854           0 :   }
    1855           0 :   ulong target_bank_idx = fd_block_id_ele_get_idx( ctx->block_id_arr, block_id_ele );
    1856             : 
    1857           0 :   fd_sched_root_notify( ctx->sched, target_bank_idx );
    1858             : 
    1859             :   /* If the identity vote has been seen on a bank that should be rooted,
    1860             :      then we are now ready to produce blocks. */
    1861           0 :   if( FD_UNLIKELY( !ctx->has_identity_vote_rooted ) ) {
    1862           0 :     fd_bank_t root_bank[1];
    1863           0 :     if( FD_UNLIKELY( !fd_banks_bank_query( root_bank, ctx->banks, target_bank_idx ) ) ) FD_LOG_CRIT(( "invariant violation: root bank not found for bank index %lu", target_bank_idx ));
    1864           0 :     if( FD_LIKELY( fd_bank_has_identity_vote_get( root_bank ) ) ) ctx->has_identity_vote_rooted = 1;
    1865           0 :   }
    1866             : 
    1867           0 :   ulong advanceable_root_idx = ULONG_MAX;
    1868           0 :   if( FD_UNLIKELY( !fd_banks_advance_root_prepare( ctx->banks, target_bank_idx, &advanceable_root_idx ) ) ) {
    1869           0 :     ctx->metrics.storage_root_behind++;
    1870           0 :     return 0;
    1871           0 :   }
    1872             : 
    1873           0 :   fd_bank_t bank[1];
    1874           0 :   FD_TEST( fd_banks_bank_query( bank, ctx->banks, advanceable_root_idx ) );
    1875             : 
    1876           0 :   fd_block_id_ele_t * advanceable_root_ele = &ctx->block_id_arr[ advanceable_root_idx ];
    1877           0 :   if( FD_UNLIKELY( !advanceable_root_ele ) ) {
    1878           0 :     FD_LOG_CRIT(( "invariant violation: advanceable root ele not found for bank index %lu", advanceable_root_idx ));
    1879           0 :   }
    1880             : 
    1881           0 :   long exacq_start, exacq_end, exrel_end;
    1882           0 :   FD_STORE_EXCLUSIVE_LOCK( ctx->store, exacq_start, exacq_end, exrel_end ) {
    1883           0 :     fd_store_publish( ctx->store, &advanceable_root_ele->block_id );
    1884           0 :   } FD_STORE_EXCLUSIVE_LOCK_END;
    1885             : 
    1886           0 :   fd_histf_sample( ctx->metrics.store_publish_wait, (ulong)fd_long_max( exacq_end-exacq_start, 0UL ) );
    1887           0 :   fd_histf_sample( ctx->metrics.store_publish_work, (ulong)fd_long_max( exrel_end-exacq_end,   0UL ) );
    1888             : 
    1889           0 :   ulong advanceable_root_slot = fd_bank_slot_get( bank );
    1890           0 :   funk_publish( ctx, advanceable_root_slot, bank->data->idx );
    1891             : 
    1892           0 :   fd_txncache_advance_root( ctx->txncache, bank->data->txncache_fork_id );
    1893           0 :   fd_sched_advance_root( ctx->sched, advanceable_root_idx );
    1894           0 :   fd_banks_advance_root( ctx->banks, advanceable_root_idx );
    1895           0 :   fd_reasm_publish( ctx->reasm, &advanceable_root_ele->block_id );
    1896             : 
    1897           0 :   ctx->published_root_slot     = advanceable_root_slot;
    1898           0 :   ctx->published_root_bank_idx = advanceable_root_idx;
    1899             : 
    1900           0 :   return 1;
    1901           0 : }
    1902             : 
    1903             : static void
    1904             : after_credit( fd_replay_tile_t *  ctx,
    1905             :               fd_stem_context_t * stem,
    1906             :               int *               opt_poll_in,
    1907           0 :               int *               charge_busy ) {
    1908           0 :   if( FD_UNLIKELY( !ctx->is_booted ) ) return;
    1909             : 
    1910           0 :   if( FD_UNLIKELY( maybe_become_leader( ctx, stem ) ) ) {
    1911           0 :     *charge_busy = 1;
    1912           0 :     *opt_poll_in = 0;
    1913           0 :     return;
    1914           0 :   }
    1915             : 
    1916             :   /* If we are leader, we can only unbecome the leader iff we have
    1917             :      received the poh hash from the poh tile and block id from reasm. */
    1918           0 :   if( FD_UNLIKELY( ctx->is_leader && ctx->recv_poh && ctx->block_id_arr[ ctx->leader_bank->data->idx ].block_id_seen ) ) {
    1919           0 :     fini_leader_bank( ctx, stem );
    1920           0 :     *charge_busy = 1;
    1921           0 :     *opt_poll_in = 0;
    1922           0 :     return;
    1923           0 :   }
    1924             : 
    1925             :   /* If the published_root is not caught up to the consensus root, then
    1926             :      we should try to advance the published root. */
    1927           0 :   if( FD_UNLIKELY( ctx->consensus_root_bank_idx!=ctx->published_root_bank_idx && advance_published_root( ctx ) ) ) {
    1928           0 :     *charge_busy = 1;
    1929           0 :     *opt_poll_in = 0;
    1930           0 :     return;
    1931           0 :   }
    1932             : 
    1933             :   /* If the reassembler has a fec that is ready, we should process it
    1934             :      and pass it to the scheduler. */
    1935             : 
    1936             :   /* FIXME: The reasm logic needs to get reworked to support
    1937             :      equivocation more robustly. */
    1938           0 :   if( FD_LIKELY( can_process_fec( ctx ) ) ) {
    1939           0 :     fd_reasm_fec_t * fec = fd_reasm_peek( ctx->reasm );
    1940             : 
    1941             :     /* If fec->eqvoc is set that means that equivocation mid-block was
    1942             :        detected in fd_reasm_t.  We need to replay up to and including
    1943             :        the equivocating FEC on a new bank. */
    1944             : 
    1945           0 :     if( FD_UNLIKELY( fec->eqvoc ) ) {
    1946           0 :       FD_LOG_WARNING(( "Block equivocation detected at slot %lu", fec->slot ));
    1947             : 
    1948             :       /* We need to figure out which and how many FECs we need to
    1949             :          (re)insert into the scheduler.  We work backwards from the
    1950             :          equivocating FEC, querying for chained merkle roots until we
    1951             :          reach the first FEC in the slot.
    1952             :          TODO: replace the magic number with a constant for the max
    1953             :                number of fecs possible in a slot with fix-32. */
    1954           0 :       fd_reasm_fec_t * fecs[ 1024 ] = { [0] = fec };
    1955           0 :       ulong            fec_cnt      = 1UL;
    1956           0 :       while( fecs[ fec_cnt-1UL ]->fec_set_idx!=0UL ) {
    1957           0 :         fec = fd_reasm_query( ctx->reasm, &fecs[ fec_cnt-1UL ]->cmr );
    1958           0 :         fecs[ fec_cnt++ ] = fec;
    1959           0 :       }
    1960             : 
    1961             :       /* If we don't have enough space in the scheduler to ingest all of
    1962             :          FECs, we can't proceed yet. */
    1963           0 :       if( FD_UNLIKELY( !fd_sched_can_ingest( ctx->sched, fec_cnt ) ) ) return;
    1964             : 
    1965             :       /* Now that we have validated that sched can ingest all of the
    1966             :          required FECs, it is finally safe to remove the equivocating
    1967             :          fec from the reasm deque. */
    1968           0 :       fd_reasm_out( ctx->reasm );
    1969             : 
    1970             :       /* Now we can process all of the FECs. */
    1971           0 :       for( ulong i=fec_cnt; i>0UL; i-- ) {
    1972           0 :         process_fec_set( ctx, stem, fecs[i-1UL] );
    1973           0 :       }
    1974           0 :     } else {
    1975             :       /* Standard case. */
    1976           0 :       fec = fd_reasm_out( ctx->reasm );
    1977           0 :       process_fec_set( ctx, stem, fec );
    1978           0 :     }
    1979             : 
    1980           0 :     *charge_busy = 1;
    1981           0 :     *opt_poll_in = 0;
    1982           0 :     return;
    1983           0 :   }
    1984             : 
    1985           0 :   *charge_busy = replay( ctx, stem );
    1986           0 :   *opt_poll_in = !*charge_busy;
    1987           0 : }
    1988             : 
    1989             : static int
    1990             : before_frag( fd_replay_tile_t * ctx,
    1991             :              ulong              in_idx,
    1992             :              ulong              seq FD_PARAM_UNUSED,
    1993           0 :              ulong              sig FD_PARAM_UNUSED ) {
    1994             : 
    1995           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_SHRED ) ) {
    1996             :     /* If reasm is full, we can not insert any more FEC sets.  We must
    1997             :        not consume any frags from shred_out until reasm can process more
    1998             :        FEC sets. */
    1999             : 
    2000           0 :     if( FD_UNLIKELY( !fd_reasm_free( ctx->reasm ) ) ) {
    2001           0 :       return -1;
    2002           0 :     }
    2003           0 :   }
    2004             : 
    2005           0 :   return 0;
    2006           0 : }
    2007             : 
    2008             : static void
    2009             : process_exec_task_done( fd_replay_tile_t *        ctx,
    2010             :                         fd_stem_context_t *       stem,
    2011             :                         fd_exec_task_done_msg_t * msg,
    2012           0 :                         ulong                     sig ) {
    2013             : 
    2014           0 :   ulong exec_tile_idx = sig&0xFFFFFFFFUL;
    2015             : 
    2016           0 :   fd_bank_t bank[1];
    2017           0 :   FD_TEST( fd_banks_bank_query( bank, ctx->banks, msg->bank_idx ) );
    2018           0 :   FD_TEST( bank->data );
    2019           0 :   bank->data->refcnt--;
    2020             : 
    2021           0 :   switch( sig>>32 ) {
    2022           0 :     case FD_EXEC_TT_TXN_EXEC: {
    2023           0 :       if( FD_UNLIKELY( !ctx->has_identity_vote_rooted ) ) {
    2024             :         /* Query the txn signature against our recently generated vote
    2025             :            txn signatures.  If the query is successful, then we have
    2026             :            seen our own vote transaction land and this should be marked
    2027             :            in the bank.  We go through this exercise until we've seen
    2028             :            our vote rooted. */
    2029           0 :         fd_txn_p_t * txn_p = fd_sched_get_txn( ctx->sched, msg->txn_exec->txn_idx );
    2030           0 :         if( fd_vote_tracker_query_sig( ctx->vote_tracker, fd_type_pun_const( txn_p->payload+TXN( txn_p )->signature_off ) ) ) {
    2031           0 :           *fd_bank_has_identity_vote_modify( bank ) += 1;
    2032           0 :         }
    2033           0 :       }
    2034           0 :       if( FD_UNLIKELY( msg->txn_exec->err && !(bank->data->flags&FD_BANK_FLAGS_DEAD) ) ) {
    2035             :         /* Every transaction in a valid block has to execute.
    2036             :            Otherwise, we should mark the block as dead. */
    2037           0 :         fd_banks_mark_bank_dead( ctx->banks, bank );
    2038           0 :         fd_sched_block_abandon( ctx->sched, bank->data->idx );
    2039             : 
    2040             :         /* We can only publish the slot as dead if we have seen the
    2041             :            block id for this slot. */
    2042           0 :         if( ctx->block_id_arr[ bank->data->idx ].block_id_seen ) {
    2043           0 :           publish_slot_dead( ctx, stem, bank );
    2044           0 :         }
    2045           0 :       }
    2046           0 :       if( FD_UNLIKELY( (bank->data->flags&FD_BANK_FLAGS_DEAD) && bank->data->refcnt==0UL ) ) {
    2047           0 :         fd_banks_mark_bank_frozen( ctx->banks, bank );
    2048           0 :       }
    2049           0 :       fd_sched_task_done( ctx->sched, FD_SCHED_TT_TXN_EXEC, msg->txn_exec->txn_idx, exec_tile_idx );
    2050           0 :       break;
    2051           0 :     }
    2052           0 :     case FD_EXEC_TT_TXN_SIGVERIFY: {
    2053           0 :       if( FD_UNLIKELY( msg->txn_sigverify->err && !(bank->data->flags&FD_BANK_FLAGS_DEAD) ) ) {
    2054             :         /* Every transaction in a valid block has to sigverify.
    2055             :            Otherwise, we should mark the block as dead.  Also freeze the
    2056             :            bank if possible. */
    2057           0 :         fd_banks_mark_bank_dead( ctx->banks, bank );
    2058           0 :         fd_sched_block_abandon( ctx->sched, bank->data->idx );
    2059             : 
    2060             :         /* We can only publish the slot as dead if we have seen the
    2061             :            block id for this slot. */
    2062           0 :         if( ctx->block_id_arr[ bank->data->idx ].block_id_seen ) {
    2063           0 :           publish_slot_dead( ctx, stem, bank );
    2064           0 :         }
    2065           0 :       }
    2066           0 :       if( FD_UNLIKELY( (bank->data->flags&FD_BANK_FLAGS_DEAD) && bank->data->refcnt==0UL ) ) {
    2067           0 :         fd_banks_mark_bank_frozen( ctx->banks, bank );
    2068           0 :       }
    2069           0 :       fd_sched_task_done( ctx->sched, FD_SCHED_TT_TXN_SIGVERIFY, msg->txn_sigverify->txn_idx, exec_tile_idx );
    2070           0 :       break;
    2071           0 :     }
    2072           0 :     default: FD_LOG_CRIT(( "unexpected sig 0x%lx", sig ));
    2073           0 :   }
    2074             : 
    2075             :   /* Reference counter just decreased, and an exec tile just got freed
    2076             :      up.  If there's a need to be more aggressively pruning, we could
    2077             :      check here if more slots just became publishable and publish.  Not
    2078             :      publishing here shouldn't bloat the fork tree too much though.  We
    2079             :      mark minority forks dead as soon as we can, and execution dispatch
    2080             :      stops on dead blocks.  So shortly afterwards, dead blocks should be
    2081             :      eligible for pruning as in-flight transactions retire from the
    2082             :      execution pipeline. */
    2083             : 
    2084           0 : }
    2085             : 
    2086             : static void
    2087             : process_tower_slot_done( fd_replay_tile_t *           ctx,
    2088             :                          fd_stem_context_t *          stem,
    2089             :                          fd_tower_slot_done_t const * msg,
    2090           0 :                          ulong                        seq ) {
    2091           0 :   fd_bank_t replay_bank[1];
    2092           0 :   if( FD_UNLIKELY( !fd_banks_bank_query( replay_bank, ctx->banks, msg->replay_bank_idx ) ) ) FD_LOG_CRIT(( "invariant violation: bank not found for bank index %lu", msg->replay_bank_idx ));
    2093           0 :   replay_bank->data->refcnt--;
    2094           0 :   FD_LOG_DEBUG(( "bank (idx=%lu, slot=%lu) refcnt decremented to %lu", replay_bank->data->idx, msg->replay_slot, replay_bank->data->refcnt ));
    2095             : 
    2096           0 :   ctx->reset_block_id = msg->reset_block_id;
    2097           0 :   ctx->reset_slot     = msg->reset_slot;
    2098           0 :   ctx->reset_timestamp_nanos = fd_log_wallclock();
    2099           0 :   ulong min_leader_slot = fd_ulong_max( msg->reset_slot+1UL, fd_ulong_if( ctx->highwater_leader_slot==ULONG_MAX, 0UL, ctx->highwater_leader_slot+1UL ) );
    2100           0 :   ctx->next_leader_slot = fd_multi_epoch_leaders_get_next_slot( ctx->mleaders, min_leader_slot, ctx->identity_pubkey );
    2101           0 :   if( FD_LIKELY( ctx->next_leader_slot != ULONG_MAX ) ) {
    2102           0 :     ctx->next_leader_tickcount = (long)((double)(ctx->next_leader_slot-ctx->reset_slot-1UL)*ctx->slot_duration_ticks) + fd_tickcount();
    2103           0 :   } else {
    2104           0 :     ctx->next_leader_tickcount = LONG_MAX;
    2105           0 :   }
    2106             : 
    2107           0 :   fd_block_id_ele_t * block_id_ele = fd_block_id_map_ele_query( ctx->block_id_map, &msg->reset_block_id, NULL, ctx->block_id_arr );
    2108           0 :   if( FD_UNLIKELY( !block_id_ele ) ) {
    2109           0 :     FD_BASE58_ENCODE_32_BYTES( msg->reset_block_id.key, reset_block_id_b58 );
    2110           0 :     FD_LOG_CRIT(( "invariant violation: block id ele doesn't exist for reset block id: %s, slot: %lu", reset_block_id_b58, msg->reset_slot ));
    2111           0 :   }
    2112           0 :   ulong reset_bank_idx = fd_block_id_ele_get_idx( ctx->block_id_arr, block_id_ele );
    2113             : 
    2114           0 :   fd_bank_t bank[1];
    2115           0 :   if( FD_UNLIKELY( !fd_banks_bank_query( bank, ctx->banks, reset_bank_idx ) ) ) {
    2116           0 :     FD_LOG_CRIT(( "invariant violation: bank not found for bank index %lu", reset_bank_idx ));
    2117           0 :   }
    2118             : 
    2119           0 :   if( FD_LIKELY( msg->root_slot!=ULONG_MAX ) ) FD_TEST( msg->root_slot<=msg->reset_slot );
    2120           0 :   fd_memcpy( ctx->reset_bank, bank, sizeof(fd_bank_t) );
    2121             : 
    2122           0 :   if( FD_LIKELY( ctx->replay_out->idx!=ULONG_MAX ) ) {
    2123           0 :     fd_poh_reset_t * reset = fd_chunk_to_laddr( ctx->replay_out->mem, ctx->replay_out->chunk );
    2124             : 
    2125           0 :     reset->bank_idx = bank->data->idx;
    2126           0 :     reset->timestamp = ctx->reset_timestamp_nanos;
    2127           0 :     reset->completed_slot = ctx->reset_slot;
    2128           0 :     reset->hashcnt_per_tick = fd_bank_hashes_per_tick_get( bank );
    2129           0 :     reset->ticks_per_slot = fd_bank_ticks_per_slot_get( bank );
    2130           0 :     reset->tick_duration_ns = (ulong)(ctx->slot_duration_nanos/(double)reset->ticks_per_slot);
    2131             : 
    2132           0 :     fd_memcpy( reset->completed_block_id, &block_id_ele->block_id, sizeof(fd_hash_t) );
    2133             : 
    2134           0 :     fd_blockhashes_t const * block_hash_queue = fd_bank_block_hash_queue_query( bank );
    2135           0 :     fd_hash_t const * last_hash = fd_blockhashes_peek_last_hash( block_hash_queue );
    2136           0 :     FD_TEST( last_hash );
    2137           0 :     fd_memcpy( reset->completed_blockhash, last_hash->uc, sizeof(fd_hash_t) );
    2138             : 
    2139           0 :     ulong ticks_per_slot = fd_bank_ticks_per_slot_get( bank );
    2140           0 :     if( FD_UNLIKELY( reset->hashcnt_per_tick==1UL ) ) {
    2141             :       /* Low power producer, maximum of one microblock per tick in the slot */
    2142           0 :       reset->max_microblocks_in_slot = ticks_per_slot;
    2143           0 :     } else {
    2144             :       /* See the long comment in after_credit for this limit */
    2145           0 :       reset->max_microblocks_in_slot = fd_ulong_min( MAX_MICROBLOCKS_PER_SLOT, ticks_per_slot*(reset->hashcnt_per_tick-1UL) );
    2146           0 :     }
    2147           0 :     reset->next_leader_slot = ctx->next_leader_slot;
    2148             : 
    2149           0 :     if( FD_LIKELY( ctx->rpc_enabled ) ) bank->data->refcnt++;
    2150           0 :     FD_LOG_DEBUG(( "bank (idx=%lu, slot=%lu) refcnt incremented to %lu", bank->data->idx, msg->reset_slot, bank->data->refcnt ));
    2151             : 
    2152           0 :     fd_stem_publish( stem, ctx->replay_out->idx, REPLAY_SIG_RESET, ctx->replay_out->chunk, sizeof(fd_poh_reset_t), 0UL, 0UL, fd_frag_meta_ts_comp( fd_tickcount() ) );
    2153           0 :     ctx->replay_out->chunk = fd_dcache_compact_next( ctx->replay_out->chunk, sizeof(fd_poh_reset_t), ctx->replay_out->chunk0, ctx->replay_out->wmark );
    2154           0 :   }
    2155             : 
    2156           0 :   FD_LOG_INFO(( "tower_slot_done(reset_slot=%lu, next_leader_slot=%lu, vote_slot=%lu, replay_slot=%lu, seqno=%lu)", msg->reset_slot, ctx->next_leader_slot, msg->vote_slot, msg->replay_slot, seq ));
    2157           0 :   maybe_become_leader( ctx, stem );
    2158             : 
    2159           0 :   if( FD_LIKELY( msg->root_slot!=ULONG_MAX ) ) {
    2160             : 
    2161           0 :     FD_TEST( msg->root_slot>=ctx->consensus_root_slot );
    2162           0 :     fd_block_id_ele_t * block_id_ele = fd_block_id_map_ele_query( ctx->block_id_map, &msg->root_block_id, NULL, ctx->block_id_arr );
    2163           0 :     FD_TEST( block_id_ele );
    2164             : 
    2165           0 :     ctx->consensus_root_slot     = msg->root_slot;
    2166           0 :     ctx->consensus_root          = msg->root_block_id;
    2167           0 :     ctx->consensus_root_bank_idx = fd_block_id_ele_get_idx( ctx->block_id_arr, block_id_ele );
    2168             : 
    2169           0 :     publish_root_advanced( ctx, stem );
    2170           0 :   }
    2171             : 
    2172           0 :   ulong distance = 0UL;
    2173           0 :   fd_bank_t * parent = bank;
    2174           0 :   while( parent ) {
    2175           0 :     if( FD_UNLIKELY( parent->data->idx==ctx->consensus_root_bank_idx ) ) break;
    2176           0 :     parent = fd_banks_get_parent( bank, ctx->banks, parent );
    2177           0 :     distance++;
    2178           0 :   }
    2179             : 
    2180           0 :   FD_MGAUGE_SET( REPLAY, ROOT_DISTANCE, distance );
    2181           0 : }
    2182             : 
    2183             : static void
    2184             : process_fec_complete( fd_replay_tile_t * ctx,
    2185           0 :                       uchar const *      shred_buf ) {
    2186           0 :   fd_shred_t const * shred = (fd_shred_t const *)fd_type_pun_const( shred_buf );
    2187             : 
    2188           0 :   fd_hash_t const * merkle_root         = (fd_hash_t const *)fd_type_pun_const( shred_buf + FD_SHRED_DATA_HEADER_SZ );
    2189           0 :   fd_hash_t const * chained_merkle_root = (fd_hash_t const *)fd_type_pun_const( shred_buf + FD_SHRED_DATA_HEADER_SZ + sizeof(fd_hash_t) );
    2190           0 :   int               is_leader_fec       = *(int const *)     fd_type_pun_const( shred_buf + FD_SHRED_DATA_HEADER_SZ + sizeof(fd_hash_t) + sizeof(fd_hash_t) );
    2191             : 
    2192           0 :   int data_complete = !!( shred->data.flags & FD_SHRED_DATA_FLAG_DATA_COMPLETE );
    2193           0 :   int slot_complete = !!( shred->data.flags & FD_SHRED_DATA_FLAG_SLOT_COMPLETE );
    2194             : 
    2195           0 :   FD_TEST( !fd_reasm_query( ctx->reasm, merkle_root ) );
    2196           0 :   if( FD_UNLIKELY( shred->slot - shred->data.parent_off == fd_reasm_slot0( ctx->reasm ) && shred->fec_set_idx == 0) ) {
    2197           0 :     chained_merkle_root = &fd_reasm_root( ctx->reasm )->key;
    2198           0 :   }
    2199             : 
    2200           0 :   FD_TEST( fd_reasm_free( ctx->reasm ) );
    2201             : 
    2202           0 :   FD_TEST( fd_reasm_insert( ctx->reasm, merkle_root, chained_merkle_root, shred->slot, shred->fec_set_idx, shred->data.parent_off, (ushort)(shred->idx - shred->fec_set_idx + 1), data_complete, slot_complete, is_leader_fec ) );
    2203           0 : }
    2204             : 
    2205             : static void
    2206           0 : process_resolv_slot_completed( fd_replay_tile_t * ctx, ulong bank_idx ) {
    2207           0 :   fd_bank_t bank[1];
    2208           0 :   FD_TEST( fd_banks_bank_query( bank, ctx->banks, bank_idx ) );
    2209             : 
    2210           0 :   bank->data->refcnt--;
    2211           0 :   FD_LOG_DEBUG(( "bank (idx=%lu, slot=%lu) refcnt decremented to %lu", bank->data->idx, fd_bank_slot_get( bank ), bank->data->refcnt ));
    2212           0 : }
    2213             : 
    2214             : static void
    2215             : process_vote_txn_sent( fd_replay_tile_t *  ctx,
    2216           0 :                        fd_txn_m_t *        txnm ) {
    2217             :   /* The send tile has signed and sent a vote.  Add this vote to the
    2218             :      vote tracker.  We go through this exercise until we've seen our
    2219             :      vote rooted. */
    2220           0 :   if( FD_UNLIKELY( !ctx->has_identity_vote_rooted ) ) {
    2221           0 :     uchar *    payload = ((uchar *)txnm) + sizeof(fd_txn_m_t);
    2222           0 :     uchar      txn_mem[ FD_TXN_MAX_SZ ] __attribute__((aligned(alignof(fd_txn_t))));
    2223           0 :     fd_txn_t * txn = (fd_txn_t *)txn_mem;
    2224           0 :     if( FD_UNLIKELY( !fd_txn_parse( payload, txnm->payload_sz, txn_mem, NULL ) ) ) {
    2225           0 :       FD_LOG_CRIT(( "Could not parse txn from send tile" ));
    2226           0 :     }
    2227           0 :     fd_vote_tracker_insert( ctx->vote_tracker, fd_type_pun_const( payload+txn->signature_off ) );
    2228           0 :   }
    2229           0 : }
    2230             : 
    2231             : static inline void
    2232           0 : maybe_verify_shred_version( fd_replay_tile_t * ctx ) {
    2233           0 :   if( FD_LIKELY( ctx->expected_shred_version && ctx->ipecho_shred_version ) ) {
    2234           0 :     if( FD_UNLIKELY( ctx->expected_shred_version!=ctx->ipecho_shred_version ) ) {
    2235           0 :       FD_LOG_ERR(( "shred version mismatch: expected %u but got %u from ipecho", ctx->expected_shred_version, ctx->ipecho_shred_version ) );
    2236           0 :     }
    2237           0 :   }
    2238             : 
    2239           0 :   if( FD_LIKELY( ctx->has_genesis_hash && ctx->hard_forks_cnt!=ULONG_MAX && (ctx->expected_shred_version || ctx->ipecho_shred_version) ) ) {
    2240           0 :     ushort expected_shred_version = ctx->expected_shred_version ? ctx->expected_shred_version : ctx->ipecho_shred_version;
    2241             : 
    2242           0 :     union {
    2243           0 :       uchar  c[ 32 ];
    2244           0 :       ushort s[ 16 ];
    2245           0 :     } running_hash;
    2246           0 :     fd_memcpy( running_hash.c, ctx->genesis_hash, sizeof(fd_hash_t) );
    2247             : 
    2248           0 :     ulong processed = 0UL;
    2249           0 :     ulong min_value = 0UL;
    2250           0 :     while( processed<ctx->hard_forks_cnt ) {
    2251           0 :       ulong min_index = ULONG_MAX;
    2252           0 :       for( ulong i=0UL; i<ctx->hard_forks_cnt; i++ ) {
    2253           0 :         if( ctx->hard_forks[ i ]>=min_value && (min_index==ULONG_MAX || ctx->hard_forks[ i ]<ctx->hard_forks[ min_index ] ) ) {
    2254           0 :           min_index = i;
    2255           0 :         }
    2256           0 :       }
    2257             : 
    2258           0 :       FD_TEST( min_index!=ULONG_MAX );
    2259           0 :       min_value = ctx->hard_forks[ min_index ];
    2260           0 :       ulong min_count = 0UL;
    2261           0 :       for( ulong i=0UL; i<ctx->hard_forks_cnt; i++ ) {
    2262           0 :         if( ctx->hard_forks[ i ]==min_value ) min_count++;
    2263           0 :       }
    2264             : 
    2265           0 :       uchar data[ 48UL ];
    2266           0 :       fd_memcpy( data, running_hash.c, sizeof(fd_hash_t) );
    2267           0 :       fd_memcpy( data+32UL, &min_value, sizeof(ulong) );
    2268           0 :       fd_memcpy( data+40UL, &min_count, sizeof(ulong) );
    2269             : 
    2270           0 :       FD_TEST( fd_sha256_hash( data, 48UL, running_hash.c ) );
    2271           0 :       processed += min_count;
    2272           0 :       min_value += 1UL;
    2273           0 :     }
    2274             : 
    2275           0 :     ushort xor = 0;
    2276           0 :     for( ulong i=0UL; i<16UL; i++ ) xor ^= running_hash.s[ i ];
    2277             : 
    2278           0 :     xor = fd_ushort_bswap( xor );
    2279           0 :     xor = fd_ushort_if( xor<USHORT_MAX, (ushort)(xor + 1), USHORT_MAX );
    2280             : 
    2281           0 :     if( FD_UNLIKELY( expected_shred_version!=xor ) ) {
    2282           0 :       FD_BASE58_ENCODE_32_BYTES( ctx->genesis_hash, genesis_hash_b58 );
    2283           0 :       FD_LOG_ERR(( "shred version mismatch: expected %u but got %u from genesis hash %s and hard forks", expected_shred_version, xor, genesis_hash_b58 ));
    2284           0 :     }
    2285           0 :   }
    2286           0 : }
    2287             : 
    2288             : static inline int
    2289             : returnable_frag( fd_replay_tile_t *  ctx,
    2290             :                  ulong               in_idx,
    2291             :                  ulong               seq,
    2292             :                  ulong               sig,
    2293             :                  ulong               chunk,
    2294             :                  ulong               sz,
    2295             :                  ulong               ctl,
    2296             :                  ulong               tsorig,
    2297             :                  ulong               tspub,
    2298           0 :                  fd_stem_context_t * stem ) {
    2299           0 :   (void)seq;
    2300           0 :   (void)ctl;
    2301           0 :   (void)tsorig;
    2302           0 :   (void)tspub;
    2303             : 
    2304           0 :   if( FD_UNLIKELY( sz!=0UL && (chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz>ctx->in[ in_idx ].mtu ) ) )
    2305           0 :     FD_LOG_ERR(( "chunk %lu %lu from in %d corrupt, not in range [%lu,%lu]", chunk, sz, ctx->in_kind[ in_idx ], ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark ));
    2306             : 
    2307           0 :   switch( ctx->in_kind[in_idx] ) {
    2308           0 :     case IN_KIND_GENESIS: {
    2309           0 :       uchar const * src = fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk );
    2310           0 :       ctx->has_genesis_hash = 1;
    2311           0 :       if( FD_LIKELY( sig==GENESI_SIG_BOOTSTRAP_COMPLETED ) ) {
    2312           0 :         boot_genesis( ctx, stem, in_idx, chunk );
    2313           0 :         fd_memcpy( ctx->genesis_hash, src+sizeof(fd_lthash_value_t), sizeof(fd_hash_t) );
    2314           0 :       } else {
    2315           0 :         fd_memcpy( ctx->genesis_hash, src, sizeof(fd_hash_t) );
    2316           0 :       }
    2317             : 
    2318           0 :       maybe_verify_cluster_type( ctx );
    2319           0 :       maybe_verify_shred_version( ctx );
    2320           0 :       break;
    2321           0 :     }
    2322           0 :     case IN_KIND_IPECHO: {
    2323           0 :       FD_TEST( sig && sig<=USHORT_MAX );
    2324           0 :       ctx->ipecho_shred_version = (ushort)sig;
    2325           0 :       maybe_verify_shred_version( ctx );
    2326           0 :       break;
    2327           0 :     }
    2328           0 :     case IN_KIND_SNAP:
    2329           0 :       on_snapshot_message( ctx, stem, in_idx, chunk, sig );
    2330           0 :       maybe_verify_shred_version( ctx );
    2331           0 :       break;
    2332           0 :     case IN_KIND_EXEC: {
    2333           0 :       process_exec_task_done( ctx, stem, fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk ), sig );
    2334           0 :       break;
    2335           0 :     }
    2336           0 :     case IN_KIND_POH: {
    2337           0 :       process_poh_message( ctx, fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk ) );
    2338           0 :       break;
    2339           0 :     }
    2340           0 :     case IN_KIND_RESOLV: {
    2341           0 :       fd_resolv_slot_exchanged_t * exchanged_slot = fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk );
    2342           0 :       process_resolv_slot_completed( ctx, exchanged_slot->bank_idx );
    2343           0 :       break;
    2344           0 :     }
    2345           0 :     case IN_KIND_TOWER: {
    2346           0 :       if     ( FD_LIKELY( sig==FD_TOWER_SIG_SLOT_DONE      ) ) process_tower_slot_done( ctx, stem, fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk ), seq );
    2347           0 :       else if( FD_LIKELY( sig==FD_TOWER_SIG_SLOT_CONFIRMED ) ) {
    2348           0 :         fd_tower_slot_confirmed_t const * msg = fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk );
    2349             : 
    2350             :         /* Implement replay plugin API here */
    2351             : 
    2352           0 :         switch( msg->kind ) {
    2353           0 :         case FD_TOWER_SLOT_CONFIRMED_OPTIMISTIC: break;
    2354           0 :         case FD_TOWER_SLOT_CONFIRMED_ROOTED:     break;
    2355           0 :         }
    2356           0 :       }
    2357           0 :       else if( FD_LIKELY( sig==FD_TOWER_SIG_SLOT_IGNORED   ) ) {
    2358           0 :         fd_tower_slot_ignored_t const * msg = fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk );
    2359           0 :         fd_tower_slot_done_t ignored = {
    2360           0 :           .replay_slot     = msg->slot,
    2361           0 :           .replay_bank_idx = msg->bank_idx,
    2362           0 :           .vote_slot       = ULONG_MAX,
    2363           0 :           .reset_slot      = ctx->reset_slot,     /* Use most recent reset slot */
    2364           0 :           .reset_block_id  = ctx->reset_block_id,
    2365           0 :           .root_slot       = ULONG_MAX
    2366           0 :         };
    2367           0 :         process_tower_slot_done( ctx, stem, &ignored, seq );
    2368           0 :       }
    2369           0 :       break;
    2370           0 :     }
    2371           0 :     case IN_KIND_SHRED: {
    2372             :       /* TODO: This message/sz should be defined. */
    2373           0 :       if( sz==FD_SHRED_DATA_HEADER_SZ + sizeof(fd_hash_t) + sizeof(fd_hash_t) + sizeof(int) ) {
    2374             :         /* If receive a FEC complete message. */
    2375           0 :         process_fec_complete( ctx, fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk ) );
    2376           0 :       }
    2377           0 :       break;
    2378           0 :     }
    2379           0 :     case IN_KIND_VTXN: {
    2380           0 :       process_vote_txn_sent( ctx, fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk ) );
    2381           0 :       break;
    2382           0 :     }
    2383           0 :     case IN_KIND_RPC:
    2384           0 :     case IN_KIND_GUI: {
    2385           0 :       fd_bank_t bank[1];
    2386           0 :       FD_TEST( fd_banks_bank_query( bank, ctx->banks, sig ) );
    2387           0 :       bank->data->refcnt--;
    2388           0 :       FD_LOG_DEBUG(( "bank (idx=%lu, slot=%lu) refcnt decremented to %lu", bank->data->idx, fd_bank_slot_get( bank ), bank->data->refcnt ));
    2389           0 :       break;
    2390           0 :     }
    2391           0 :     default:
    2392           0 :       FD_LOG_ERR(( "unhandled kind %d", ctx->in_kind[ in_idx ] ));
    2393           0 :   }
    2394             : 
    2395           0 :   return 0;
    2396           0 : }
    2397             : 
    2398             : static inline fd_replay_out_link_t
    2399             : out1( fd_topo_t const *      topo,
    2400             :       fd_topo_tile_t const * tile,
    2401           0 :       char const *           name ) {
    2402           0 :   ulong idx = ULONG_MAX;
    2403             : 
    2404           0 :   for( ulong i=0UL; i<tile->out_cnt; i++ ) {
    2405           0 :     fd_topo_link_t const * link = &topo->links[ tile->out_link_id[ i ] ];
    2406           0 :     if( !strcmp( link->name, name ) ) {
    2407           0 :       if( FD_UNLIKELY( idx!=ULONG_MAX ) ) FD_LOG_ERR(( "tile %s:%lu had multiple output links named %s but expected one", tile->name, tile->kind_id, name ));
    2408           0 :       idx = i;
    2409           0 :     }
    2410           0 :   }
    2411             : 
    2412           0 :   if( FD_UNLIKELY( idx==ULONG_MAX ) ) return (fd_replay_out_link_t){ .idx = ULONG_MAX, .mem = NULL, .chunk0 = 0, .wmark = 0, .chunk = 0 };
    2413             : 
    2414           0 :   void * mem = topo->workspaces[ topo->objs[ topo->links[ tile->out_link_id[ idx ] ].dcache_obj_id ].wksp_id ].wksp;
    2415           0 :   ulong chunk0 = fd_dcache_compact_chunk0( mem, topo->links[ tile->out_link_id[ idx ] ].dcache );
    2416           0 :   ulong wmark  = fd_dcache_compact_wmark ( mem, topo->links[ tile->out_link_id[ idx ] ].dcache, topo->links[ tile->out_link_id[ idx ] ].mtu );
    2417             : 
    2418           0 :   return (fd_replay_out_link_t){ .idx = idx, .mem = mem, .chunk0 = chunk0, .wmark = wmark, .chunk = chunk0 };
    2419           0 : }
    2420             : 
    2421             : static void
    2422             : privileged_init( fd_topo_t *      topo,
    2423           0 :                  fd_topo_tile_t * tile ) {
    2424           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    2425             : 
    2426           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    2427           0 :   fd_replay_tile_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_replay_tile_t), sizeof(fd_replay_tile_t) );
    2428             : 
    2429           0 :   if( FD_UNLIKELY( !strcmp( tile->replay.identity_key_path, "" ) ) ) FD_LOG_ERR(( "identity_key_path not set" ));
    2430             : 
    2431           0 :   ctx->identity_pubkey[ 0 ] = *(fd_pubkey_t const *)fd_type_pun_const( fd_keyload_load( tile->replay.identity_key_path, /* pubkey only: */ 1 ) );
    2432             : 
    2433           0 :   if( FD_UNLIKELY( !tile->replay.bundle.vote_account_path[0] ) ) {
    2434           0 :     tile->replay.bundle.enabled = 0;
    2435           0 :   }
    2436             : 
    2437           0 :   if( FD_UNLIKELY( tile->replay.bundle.enabled ) ) {
    2438           0 :     if( FD_UNLIKELY( !fd_base58_decode_32( tile->replay.bundle.vote_account_path, ctx->bundle.vote_account.uc ) ) ) {
    2439           0 :       const uchar * vote_key = fd_keyload_load( tile->replay.bundle.vote_account_path, /* pubkey only: */ 1 );
    2440           0 :       fd_memcpy( ctx->bundle.vote_account.uc, vote_key, 32UL );
    2441           0 :     }
    2442           0 :   }
    2443             : 
    2444           0 :   if( FD_UNLIKELY( !fd_rng_secure( &ctx->reasm_seed, sizeof(ulong) ) ) ) {
    2445           0 :     FD_LOG_CRIT(( "fd_rng_secure failed" ));
    2446           0 :   }
    2447             : 
    2448           0 :   if( FD_UNLIKELY( !fd_rng_secure( &ctx->vote_tracker_seed, sizeof(ulong) ) ) ) {
    2449           0 :     FD_LOG_CRIT(( "fd_rng_secure failed" ));
    2450           0 :   }
    2451             : 
    2452           0 :   if( FD_UNLIKELY( !fd_rng_secure( &ctx->block_id_map_seed, sizeof(ulong) ) ) ) {
    2453           0 :     FD_LOG_CRIT(( "fd_rng_secure failed" ));
    2454           0 :   }
    2455           0 : }
    2456             : 
    2457             : static void
    2458             : unprivileged_init( fd_topo_t *      topo,
    2459           0 :                    fd_topo_tile_t * tile ) {
    2460           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    2461             : 
    2462           0 :   ulong chain_cnt = fd_block_id_map_chain_cnt_est( tile->replay.max_live_slots );
    2463             : 
    2464           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    2465           0 :   fd_replay_tile_t * ctx    = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_replay_tile_t),   sizeof(fd_replay_tile_t) );
    2466           0 :   void * block_id_arr_mem   = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_block_id_ele_t),  sizeof(fd_block_id_ele_t) * tile->replay.max_live_slots );
    2467           0 :   void * block_id_map_mem   = FD_SCRATCH_ALLOC_APPEND( l, fd_block_id_map_align(),     fd_block_id_map_footprint( chain_cnt ) );
    2468           0 :   void * _txncache          = FD_SCRATCH_ALLOC_APPEND( l, fd_txncache_align(),         fd_txncache_footprint( tile->replay.max_live_slots ) );
    2469           0 :   void * reasm_mem          = FD_SCRATCH_ALLOC_APPEND( l, fd_reasm_align(),            fd_reasm_footprint( tile->replay.fec_max ) );
    2470           0 :   void * sched_mem          = FD_SCRATCH_ALLOC_APPEND( l, fd_sched_align(),            fd_sched_footprint( tile->replay.max_live_slots ) );
    2471           0 :   void * vinyl_req_pool_mem = FD_SCRATCH_ALLOC_APPEND( l, fd_vinyl_req_pool_align(),   fd_vinyl_req_pool_footprint( 1UL, 1UL ) );
    2472           0 :   void * vote_tracker_mem   = FD_SCRATCH_ALLOC_APPEND( l, fd_vote_tracker_align(),     fd_vote_tracker_footprint() );
    2473           0 :   void * _capture_ctx       = FD_SCRATCH_ALLOC_APPEND( l, fd_capture_ctx_align(),      fd_capture_ctx_footprint() );
    2474           0 : # if FD_HAS_FLATCC
    2475           0 :   void * block_dump_ctx     = NULL;
    2476           0 :   if( FD_UNLIKELY( tile->replay.dump_block_to_pb ) ) {
    2477           0 :     block_dump_ctx = FD_SCRATCH_ALLOC_APPEND( l, fd_block_dump_context_align(), fd_block_dump_context_footprint() );
    2478           0 :   }
    2479           0 : # endif
    2480             : 
    2481           0 :   ulong store_obj_id = fd_pod_query_ulong( topo->props, "store", ULONG_MAX );
    2482           0 :   FD_TEST( store_obj_id!=ULONG_MAX );
    2483           0 :   ctx->store = fd_store_join( fd_topo_obj_laddr( topo, store_obj_id ) );
    2484           0 :   FD_TEST( ctx->store );
    2485             : 
    2486           0 :   ulong banks_obj_id = fd_pod_query_ulong( topo->props, "banks", ULONG_MAX );
    2487           0 :   FD_TEST( banks_obj_id!=ULONG_MAX );
    2488           0 :   ulong banks_locks_obj_id = fd_pod_query_ulong( topo->props, "banks_locks", ULONG_MAX );
    2489           0 :   FD_TEST( banks_locks_obj_id!=ULONG_MAX );
    2490             : 
    2491           0 :   FD_TEST( fd_banks_join( ctx->banks, fd_topo_obj_laddr( topo, banks_obj_id ), fd_topo_obj_laddr( topo, banks_locks_obj_id ) ) );
    2492             : 
    2493           0 :   fd_bank_data_t * bank_pool = fd_banks_get_bank_pool( ctx->banks->data );
    2494           0 :   FD_MGAUGE_SET( REPLAY, MAX_LIVE_BANKS, fd_banks_pool_max( bank_pool ) );
    2495             : 
    2496           0 :   fd_bank_t bank[1];
    2497           0 :   FD_TEST( fd_banks_init_bank( bank, ctx->banks ) );
    2498           0 :   fd_bank_slot_set( bank, 0UL );
    2499           0 :   FD_TEST( bank->data->idx==FD_REPLAY_BOOT_BANK_IDX );
    2500             : 
    2501           0 :   ctx->consensus_root_slot = ULONG_MAX;
    2502           0 :   ctx->consensus_root      = (fd_hash_t){ .ul[0] = FD_RUNTIME_INITIAL_BLOCK_ID };
    2503           0 :   ctx->published_root_slot = ULONG_MAX;
    2504             : 
    2505           0 :   ctx->expected_shred_version = tile->replay.expected_shred_version;
    2506           0 :   ctx->ipecho_shred_version = 0;
    2507           0 :   fd_memcpy( ctx->genesis_path, tile->replay.genesis_path, sizeof(ctx->genesis_path) );
    2508           0 :   ctx->has_genesis_hash = 0;
    2509           0 :   ctx->cluster_type = FD_CLUSTER_UNKNOWN;
    2510           0 :   ctx->hard_forks_cnt = ULONG_MAX;
    2511             : 
    2512           0 :   if( FD_UNLIKELY( tile->replay.bundle.enabled ) ) {
    2513           0 :     ctx->bundle.enabled = 1;
    2514           0 :     if( FD_UNLIKELY( !fd_bundle_crank_gen_init( ctx->bundle.gen,
    2515           0 :              (fd_acct_addr_t const *)tile->replay.bundle.tip_distribution_program_addr,
    2516           0 :              (fd_acct_addr_t const *)tile->replay.bundle.tip_payment_program_addr,
    2517           0 :              (fd_acct_addr_t const *)ctx->bundle.vote_account.uc,
    2518           0 :              (fd_acct_addr_t const *)ctx->bundle.vote_account.uc, "NAN", 0UL ) ) ) {
    2519           0 :       FD_LOG_ERR(( "failed to initialize bundle crank gen" ));
    2520           0 :     }
    2521           0 :   } else {
    2522           0 :     ctx->bundle.enabled = 0;
    2523           0 :   }
    2524             : 
    2525           0 :   fd_features_t * features = fd_bank_features_modify( bank );
    2526           0 :   fd_features_enable_cleaned_up( features, &FD_RUNTIME_CLUSTER_VERSION );
    2527             : 
    2528           0 :   char const * one_off_features[ 16UL ];
    2529           0 :   FD_TEST( tile->replay.enable_features_cnt<=sizeof(one_off_features)/sizeof(one_off_features[0]) );
    2530           0 :   for( ulong i=0UL; i<tile->replay.enable_features_cnt; i++ ) one_off_features[ i ] = tile->replay.enable_features[i];
    2531           0 :   fd_features_enable_one_offs( features, one_off_features, (uint)tile->replay.enable_features_cnt, 0UL );
    2532             : 
    2533           0 :   fd_topo_obj_t const * vinyl_data = fd_topo_find_tile_obj( topo, tile, "vinyl_data" );
    2534           0 :   int enable_reclaims = !vinyl_data;
    2535             : 
    2536           0 :   FD_TEST( fd_accdb_admin_v1_init ( ctx->accdb_admin,     fd_topo_obj_laddr( topo, tile->replay.funk_obj_id      ), enable_reclaims ) );
    2537           0 :   FD_TEST( fd_progcache_admin_join( ctx->progcache_admin, fd_topo_obj_laddr( topo, tile->replay.progcache_obj_id ) ) );
    2538             : 
    2539           0 :   if( !vinyl_data ) {
    2540           0 :     FD_TEST( fd_accdb_user_v1_init( ctx->accdb, fd_topo_obj_laddr( topo, tile->replay.funk_obj_id ) ) );
    2541           0 :   } else {
    2542           0 :     fd_topo_obj_t const * vinyl_rq       = fd_topo_find_tile_obj( topo, tile, "vinyl_rq" );
    2543           0 :     fd_topo_obj_t const * vinyl_req_pool = fd_topo_find_tile_obj( topo, tile, "vinyl_rpool" );
    2544           0 :     FD_TEST( fd_accdb_user_v2_init( ctx->accdb,
    2545           0 :         fd_topo_obj_laddr( topo, tile->replay.funk_obj_id ),
    2546           0 :         fd_topo_obj_laddr( topo, vinyl_rq->id ),
    2547           0 :         topo->workspaces[ vinyl_data->wksp_id ].wksp,
    2548           0 :         fd_topo_obj_laddr( topo, vinyl_req_pool->id ),
    2549           0 :         vinyl_rq->id ) );
    2550           0 :   }
    2551             : 
    2552           0 :   void * _txncache_shmem = fd_topo_obj_laddr( topo, tile->replay.txncache_obj_id );
    2553           0 :   fd_txncache_shmem_t * txncache_shmem = fd_txncache_shmem_join( _txncache_shmem );
    2554           0 :   FD_TEST( txncache_shmem );
    2555           0 :   ctx->txncache = fd_txncache_join( fd_txncache_new( _txncache, txncache_shmem ) );
    2556           0 :   FD_TEST( ctx->txncache );
    2557             : 
    2558           0 :   ctx->capture_ctx = NULL;
    2559           0 :   if( FD_UNLIKELY( strcmp( "", tile->replay.solcap_capture ) || strcmp( "", tile->replay.dump_proto_dir ) ) ) {
    2560           0 :     ctx->capture_ctx = fd_capture_ctx_join( fd_capture_ctx_new( _capture_ctx ) );
    2561           0 :     ctx->capture_ctx->solcap_start_slot = tile->replay.capture_start_slot;
    2562           0 :   }
    2563             : 
    2564           0 :   if( FD_UNLIKELY( strcmp( "", tile->replay.dump_proto_dir ) ) ) {
    2565           0 :     ctx->capture_ctx->dump_proto_output_dir = tile->replay.dump_proto_dir;
    2566           0 :     if( FD_LIKELY( tile->replay.dump_block_to_pb ) ) ctx->capture_ctx->dump_block_to_pb = tile->replay.dump_block_to_pb;
    2567           0 :   }
    2568             : 
    2569           0 : # if FD_HAS_FLATCC
    2570           0 :   if( FD_UNLIKELY( tile->replay.dump_block_to_pb ) ) {
    2571           0 :     ctx->block_dump_ctx = fd_block_dump_context_join( fd_block_dump_context_new( block_dump_ctx ) );
    2572           0 :   } else {
    2573           0 :     ctx->block_dump_ctx = NULL;
    2574           0 :   }
    2575           0 : # endif
    2576             : 
    2577           0 :   ctx->exec_cnt = fd_topo_tile_name_cnt( topo, "exec" );
    2578             : 
    2579           0 :   ctx->is_booted = 0;
    2580             : 
    2581           0 :   ctx->larger_max_cost_per_block = tile->replay.larger_max_cost_per_block;
    2582             : 
    2583           0 :   ctx->reasm = fd_reasm_join( fd_reasm_new( reasm_mem, tile->replay.fec_max, ctx->reasm_seed ) );
    2584           0 :   FD_TEST( ctx->reasm );
    2585             : 
    2586           0 :   ctx->sched = fd_sched_join( fd_sched_new( sched_mem, tile->replay.max_live_slots, ctx->exec_cnt ), tile->replay.max_live_slots );
    2587           0 :   FD_TEST( ctx->sched );
    2588             : 
    2589           0 :   FD_TEST( fd_vinyl_req_pool_new( vinyl_req_pool_mem, 1UL, 1UL ) );
    2590             : 
    2591           0 :   ctx->vote_tracker = fd_vote_tracker_join( fd_vote_tracker_new( vote_tracker_mem, ctx->vote_tracker_seed ) );
    2592           0 :   FD_TEST( ctx->vote_tracker );
    2593             : 
    2594           0 :   ctx->has_identity_vote_rooted = 0;
    2595             : 
    2596           0 :   ctx->mleaders = fd_multi_epoch_leaders_join( fd_multi_epoch_leaders_new( ctx->mleaders_mem ) );
    2597           0 :   FD_TEST( ctx->mleaders );
    2598             : 
    2599           0 :   ctx->is_leader             = 0;
    2600           0 :   ctx->reset_slot            = 0UL;
    2601           0 :   fd_memset( ctx->reset_bank, 0, sizeof(fd_bank_t) );
    2602           0 :   ctx->reset_block_id        = (fd_hash_t){ .ul[0] = FD_RUNTIME_INITIAL_BLOCK_ID };
    2603           0 :   ctx->reset_timestamp_nanos = 0UL;
    2604           0 :   ctx->next_leader_slot      = ULONG_MAX;
    2605           0 :   ctx->next_leader_tickcount = LONG_MAX;
    2606           0 :   ctx->highwater_leader_slot = ULONG_MAX;
    2607           0 :   ctx->slot_duration_nanos   = 350L*1000L*1000L; /* TODO: Not fixed ... not always 350ms ... */
    2608           0 :   ctx->slot_duration_ticks   = (double)ctx->slot_duration_nanos*fd_tempo_tick_per_ns( NULL );
    2609           0 :   ctx->leader_bank->data     = NULL;
    2610             : 
    2611           0 :   ctx->block_id_len = tile->replay.max_live_slots;
    2612           0 :   ctx->block_id_arr = (fd_block_id_ele_t *)block_id_arr_mem;
    2613           0 :   ctx->block_id_map = fd_block_id_map_join( fd_block_id_map_new( block_id_map_mem, chain_cnt, ctx->block_id_map_seed ) );
    2614           0 :   FD_TEST( ctx->block_id_map );
    2615             : 
    2616           0 :   ctx->resolv_tile_cnt = fd_topo_tile_name_cnt( topo, "resolv" );
    2617             : 
    2618           0 :   FD_TEST( tile->in_cnt<=sizeof(ctx->in)/sizeof(ctx->in[0]) );
    2619           0 :   for( ulong i=0UL; i<tile->in_cnt; i++ ) {
    2620           0 :     fd_topo_link_t * link = &topo->links[ tile->in_link_id[ i ] ];
    2621           0 :     fd_topo_wksp_t * link_wksp = &topo->workspaces[ topo->objs[ link->dcache_obj_id ].wksp_id ];
    2622             : 
    2623           0 :     if( FD_LIKELY( link->dcache ) ) {
    2624           0 :       ctx->in[ i ].mem    = link_wksp->wksp;
    2625           0 :       ctx->in[ i ].chunk0 = fd_dcache_compact_chunk0( ctx->in[ i ].mem, link->dcache );
    2626           0 :       ctx->in[ i ].wmark  = fd_dcache_compact_wmark ( ctx->in[ i ].mem, link->dcache, link->mtu );
    2627           0 :       ctx->in[ i ].mtu    = link->mtu;
    2628           0 :     }
    2629             : 
    2630           0 :     if(      !strcmp( link->name, "genesi_out"   ) ) ctx->in_kind[ i ] = IN_KIND_GENESIS;
    2631           0 :     else if( !strcmp( link->name, "ipecho_out"   ) ) ctx->in_kind[ i ] = IN_KIND_IPECHO;
    2632           0 :     else if( !strcmp( link->name, "snapin_manif" ) ) ctx->in_kind[ i ] = IN_KIND_SNAP;
    2633           0 :     else if( !strcmp( link->name, "exec_replay"  ) ) ctx->in_kind[ i ] = IN_KIND_EXEC;
    2634           0 :     else if( !strcmp( link->name, "tower_out"    ) ) ctx->in_kind[ i ] = IN_KIND_TOWER;
    2635           0 :     else if( !strcmp( link->name, "poh_replay"   ) ) ctx->in_kind[ i ] = IN_KIND_POH;
    2636           0 :     else if( !strcmp( link->name, "resolv_repla" ) ) ctx->in_kind[ i ] = IN_KIND_RESOLV;
    2637           0 :     else if( !strcmp( link->name, "shred_out"    ) ) ctx->in_kind[ i ] = IN_KIND_SHRED;
    2638           0 :     else if( !strcmp( link->name, "send_out"     ) ) ctx->in_kind[ i ] = IN_KIND_VTXN;
    2639           0 :     else if( !strcmp( link->name, "gui_replay"   ) ) ctx->in_kind[ i ] = IN_KIND_GUI;
    2640           0 :     else if( !strcmp( link->name, "rpc_replay"   ) ) ctx->in_kind[ i ] = IN_KIND_RPC;
    2641           0 :     else FD_LOG_ERR(( "unexpected input link name %s", link->name ));
    2642           0 :   }
    2643             : 
    2644           0 :   *ctx->stake_out  = out1( topo, tile, "replay_stake" ); FD_TEST( ctx->stake_out->idx!=ULONG_MAX );
    2645           0 :   *ctx->replay_out = out1( topo, tile, "replay_out" ); FD_TEST( ctx->replay_out->idx!=ULONG_MAX );
    2646             : 
    2647           0 :   ulong idx = fd_topo_find_tile_out_link( topo, tile, "replay_exec", 0UL );
    2648           0 :   FD_TEST( idx!=ULONG_MAX );
    2649           0 :   fd_topo_link_t * link = &topo->links[ tile->out_link_id[ idx ] ];
    2650             : 
    2651           0 :   fd_replay_out_link_t * exec_out = ctx->exec_out;
    2652           0 :   exec_out->idx    = idx;
    2653           0 :   exec_out->mem    = topo->workspaces[ topo->objs[ link->dcache_obj_id ].wksp_id ].wksp;
    2654           0 :   exec_out->chunk0 = fd_dcache_compact_chunk0( exec_out->mem, link->dcache );
    2655           0 :   exec_out->wmark  = fd_dcache_compact_wmark( exec_out->mem, link->dcache, link->mtu );
    2656           0 :   exec_out->chunk  = exec_out->chunk0;
    2657             : 
    2658           0 :   ctx->gui_enabled = fd_topo_find_tile( topo, "gui", 0UL )!=ULONG_MAX;
    2659           0 :   ctx->rpc_enabled = fd_topo_find_tile( topo, "rpc", 0UL )!=ULONG_MAX;
    2660             : 
    2661           0 :   if( FD_UNLIKELY( strcmp( "", tile->replay.solcap_capture ) ) ) {
    2662           0 :     idx = fd_topo_find_tile_out_link( topo, tile, "cap_repl", 0UL );
    2663           0 :     FD_TEST( idx!=ULONG_MAX );
    2664           0 :     link = &topo->links[ tile->out_link_id[ idx ] ];
    2665             : 
    2666             : 
    2667           0 :     fd_capture_link_buf_t * cap_repl_out = ctx->cap_repl_out;
    2668           0 :     cap_repl_out->base.vt = &fd_capture_link_buf_vt;
    2669           0 :     cap_repl_out->idx     = idx;
    2670           0 :     cap_repl_out->mem     = topo->workspaces[ topo->objs[ link->dcache_obj_id ].wksp_id ].wksp;
    2671           0 :     cap_repl_out->chunk0  = fd_dcache_compact_chunk0( cap_repl_out->mem, link->dcache );
    2672           0 :     cap_repl_out->wmark   = fd_dcache_compact_wmark( cap_repl_out->mem, link->dcache, link->mtu );
    2673           0 :     cap_repl_out->chunk   = cap_repl_out->chunk0;
    2674           0 :     cap_repl_out->mcache  = link->mcache;
    2675           0 :     cap_repl_out->depth   = fd_mcache_depth( link->mcache );
    2676           0 :     cap_repl_out->seq     = 0UL;
    2677             : 
    2678           0 :     ctx->capture_ctx->capctx_type.buf  = cap_repl_out;
    2679           0 :     ctx->capture_ctx->capture_link    = &cap_repl_out->base;
    2680           0 :     ctx->capture_ctx->current_txn_idx = 0UL;
    2681             : 
    2682             : 
    2683           0 :     ulong consumer_tile_idx = fd_topo_find_tile( topo, "solcap", 0UL );
    2684           0 :     fd_topo_tile_t * consumer_tile = &topo->tiles[ consumer_tile_idx ];
    2685           0 :     cap_repl_out->fseq = NULL;
    2686           0 :     for( ulong j = 0UL; j < consumer_tile->in_cnt; j++ ) {
    2687           0 :       if( FD_UNLIKELY( consumer_tile->in_link_id[ j ]  == link->id ) ) {
    2688           0 :         cap_repl_out->fseq = fd_fseq_join( fd_topo_obj_laddr( topo, consumer_tile->in_link_fseq_obj_id[ j ] ) );
    2689           0 :         FD_TEST( cap_repl_out->fseq );
    2690           0 :         break;
    2691           0 :       }
    2692           0 :     }
    2693           0 :   }
    2694             : 
    2695           0 :   fd_memset( &ctx->metrics, 0, sizeof(ctx->metrics) );
    2696             : 
    2697           0 :   fd_histf_join( fd_histf_new( ctx->metrics.store_link_wait,    FD_MHIST_SECONDS_MIN( REPLAY, STORE_LINK_WAIT ),
    2698           0 :                                                                 FD_MHIST_SECONDS_MAX( REPLAY, STORE_LINK_WAIT ) ) );
    2699           0 :   fd_histf_join( fd_histf_new( ctx->metrics.store_link_work,    FD_MHIST_SECONDS_MIN( REPLAY, STORE_LINK_WORK ),
    2700           0 :                                                                 FD_MHIST_SECONDS_MAX( REPLAY, STORE_LINK_WORK ) ) );
    2701           0 :   fd_histf_join( fd_histf_new( ctx->metrics.store_read_wait,    FD_MHIST_SECONDS_MIN( REPLAY, STORE_READ_WAIT ),
    2702           0 :                                                                 FD_MHIST_SECONDS_MAX( REPLAY, STORE_READ_WAIT ) ) );
    2703           0 :   fd_histf_join( fd_histf_new( ctx->metrics.store_read_work,    FD_MHIST_SECONDS_MIN( REPLAY, STORE_READ_WORK ),
    2704           0 :                                                                 FD_MHIST_SECONDS_MAX( REPLAY, STORE_READ_WORK ) ) );
    2705           0 :   fd_histf_join( fd_histf_new( ctx->metrics.store_publish_wait, FD_MHIST_SECONDS_MIN( REPLAY, STORE_PUBLISH_WAIT ),
    2706           0 :                                                                 FD_MHIST_SECONDS_MAX( REPLAY, STORE_PUBLISH_WAIT ) ) );
    2707           0 :   fd_histf_join( fd_histf_new( ctx->metrics.store_publish_work, FD_MHIST_SECONDS_MIN( REPLAY, STORE_PUBLISH_WORK ),
    2708           0 :                                                                 FD_MHIST_SECONDS_MAX( REPLAY, STORE_PUBLISH_WORK ) ) );
    2709             : 
    2710           0 :   ulong scratch_top = FD_SCRATCH_ALLOC_FINI( l, 1UL );
    2711           0 :   if( FD_UNLIKELY( scratch_top > (ulong)scratch + scratch_footprint( tile ) ) )
    2712           0 :     FD_LOG_ERR(( "scratch overflow %lu %lu %lu", scratch_top - (ulong)scratch - scratch_footprint( tile ), scratch_top, (ulong)scratch + scratch_footprint( tile ) ));
    2713           0 : }
    2714             : 
    2715             : static ulong
    2716             : populate_allowed_seccomp( fd_topo_t const *      topo FD_FN_UNUSED,
    2717             :                           fd_topo_tile_t const * tile FD_FN_UNUSED,
    2718             :                           ulong                  out_cnt,
    2719           0 :                           struct sock_filter *   out ) {
    2720             : 
    2721           0 :   populate_sock_filter_policy_fd_replay_tile( out_cnt, out, (uint)fd_log_private_logfile_fd() );
    2722           0 :   return sock_filter_policy_fd_replay_tile_instr_cnt;
    2723           0 : }
    2724             : 
    2725             : static ulong
    2726             : populate_allowed_fds( fd_topo_t const *      topo FD_FN_UNUSED,
    2727             :                       fd_topo_tile_t const * tile FD_FN_UNUSED,
    2728             :                       ulong                  out_fds_cnt,
    2729           0 :                       int *                  out_fds ) {
    2730             : 
    2731           0 :   if( FD_UNLIKELY( out_fds_cnt<2UL ) ) FD_LOG_ERR(( "out_fds_cnt %lu", out_fds_cnt ));
    2732             : 
    2733           0 :   ulong out_cnt = 0UL;
    2734           0 :   out_fds[ out_cnt++ ] = 2; /* stderr */
    2735           0 :   if( FD_LIKELY( -1!=fd_log_private_logfile_fd() ) )
    2736           0 :     out_fds[ out_cnt++ ] = fd_log_private_logfile_fd(); /* logfile */
    2737           0 :   return out_cnt;
    2738           0 : }
    2739             : 
    2740             : #undef DEBUG_LOGGING
    2741             : 
    2742             : /* counting carefully, after_credit can generate at most 7 frags and
    2743             :    returnable_frag boot_genesis can also generate at most 7 frags, so 14
    2744             :    is a conservative bound. */
    2745           0 : #define STEM_BURST (14UL)
    2746             : 
    2747             : /* TODO: calculate this properly/fix stem to work with larger numbers of links */
    2748             : /* 1000 chosen empirically as anything larger slowed down replay times. Need to calculate
    2749             :    this properly. */
    2750           0 : #define STEM_LAZY ((long)10e3)
    2751             : 
    2752           0 : #define STEM_CALLBACK_CONTEXT_TYPE  fd_replay_tile_t
    2753           0 : #define STEM_CALLBACK_CONTEXT_ALIGN alignof(fd_replay_tile_t)
    2754             : 
    2755           0 : #define STEM_CALLBACK_METRICS_WRITE   metrics_write
    2756           0 : #define STEM_CALLBACK_AFTER_CREDIT    after_credit
    2757           0 : #define STEM_CALLBACK_BEFORE_FRAG     before_frag
    2758           0 : #define STEM_CALLBACK_RETURNABLE_FRAG returnable_frag
    2759             : 
    2760             : #include "../../disco/stem/fd_stem.c"
    2761             : 
    2762             : fd_topo_run_tile_t fd_tile_replay = {
    2763             :   .name                     = "replay",
    2764             :   .populate_allowed_seccomp = populate_allowed_seccomp,
    2765             :   .populate_allowed_fds     = populate_allowed_fds,
    2766             :   .scratch_align            = scratch_align,
    2767             :   .scratch_footprint        = scratch_footprint,
    2768             :   .privileged_init          = privileged_init,
    2769             :   .unprivileged_init        = unprivileged_init,
    2770             :   .run                      = stem_run,
    2771             : };

Generated by: LCOV version 1.14