LCOV - code coverage report
Current view: top level - discof/votor - fd_votor_tile.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 0 2194 0.0 %
Date: 2026-11-26 02:16:43 Functions: 0 162 0.0 %

          Line data    Source code
       1             : #define _GNU_SOURCE /* syscall, pwritev2, RENAME_EXCHANGE */
       2             : #include "fd_votor_tile.h"
       3             : #include <linux/futex.h>
       4             : #include "generated/fd_votor_tile_seccomp.h"
       5             : 
       6             : #include "../../choreo/votor/fd_cert_serde.h"
       7             : #include "../../choreo/votor/fd_votor_pool.h"
       8             : #include "../../choreo/votor/fd_vote_history_serde.h"
       9             : #include "../../choreo/votor/fd_vote_serde.h"
      10             : #include "../../choreo/votor/fd_votor_loop.h"
      11             : #include "../../disco/events/generated/fd_event_gen.h"
      12             : #include "../../disco/keyguard/fd_keyguard.h"
      13             : #include "../../disco/keyguard/fd_keyguard_client.h"
      14             : #include "../../disco/keyguard/fd_keyload.h"
      15             : #include "../../disco/keyguard/fd_keyswitch.h"
      16             : #include "../../disco/metrics/fd_metrics.h"
      17             : #include "../../disco/net/fd_net_tile.h"
      18             : #include "../../disco/stem/fd_stem.h"
      19             : #include "../../disco/topo/fd_topo.h"
      20             : #include "../../disco/fd_clock_tile.h"
      21             : #include "../../flamenco/gossip/fd_gossip_message.h"
      22             : #include "../../flamenco/leaders/fd_leaders_base.h"
      23             : #include "../../flamenco/leaders/fd_multi_epoch_leaders.h"
      24             : #include "../../flamenco/stakes/fd_stake_weight.h"
      25             : #include "../../util/net/fd_net_headers.h"
      26             : #include "../../util/fd_hash32.h"
      27             : #include "../../waltz/quic/fd_quic.h"
      28             : #include "../../waltz/quic/fd_quic_conn.h"
      29             : #include "../../waltz/quic/fd_quic_private.h"
      30             : #include "../replay/fd_replay_tile.h"
      31             : #include "../restore/utils/fd_wfs.h"
      32             : 
      33             : #include <dirent.h>
      34             : #include <errno.h>
      35             : #include <fcntl.h>
      36             : #include <stdio.h>
      37             : #include <unistd.h>
      38             : #include <sys/mman.h>
      39             : #include <sys/stat.h>
      40             : #include <sys/syscall.h>
      41             : #include <sys/uio.h>
      42             : 
      43           0 : #define IN_KIND_EPOCH  (0)
      44           0 : #define IN_KIND_GOSSIP (1)
      45           0 : #define IN_KIND_IPECHO (2)
      46           0 : #define IN_KIND_NET    (3)
      47           0 : #define IN_KIND_REPLAY (4)
      48           0 : #define IN_KIND_SIGN   (5)
      49           0 : #define IN_KIND_FAILOV (6)
      50             : 
      51           0 : #define OUT_IDX_VOTOR (0UL)
      52           0 : #define OUT_IDX_NET   (1UL)
      53             : 
      54           0 : #define QUIC_CLOSE_CODE_INVALID_IDENTITY     (2U) /* agave_votor_transport::error::close_codes::INVALID_IDENTITY */
      55           0 : #define QUIC_CLOSE_CODE_NOT_ADMITTED         (3U) /* agave_votor_transport::error::close_codes::NOT_ADMITTED */
      56           0 : #define QUIC_CLOSE_CODE_BANNED               (4U) /* agave_votor_transport::error::close_codes::BANNED */
      57           0 : #define QUIC_CLOSE_CODE_TOO_MANY_CONNECTIONS (5U) /* agave_votor_transport::error::close_codes::TOO_MANY_CONNECTIONS */
      58             : 
      59           0 : #define QUIC_BAN_TIMEOUT_NS   (10L*1000L*1000L*1000L) /* agave_bls_sigverify::bls_sigverifier::BAN_TIMEOUT */
      60           0 : #define QUIC_K_GRANULARITY_NS (1000000L)              /* 1 ms, RFC 9002 kGranularity, same as FD_QUIC_K_GRANULARITY_NS */
      61             : 
      62           0 : #define QUIC_CLIENT_CONN_BACKOFF_MIN_NS (1L*1000L*1000L*1000L)       /* 1 s */
      63           0 : #define QUIC_CLIENT_CONN_BACKOFF_MAX_NS (1L*1000L*1000L*1000L)       /* 1 s */
      64           0 : #define QUIC_CLIENT_CONN_AHEAD_NS       (10L*1000L*1000L*1000L)      /* connect to peers this long before our first ranked epoch, spreading the handshakes out (Agave admits next-epoch voters from 30000 slots out) */
      65             : #define QUIC_CLIENT_CONN_MAX            (FD_VOTOR_VAT_MAX * (3 + 1)) /* one conn to every validator of the prev, curr and next epochs, plus an epoch of evicted conns still closing */
      66             : 
      67           0 : #define QUIC_SERVER_CONN_PER_PEER_MAX (2UL)                                              /* allow up to 2 per peer, in case of failures (zombies, network partition, etc.) */
      68             : #define QUIC_SERVER_CONN_MAX          (FD_VOTOR_VAT_MAX * QUIC_SERVER_CONN_PER_PEER_MAX) /* at most FD_VOTOR_VAT_MAX connections */
      69             : 
      70           0 : #define REWARD_VOTE_MAX        (FD_VOTOR_REWARD_SLOT_DELTA+FD_VOTOR_SLOTS_PER_WINDOW) /* voting slot+REWARD_VOTE_MAX needs ParentReady past slot+8's window, deciding slot's reward */
      71           0 : #define REWARD_VOTE_RTT_MIN_NS (10000000L)                                            /* retry a reward vote no sooner than 10ms */
      72           0 : #define REWARD_VOTE_RTT_MAX_NS (200000000L)                                           /* retry a reward vote no later than 200ms */
      73           0 : #define REWARD_VOTE_TX_MAX     (16UL)                                                 /* sends per reward vote: RTT_MIN doubling to RTT_MAX fits 13 before slot+8's footer seals at 200ms slots */
      74           0 : #define REWARD_REPUBLISH_NS    (50000000L)                                            /* republish a reward cert no sooner than 50ms, each publish verifies its aggregates */
      75             : 
      76           0 : #define STANDSTILL_TX_INTERVAL_NS    (50000000L)   /* 20 standstill messages a second, Agave's STANDSTILL_REFRESH_BATCH_SIZE per STANDSTILL_REFRESH_INTERVAL */
      77           0 : #define STANDSTILL_CYCLE_INTERVAL_NS (1000000000L) /* pause between standstill cycles, Agave's STANDSTILL_REFRESH_INTERVAL */
      78             : 
      79             : #define VOTE_TOO_NEW (40UL) /* lookahead at most 40 slots from highest ParentReady, Agave's MAX_VOTE_SLOT_DISTANCE_FROM_PARENT_READY */
      80             : 
      81             : #define SER_MAX (FD_VOTE_SER_MAX>FD_CERT_SER_MAX ? FD_VOTE_SER_MAX : FD_CERT_SER_MAX)
      82             : 
      83             : static fd_quic_limits_t quic_client_limits = {
      84             :   .conn_cnt                    = QUIC_CLIENT_CONN_MAX,
      85             :   .handshake_cnt               = 1024UL,
      86             :   .conn_id_cnt                 = FD_QUIC_MIN_CONN_ID_CNT,
      87             :   .inflight_frame_cnt          = 16UL * QUIC_CLIENT_CONN_MAX,
      88             :   .min_inflight_frame_cnt_conn = 8UL,
      89             : };
      90             : 
      91             : static fd_quic_limits_t quic_server_limits = {
      92             :   .conn_cnt                    = QUIC_SERVER_CONN_MAX,
      93             :   .handshake_cnt               = 1024UL,
      94             :   .conn_id_cnt                 = FD_QUIC_MIN_CONN_ID_CNT,
      95             :   .inflight_frame_cnt          = 64UL * QUIC_SERVER_CONN_MAX,
      96             :   .min_inflight_frame_cnt_conn = 32UL,
      97             : };
      98             : 
      99           0 : #define CONTACT_INFOS_LG_SLOT_CNT (16) /* FD_CONTACT_INFO_TABLE_SIZE keys, fill ratio 0.5 */
     100             : FD_STATIC_ASSERT( (1UL<<CONTACT_INFOS_LG_SLOT_CNT)==2UL*FD_CONTACT_INFO_TABLE_SIZE, contact_infos );
     101             : 
     102             : struct contact_info {
     103             :   fd_pubkey_t id_key;
     104             :   uint        hash;
     105             :   uint        ip4;
     106             :   ushort      port;
     107             :   uchar       removed; /* gossip removed it, kept until its peer is evicted */
     108             : };
     109             : typedef struct contact_info contact_info_t;
     110             : 
     111             : #define MAP_NAME                contact_infos
     112           0 : #define MAP_T                   contact_info_t
     113           0 : #define MAP_KEY                 id_key
     114           0 : #define MAP_KEY_T               fd_pubkey_t
     115           0 : #define MAP_KEY_NULL            ((fd_pubkey_t){ .ul = {0} }) /* no validator identity is the zero pubkey */
     116           0 : #define MAP_KEY_INVAL(k)        (!((k).ul[0]|(k).ul[1]|(k).ul[2]|(k).ul[3]))
     117           0 : #define MAP_KEY_EQUAL(k0,k1)    (!memcmp(&(k0),&(k1),sizeof(fd_pubkey_t)))
     118             : #define MAP_KEY_EQUAL_IS_SLOW   1
     119           0 : #define MAP_KEY_HASH(key,seed)  ((uint)fd_hash32((key).uc,(seed)))
     120             : #include "../../util/tmpl/fd_map_dynamic.c"
     121             : 
     122           0 : #define PEERS_LG_SLOT_CNT (13) /* Capacity for four epochs of FD_VOTOR_VAT_MAX identities. */
     123             : FD_STATIC_ASSERT( (1UL<<PEERS_LG_SLOT_CNT)>=4UL*FD_VOTOR_VAT_MAX, peers );
     124             : 
     125             : struct peer {
     126             :   fd_pubkey_t      id_key;
     127             :   uint             hash;
     128             :   ushort           prev_rank;
     129             :   ushort           curr_rank;
     130             :   ushort           next_rank;
     131             :   fd_quic_conn_t * tx_conn;
     132             :   fd_quic_conn_t * rx_conn[ QUIC_SERVER_CONN_PER_PEER_MAX ];
     133             :   long             ban_ts;
     134             :   long             conn_ts;
     135             :   long             conn_backoff;
     136             :   int              reconn_pending; /* 1 if the peer has an entry in reconn_prq */
     137             : };
     138             : typedef struct peer peer_t;
     139             : 
     140             : #define MAP_NAME                peers
     141           0 : #define MAP_T                   peer_t
     142           0 : #define MAP_KEY                 id_key
     143           0 : #define MAP_KEY_T               fd_pubkey_t
     144           0 : #define MAP_KEY_NULL            ((fd_pubkey_t){ .ul = {0} }) /* no validator identity is the zero pubkey */
     145           0 : #define MAP_KEY_INVAL(k)        (!((k).ul[0]|(k).ul[1]|(k).ul[2]|(k).ul[3]))
     146           0 : #define MAP_KEY_EQUAL(k0,k1)    (!memcmp(&(k0),&(k1),sizeof(fd_pubkey_t)))
     147             : #define MAP_KEY_EQUAL_IS_SLOW   1
     148           0 : #define MAP_KEY_HASH(key,seed)  ((uint)fd_hash32((key).uc,(seed)))
     149             : #include "../../util/tmpl/fd_map_dynamic.c"
     150             : 
     151             : struct reconn {
     152             :   long        timeout;
     153             :   fd_pubkey_t id_key;
     154             : };
     155             : typedef struct reconn reconn_t;
     156             : 
     157             : #define PRQ_NAME reconn_prq
     158           0 : #define PRQ_T    reconn_t
     159             : #include "../../util/tmpl/fd_prq.c"
     160             : 
     161           0 : #define RECONN_MAX (1UL<<PEERS_LG_SLOT_CNT)
     162             : 
     163             : /* reward_vote specially tracks that our vote for slot is ACK'd by the
     164             :    leader for the reward slot (slot + 8). */
     165             : 
     166             : struct reward_vote {
     167             :   ulong            slot; /* ULONG_MAX if free */
     168             :   long             retry_ts;
     169             :   long             backoff;
     170             :   ulong            tx_cnt;
     171             :   fd_quic_conn_t * conn; /* conn the pkt_nums were sent on */
     172             :   ulong            pkt_num[ REWARD_VOTE_TX_MAX ]; /* every send on conn, an ACK of any acks the vote */
     173             :   fd_vote_t        vote;
     174             : };
     175             : typedef struct reward_vote reward_vote_t;
     176             : 
     177             : /* reward_cert tracks whether we've obtained a better reward cert for a
     178             :    given slot, marking it dirty to be republished. */
     179             : 
     180             : struct reward_cert {
     181             :   ulong slot; /* ULONG_MAX if free */
     182             :   int   dirty;
     183             :   long  publish_ts;
     184             : };
     185             : typedef struct reward_cert reward_cert_t;
     186             : 
     187           0 : #define AUTH_VTR_LG_SLOT_CNT (5) /* identity plus 16 authorized voters, fill ratio 0.53 */
     188             : 
     189             : struct auth_vtr_key {
     190             :   uchar uc[ FD_BLS_PUB_COMPRESSED_SZ ];
     191             : };
     192             : typedef struct auth_vtr_key auth_vtr_key_t;
     193             : 
     194             : struct auth_vtr {
     195             :   auth_vtr_key_t bls_key;   /* derived from the identity or an authorized voter */
     196             :   ulong          paths_idx; /* index in authorized voter paths, ULONG_MAX for the identity */
     197             : };
     198             : typedef struct auth_vtr auth_vtr_t;
     199             : 
     200             : #define MAP_NAME              auth_vtr
     201           0 : #define MAP_T                 auth_vtr_t
     202           0 : #define MAP_LG_SLOT_CNT       AUTH_VTR_LG_SLOT_CNT
     203           0 : #define MAP_KEY               bls_key
     204           0 : #define MAP_KEY_T             auth_vtr_key_t
     205           0 : #define MAP_KEY_NULL          ((auth_vtr_key_t){ .uc = {0} }) /* no compressed BLS public key is all zero */
     206           0 : #define MAP_KEY_EQUAL(k0,k1)  (!memcmp(&(k0),&(k1),sizeof(auth_vtr_key_t)))
     207           0 : #define MAP_KEY_INVAL(k)      (MAP_KEY_EQUAL((k),MAP_KEY_NULL))
     208             : #define MAP_KEY_EQUAL_IS_SLOW 1
     209           0 : #define MAP_KEY_HASH(key)     ((uint)fd_hash(0UL,&(key),sizeof(auth_vtr_key_t)))
     210             : #define MAP_MEMOIZE           0
     211             : #include "../../util/tmpl/fd_map.c"
     212             : 
     213             : struct sort_voter {
     214             :   uchar const * bls;
     215             :   uchar const * id;
     216             :   ulong         stake;
     217             :   fd_bls_pub_t  pub;
     218             :   ulong         idx;
     219             :   int           dup;
     220             : };
     221             : typedef struct sort_voter sort_voter_t;
     222             : 
     223             : #define SORT_NAME        sort_voter_bls
     224           0 : #define SORT_KEY_T       sort_voter_t
     225           0 : #define SORT_BEFORE(a,b) (memcmp((a).bls,(b).bls,FD_BLS_PUB_COMPRESSED_SZ)<0)
     226             : #include "../../util/tmpl/fd_sort.c"
     227             : 
     228             : #define SORT_NAME        sort_voter_id
     229           0 : #define SORT_KEY_T       sort_voter_t
     230           0 : #define SORT_BEFORE(a,b) (memcmp((a).id,(b).id,sizeof(fd_pubkey_t))<0)
     231             : #include "../../util/tmpl/fd_sort.c"
     232             : 
     233             : /* known_key is a validated point from an earlier epoch's ranking, so
     234             :    an unchanged key skips decompression and the subgroup check. */
     235             : 
     236             : struct known_key {
     237             :   uchar const *        bls;
     238             :   fd_bls_pub_t const * pub;
     239             : };
     240             : typedef struct known_key known_key_t;
     241             : 
     242             : #define SORT_NAME        sort_known_key
     243           0 : #define SORT_KEY_T       known_key_t
     244           0 : #define SORT_BEFORE(a,b) (memcmp((a).bls,(b).bls,FD_BLS_PUB_COMPRESSED_SZ)<0)
     245             : #include "../../util/tmpl/fd_sort.c"
     246             : 
     247             : #define SORT_NAME        sort_voter_stake
     248           0 : #define SORT_KEY_T       sort_voter_t
     249           0 : #define SORT_BEFORE(a,b) ((a).stake>(b).stake||((a).stake==(b).stake&&memcmp((a).bls,(b).bls,FD_BLS_PUB_COMPRESSED_SZ)<0))
     250             : #include "../../util/tmpl/fd_sort.c"
     251             : 
     252             : struct fd_votor_tile {
     253             : 
     254             :   /* Signing */
     255             : 
     256             :   fd_pubkey_t          id_key;
     257             :   fd_pubkey_t          id_key_bak;      /* the identity whose .bak is the vote history spare */
     258             :   fd_keyswitch_t *     id_keyswitch;
     259             :   ulong                keyswitch_state; /* FD_KEYSWITCH_STATE_{...} */
     260             :   ulong                replay_in_seq;   /* seq after the last replay_slot frag consumed */
     261             :   auth_vtr_t *         auth_vtr;
     262             :   ulong                auth_vtr_path_cnt;
     263             :   fd_keyswitch_t *     auth_vtr_keyswitch;
     264             :   fd_keyguard_client_t keyguard_client[1];
     265             : 
     266             :   /* Vote history */
     267             : 
     268             :   ulong       vote_history_slot;     /* first slot votor may vote in, from the vote history file, 0 if none */
     269             :   int         vote_history_bak_full; /* the spare holds id_key_bak's vote history */
     270             :   int         vote_history_fd;
     271             :   int         vote_history_fd_swp;   /* swap file, atomic rename */
     272             :   int         vote_history_fd_bak;   /* spare, the new identity's at a switch */
     273             :   int         vote_history_fd_dir;
     274             : 
     275             :   /* Initialization */
     276             : 
     277             :   int           init;
     278             :   fd_block_id_t boot_block_id;
     279             :   ulong         slot_max; /* max_live_slots */
     280             : 
     281             :   /* Wait-for-supermajority (see fd_wfs.h). */
     282             : 
     283             :   ulong  wfs_slot;
     284             :   int    wfs_hash_is_zero;
     285             :   ushort wfs_shred_version;
     286             :   int    wfs_signalled;  /* latch: REPLAY_SIG_WFS_DONE seen */
     287             : 
     288             :   /* Cluster metadata */
     289             : 
     290             :   ushort                     shred_version;
     291             :   long                       ns_per_slot;
     292             :   ulong                      epoch_slot_cnt;
     293             :   fd_epoch_info_t *          prev_epoch_info;
     294             :   ulong                      prev_epoch_slot;
     295             :   fd_epoch_info_t *          curr_epoch_info;
     296             :   ulong                      curr_epoch_slot;
     297             :   fd_epoch_info_t *          next_epoch_info;
     298             :   ulong                      next_epoch_slot;
     299             :   fd_multi_epoch_leaders_t * mleaders;
     300             :   ulong                      next_leader_slot;
     301             :   ulong                      highest_vote_or_lead_slot; /* voting can be out of order, so track a hi-watermark of every vote votor decided and window it led */
     302             :   ulong                      highest_parent_ready_slot;
     303             :   ulong                      highest_certed_final_slot; /* highest slot whose final cert was published paired with its notar cert */
     304             :   ulong                      catchup_slot;              /* highest slot past the pool window with a verified cert, 0 if none */
     305             :   ulong                      catchup_final_slot;        /* same, for a final or fast-final cert */
     306             :   ulong                      catchup_vote_slot;         /* first slot worth a vote or cert while catching up: slot_max behind catchup_slot, or the first whose reward block follows catchup_final_slot */
     307             : 
     308             :   /* Alpenglow data structures */
     309             : 
     310             :   fd_votor_pool_t * pool;
     311             :   fd_votor_loop_t * votor;
     312             : 
     313             :   /* Standstill */
     314             : 
     315             :   ulong                           standstill_slot; /* the finalized slot when standstill_ts was last reset */
     316             :   long                            standstill_ts;   /* LONG_MAX until votor runs, then FD_VOTOR_DELTA_STANDSTILL_NS after standstill_slot changes, then every STANDSTILL_TX_INTERVAL_NS */
     317             :   fd_votor_pool_standstill_iter_t standstill_iter[1];
     318             : 
     319             :   /* Networking */
     320             : 
     321             :   contact_info_t *   contact_infos;
     322             :   peer_t *           peers;
     323             :   fd_pubkey_t        client_peer_id_keys[ QUIC_CLIENT_CONN_MAX ];
     324             :   fd_pubkey_t        server_peer_id_keys[ QUIC_SERVER_CONN_MAX ];
     325             :   fd_net_rx_bounds_t net_in_bounds[ 32 ];
     326             :   uchar              net_buf[ FD_NET_MTU ];
     327             :   fd_quic_t *        quic_client;
     328             :   fd_quic_t *        quic_server;
     329             :   fd_clock_tile_t    clock[1];
     330             :   fd_aio_t           quic_tx_aio[ 1 ];
     331             :   ushort             quic_client_listen_port;
     332             :   uint               src_ip_addr;
     333             :   fd_ip4_udp_hdrs_t  hdr[ 1 ];
     334             :   ushort             net_id;
     335             :   reconn_t *         reconn_prq;
     336             :   ulong              conn_ahead_slot; /* next_epoch_slot we last queued connects ahead of */
     337             :   reward_vote_t      reward_votes[ REWARD_VOTE_MAX ];           /* our reward votes awaiting an ACK from the leader for the reward slot.  circ buf indexed by slot%REWARD_VOTE_MAX */
     338             :   reward_cert_t      reward_certs[ FD_VOTOR_SLOTS_PER_WINDOW ]; /* reward certs published for our leader window.  circ buf indexed by slot%FD_VOTOR_SLOTS_PER_WINDOW */
     339             : 
     340             :   /* Links */
     341             : 
     342             :   int in_kind[32];
     343             :   struct {
     344             :     fd_wksp_t * mem;
     345             :   } in[ 32 ];
     346             : 
     347             :   void * net_out_mem;
     348             :   ulong  net_out_chunk0;
     349             :   ulong  net_out_wmark;
     350             :   ulong  net_out_chunk;
     351             : 
     352             :   void * votor_out_mem;
     353             :   ulong  votor_out_chunk0;
     354             :   ulong  votor_out_wmark;
     355             :   ulong  votor_out_chunk;
     356             : 
     357             :   ulong                                        net_tx_cnt;
     358             :   struct { ulong chunk; ulong sz; ulong sig; } net_tx[ FD_VOTOR_NET_BURST ];
     359             : 
     360             :   fd_stem_context_t * stem; /* for publishing from the quic callbacks */
     361             : 
     362             :   /* Scratch */
     363             : 
     364             :   struct {
     365             :     union {
     366             :       fd_vote_t             vote;
     367             :       fd_cert_t             cert;
     368             :       fd_votor_pool_event_t pool_event;
     369             :       fd_block_id_t         repair_event;
     370             :     };
     371             :     fd_epoch_info_t prev_epoch_info;
     372             :     fd_epoch_info_t curr_epoch_info;
     373             :     fd_epoch_info_t next_epoch_info;
     374             :     uchar           ser[ SER_MAX ];
     375             :     fd_bls_set_t    bad[ fd_bls_set_word_cnt ];
     376             :     uchar           vote_history[ FD_VOTE_HISTORY_SER_SZ ];
     377             :   } scratch;
     378             : 
     379             :   /* Metrics */
     380             : 
     381             :   struct {
     382             :     ulong datagram_rx[ FD_METRICS_ENUM_DATAGRAM_RX_RESULT_CNT ];
     383             :     ulong vote_rx    [ FD_METRICS_ENUM_VOTE_RX_RESULT_CNT     ];
     384             :     ulong cert_rx    [ FD_METRICS_ENUM_CERT_RX_RESULT_CNT     ];
     385             :     ulong bls_verify;
     386             :     ulong vote_history_write;
     387             :     ulong leader_window_superseded;
     388             :     ulong cert_tx_unstaked;
     389             :   } metrics;
     390             : 
     391             :   /* Failover */
     392             : 
     393             :   int         failover_enabled;         /* the topology has the failover links */
     394             :   int         installed_by_failover;    /* the identity we run came from a failover switch, not boot or set-identity */
     395             :   ulong       highest_unsent_slot;      /* highest vote the tile built but did not send, ULONG_MAX none */
     396             :   int         failover_hist_adopted;    /* a history, possibly empty, was adopted since the last switch */
     397             :   ulong       adopted_tip;              /* tip of the adopted history, ULONG_MAX for an empty one or none */
     398             :   int         vote_authority;           /* our rank may be installed, 0 keeps us unranked */
     399             :   int         hist_was_truncated;       /* the last export dropped windows, warned once */
     400             :   ulong       last_leader_slot;         /* slot of the last LEADER we published, ULONG_MAX before any */
     401             :   ulong       adopted_last_leader_slot; /* window of the adopted last LEADER or vote bound, ULONG_MAX when none */
     402             :   ulong       last_vote_slot;           /* highest slot we broadcast a vote for, ULONG_MAX before any */
     403             :   fd_pubkey_t last_vote_key;            /* the identity that vote went out as */
     404             :   ulong       root_slot;                /* replay's root at the last completed slot, ULONG_MAX before any */
     405             :   ulong       highest_completed_slot;   /* highest slot replay completed, 0 before any */
     406             : 
     407             :   /* Publish a vote history snapshot (votor_hist) that the failover tile forwards to the peer */
     408             : 
     409             :   ulong  hist_out_idx; /* votor_hist, ULONG_MAX without failover */
     410             :   void * hist_out_mem;
     411             :   ulong  hist_out_chunk0;
     412             :   ulong  hist_out_wmark;
     413             :   ulong  hist_out_chunk;
     414             :   ulong  hist_seq;     /* votor_hist sequence after our last frame */
     415             : 
     416             :   /* Receive and respond to an adoption request (failov_votor) */
     417             : 
     418             :   ulong  failov_out_idx; /* votor_failov (our adoption response) */
     419             :   void * failov_out_mem;
     420             :   ulong  failov_out_chunk0;
     421             :   ulong  failov_out_wmark;
     422             :   ulong  failov_out_chunk;
     423             : 
     424             :   uchar  adopt_req[ FD_VOTOR_ADOPT_REQ_HDR_SZ+FD_VOTOR_HIST_SER_MAX ];
     425             :   ulong  adopt_req_sz;
     426             : };
     427             : typedef struct fd_votor_tile fd_votor_tile_t;
     428             : 
     429             : static void
     430             : report_alpenglow_vote( fd_votor_tile_t * ctx,
     431             :                        fd_quic_conn_t *  conn,
     432             :                        fd_vote_t const * vote,
     433             :                        uchar             tag,
     434             :                        int               result,
     435             :                        uchar             quorum_reached,
     436             :                        int               reason,
     437             :                        long              aggregation_start_time,
     438             :                        long              broadcast_start_time,
     439           0 :                        peer_t const *    reward_leader ) {
     440           0 :   fd_event_alpenglow_vote_t ev;
     441           0 :   fd_memset( &ev, 0, FD_EVENT_ALPENGLOW_VOTE_PREFIX_SZ );
     442           0 :   ev.kind       = FD_EVENT_ALPENGLOW_VOTE_KIND_NOTAR+tag-FD_VOTE_SERDE_TAG_NOTAR;
     443           0 :   ev.voter_rank = USHORT_MAX;
     444             : 
     445           0 :   if( FD_LIKELY( vote ) ) {
     446           0 :     ev.slot       = fd_vote_slot( vote );
     447           0 :     ev.voter_rank = fd_vote_rank( vote );
     448           0 :     fd_block_hash_t const * block_hash = fd_vote_block_hash( vote );
     449           0 :     if( FD_LIKELY( block_hash ) ) memcpy( ev.block_id, block_hash, sizeof(fd_block_hash_t) );
     450           0 :   }
     451             : 
     452           0 :   fd_pubkey_t const * id_key = conn ? fd_quic_conn_get_context( conn ) : &ctx->id_key;
     453           0 :   FD_STORE( ushort, ev.received_from_ip+10, (ushort)0xffff );
     454           0 :   FD_STORE( uint,   ev.received_from_ip+12, conn ? conn->peer[ 0 ].ip_addr : ctx->src_ip_addr );
     455           0 :   if( FD_LIKELY( id_key ) ) memcpy( ev.received_from_identity, id_key->uc, sizeof(fd_pubkey_t) );
     456             : 
     457           0 :   ev.our_vote                           = !conn;
     458           0 :   ev.reason                             = reason;
     459           0 :   ev.processing_result                  = result;
     460           0 :   ev.quorum_reached_safe_to_notar       = fd_uchar_extract_bit( quorum_reached, FD_VOTOR_POOL_QUORUM_REACHED_SAFE_TO_NOTAR  );
     461           0 :   ev.quorum_reached_safe_to_skip        = fd_uchar_extract_bit( quorum_reached, FD_VOTOR_POOL_QUORUM_REACHED_SAFE_TO_SKIP   );
     462           0 :   ev.quorum_reached_final_cert          = fd_uchar_extract_bit( quorum_reached, FD_VOTOR_POOL_QUORUM_REACHED_FINAL          );
     463           0 :   ev.quorum_reached_fast_final_cert     = fd_uchar_extract_bit( quorum_reached, FD_VOTOR_POOL_QUORUM_REACHED_FAST_FINAL     );
     464           0 :   ev.quorum_reached_notar_cert          = fd_uchar_extract_bit( quorum_reached, FD_VOTOR_POOL_QUORUM_REACHED_NOTAR          );
     465           0 :   ev.quorum_reached_notar_fallback_cert = fd_uchar_extract_bit( quorum_reached, FD_VOTOR_POOL_QUORUM_REACHED_NOTAR_FALLBACK );
     466           0 :   ev.quorum_reached_skip_cert           = fd_uchar_extract_bit( quorum_reached, FD_VOTOR_POOL_QUORUM_REACHED_SKIP           );
     467           0 :   ev.aggregation_start_time             = (ulong)fd_long_if( result==FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_ACCEPTED, aggregation_start_time, 0L );
     468           0 :   ev.broadcast_start_time               = (ulong)broadcast_start_time;
     469             : 
     470           0 :   if( FD_UNLIKELY( reason==FD_EVENT_ALPENGLOW_VOTE_REASON_REWARD_NO_CONNECTION ) ) {
     471           0 :     ulong                   reward_slot = ev.slot+FD_VOTOR_REWARD_SLOT_DELTA;
     472           0 :     fd_epoch_info_t const * reward_info = fd_ptr_if( reward_slot>=ctx->next_epoch_slot, ctx->next_epoch_info, fd_ptr_if( reward_slot>=ctx->curr_epoch_slot, ctx->curr_epoch_info, ctx->prev_epoch_info ) );
     473           0 :     ulong                   cnt         = reward_info ? reward_info->validator_cnt : 0UL;
     474           0 :     ushort                  rank        = fd_ushort_if( reward_slot>=ctx->next_epoch_slot, reward_leader->next_rank, fd_ushort_if( reward_slot>=ctx->curr_epoch_slot, reward_leader->curr_rank, reward_leader->prev_rank ) );
     475           0 :     contact_info_t const *  ci          = contact_infos_query( ctx->contact_infos, reward_leader->id_key, NULL );
     476           0 :     fd_memset( ev.broadcast_to, 0, cnt*sizeof(fd_event_alpenglow_vote_broadcast_to_t) );
     477           0 :     if( FD_LIKELY( rank<cnt ) ) memcpy( ev.broadcast_to[ rank ].identity, reward_leader->id_key.uc, sizeof(fd_pubkey_t) );
     478           0 :     if( FD_LIKELY( rank<cnt && ci ) ) {
     479           0 :       FD_STORE( ushort, ev.broadcast_to[ rank ].ip+10, (ushort)0xffff );
     480           0 :       FD_STORE( uint,   ev.broadcast_to[ rank ].ip+12, ci->ip4 );
     481           0 :       ev.broadcast_to[ rank ].port = ci->port;
     482           0 :     }
     483           0 :     ev.broadcast_to_cnt = cnt;
     484           0 :   }
     485             : 
     486           0 :   if( FD_UNLIKELY( !conn && reason!=FD_EVENT_ALPENGLOW_VOTE_REASON_REWARD_ACKED && reason!=FD_EVENT_ALPENGLOW_VOTE_REASON_REWARD_NO_CONNECTION ) ) {
     487           0 :     ulong                   rank_slot = fd_ulong_if( reason==FD_EVENT_ALPENGLOW_VOTE_REASON_REWARD, ev.slot+FD_VOTOR_REWARD_SLOT_DELTA, ev.slot );
     488           0 :     fd_epoch_info_t const * rank_info = fd_ptr_if( rank_slot>=ctx->next_epoch_slot, ctx->next_epoch_info, fd_ptr_if( rank_slot>=ctx->curr_epoch_slot, ctx->curr_epoch_info, ctx->prev_epoch_info ) );
     489           0 :     ulong                   cnt       = rank_info ? rank_info->validator_cnt : 0UL;
     490           0 :     fd_memset( ev.broadcast_to, 0, cnt*sizeof(fd_event_alpenglow_vote_broadcast_to_t) );
     491           0 :     for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); slot++ ) {
     492           0 :       peer_t const * peer = &ctx->peers[ slot ];
     493           0 :       if( FD_LIKELY(    peers_key_inval( peer->id_key )
     494           0 :                      || !peer->tx_conn
     495           0 :                      || peer->tx_conn->state!=FD_QUIC_CONN_STATE_ACTIVE
     496           0 :                      || (peer==reward_leader)!=(reason==FD_EVENT_ALPENGLOW_VOTE_REASON_REWARD) ) ) continue;
     497           0 :       ushort rank = fd_ushort_if( rank_slot>=ctx->next_epoch_slot, peer->next_rank, fd_ushort_if( rank_slot>=ctx->curr_epoch_slot, peer->curr_rank, peer->prev_rank ) );
     498           0 :       if( FD_UNLIKELY( rank>=cnt ) ) continue;
     499           0 :       memcpy( ev.broadcast_to[ rank ].identity, peer->id_key.uc, sizeof(fd_pubkey_t) );
     500           0 :       FD_STORE( ushort, ev.broadcast_to[ rank ].ip+10, (ushort)0xffff );
     501           0 :       FD_STORE( uint,   ev.broadcast_to[ rank ].ip+12, peer->tx_conn->peer[ 0 ].ip_addr );
     502           0 :       ev.broadcast_to[ rank ].port = peer->tx_conn->peer[ 0 ].udp_port;
     503           0 :     }
     504           0 :     ev.broadcast_to_cnt = cnt;
     505           0 :   }
     506             : 
     507           0 :   fd_event_report_alpenglow_vote( &ev );
     508           0 : }
     509             : 
     510             : static void
     511             : report_alpenglow_cert( fd_votor_tile_t * ctx,
     512             :                        fd_quic_conn_t *  conn,
     513             :                        fd_cert_t const * cert,
     514             :                        uchar             tag,
     515             :                        int               result,
     516             :                        long              verify_start_time,
     517           0 :                        long              broadcast_start_time ) {
     518           0 :   fd_event_alpenglow_cert_t ev;
     519           0 :   fd_memset( &ev, 0, FD_EVENT_ALPENGLOW_CERT_PREFIX_SZ );
     520           0 :   ev.kind = FD_EVENT_ALPENGLOW_CERT_KIND_FINAL+tag-FD_CERT_SERDE_TAG_FINAL;
     521             : 
     522           0 :   if( FD_LIKELY( cert ) ) {
     523           0 :     ev.slot = fd_cert_slot( cert );
     524           0 :     fd_block_hash_t const * block_hash = fd_cert_block_hash( cert );
     525           0 :     if( FD_LIKELY( block_hash ) ) memcpy( ev.block_id, block_hash, sizeof(fd_block_hash_t) );
     526           0 :     fd_bls_agg_t const * agg;
     527           0 :     fd_bls_agg_t const * agg2 = NULL;
     528           0 :     switch( cert->kind ) {
     529           0 :     case FD_CERT_KIND_FINAL:          agg = &cert->final.agg;                                                                 break;
     530           0 :     case FD_CERT_KIND_FAST_FINAL:     agg = &cert->fast_final.agg;                                                            break;
     531           0 :     case FD_CERT_KIND_NOTAR:          agg = &cert->notar.agg;                                                                 break;
     532           0 :     case FD_CERT_KIND_NOTAR_FALLBACK: agg = &cert->notar_fallback.agg_notar; agg2 = &cert->notar_fallback.agg_notar_fallback; break;
     533           0 :     case FD_CERT_KIND_SKIP:           agg = &cert->skip.agg_skip;            agg2 = &cert->skip.agg_skip_fallback;            break;
     534           0 :     default:                          FD_LOG_CRIT(( "unreachable" ));
     535           0 :     }
     536           0 :     for( ulong rank = fd_bls_set_const_iter_init( agg->set );
     537           0 :                      !fd_bls_set_const_iter_done( rank );
     538           0 :                rank = fd_bls_set_const_iter_next( agg->set, rank ) ) {
     539           0 :       ev.voters[ rank>>3 ] = (uchar)( ev.voters[ rank>>3 ] | (1U<<(rank&7UL)) );
     540           0 :       ev.voters_len        = (rank>>3)+1UL;
     541           0 :     }
     542           0 :     if( FD_UNLIKELY( agg2 ) ) {
     543           0 :       for( ulong rank = fd_bls_set_const_iter_init( agg2->set );
     544           0 :                        !fd_bls_set_const_iter_done( rank );
     545           0 :                  rank = fd_bls_set_const_iter_next( agg2->set, rank ) ) {
     546           0 :         ev.fallback_voters[ rank>>3 ] = (uchar)( ev.fallback_voters[ rank>>3 ] | (1U<<(rank&7UL)) );
     547           0 :         ev.fallback_voters_len        = (rank>>3)+1UL;
     548           0 :       }
     549           0 :     }
     550           0 :   }
     551             : 
     552           0 :   fd_pubkey_t const * id_key = conn ? fd_quic_conn_get_context( conn ) : &ctx->id_key;
     553           0 :   FD_STORE( ushort, ev.relayer_ip+10, (ushort)0xffff );
     554           0 :   FD_STORE( uint,   ev.relayer_ip+12, conn ? conn->peer[ 0 ].ip_addr : ctx->src_ip_addr );
     555           0 :   if( FD_LIKELY( id_key ) ) memcpy( ev.relayer_identity, id_key->uc, sizeof(fd_pubkey_t) );
     556             : 
     557           0 :   ev.our_cert             = !conn;
     558           0 :   ev.processing_result    = result;
     559           0 :   ev.verify_start_time    = (ulong)verify_start_time;
     560           0 :   ev.broadcast_start_time = (ulong)broadcast_start_time;
     561             : 
     562           0 :   if( FD_UNLIKELY( !conn ) ) {
     563           0 :     fd_epoch_info_t const * epoch_info = fd_ptr_if( ev.slot>=ctx->next_epoch_slot, ctx->next_epoch_info, fd_ptr_if( ev.slot>=ctx->curr_epoch_slot, ctx->curr_epoch_info, ctx->prev_epoch_info ) );
     564           0 :     ulong                   cnt        = epoch_info ? epoch_info->validator_cnt : 0UL;
     565           0 :     fd_memset( ev.broadcast_to, 0, cnt*sizeof(fd_event_alpenglow_cert_broadcast_to_t) );
     566           0 :     for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); slot++ ) {
     567           0 :       peer_t const * peer = &ctx->peers[ slot ];
     568           0 :       if( FD_LIKELY( peers_key_inval( peer->id_key ) || !peer->tx_conn || peer->tx_conn->state!=FD_QUIC_CONN_STATE_ACTIVE ) ) continue;
     569           0 :       ushort rank = fd_ushort_if( ev.slot>=ctx->next_epoch_slot, peer->next_rank, fd_ushort_if( ev.slot>=ctx->curr_epoch_slot, peer->curr_rank, peer->prev_rank ) );
     570           0 :       if( FD_UNLIKELY( rank>=cnt ) ) continue;
     571           0 :       memcpy( ev.broadcast_to[ rank ].identity, peer->id_key.uc, sizeof(fd_pubkey_t) );
     572           0 :       FD_STORE( ushort, ev.broadcast_to[ rank ].ip+10, (ushort)0xffff );
     573           0 :       FD_STORE( uint,   ev.broadcast_to[ rank ].ip+12, peer->tx_conn->peer[ 0 ].ip_addr );
     574           0 :       ev.broadcast_to[ rank ].port = peer->tx_conn->peer[ 0 ].udp_port;
     575           0 :     }
     576           0 :     ev.broadcast_to_cnt = cnt;
     577           0 :   }
     578             : 
     579           0 :   fd_event_report_alpenglow_cert( &ev );
     580           0 : }
     581             : 
     582             : static void
     583             : ban_peer( fd_votor_tile_t * ctx,
     584             :           peer_t *          peer,
     585           0 :           long              now ) {
     586           0 :   FD_BASE58_ENCODE_32_BYTES( peer->id_key.uc, id_key_b58 );
     587           0 :   FD_LOG_WARNING(( "banning peer %s", id_key_b58 ));
     588           0 :   for( ulong i=0UL; i<QUIC_SERVER_CONN_PER_PEER_MAX; i++ ) {
     589           0 :     if( FD_UNLIKELY( !peer->rx_conn[ i ] ) ) continue;
     590           0 :     fd_quic_conn_set_context( peer->rx_conn[ i ], NULL );
     591           0 :     fd_quic_conn_close( peer->rx_conn[ i ], QUIC_CLOSE_CODE_BANNED );
     592           0 :     peer->rx_conn[ i ] = NULL;
     593           0 :   }
     594           0 :   if( FD_LIKELY( peer->tx_conn ) ) {
     595           0 :     fd_quic_conn_set_context( peer->tx_conn, NULL );
     596           0 :     fd_quic_conn_close( peer->tx_conn, QUIC_CLOSE_CODE_BANNED );
     597           0 :     peer->tx_conn = NULL;
     598           0 :   }
     599           0 :   peer->ban_ts = now;
     600           0 :   if( FD_LIKELY( !peer->reconn_pending ) ) { /* redial outbound when the ban lapses */
     601           0 :     reconn_t reconn = { .timeout = now+QUIC_BAN_TIMEOUT_NS, .id_key = peer->id_key };
     602           0 :     reconn_prq_insert( ctx->reconn_prq, &reconn );
     603           0 :     peer->reconn_pending = 1;
     604           0 :   }
     605           0 : }
     606             : 
     607             : static void
     608             : ban_bad_ranks( fd_votor_tile_t *    ctx,
     609             :                fd_bls_set_t const * bad,
     610           0 :                ulong                slot_as_of ) {
     611           0 :   fd_epoch_info_t const * epoch_info = fd_ptr_if( slot_as_of>=ctx->next_epoch_slot, ctx->next_epoch_info, fd_ptr_if( slot_as_of>=ctx->curr_epoch_slot, ctx->curr_epoch_info, ctx->prev_epoch_info ) );
     612           0 :   if( FD_UNLIKELY( !epoch_info ) ) return;
     613           0 :   long now = fd_clock_tile_now( ctx->clock );
     614           0 :   for( ulong rank = fd_bls_set_const_iter_init( bad );
     615           0 :                    !fd_bls_set_const_iter_done( rank );
     616           0 :              rank = fd_bls_set_const_iter_next( bad, rank ) ) {
     617           0 :     fd_pubkey_t id_key; memcpy( id_key.uc, epoch_info->validators[ rank ].id_key, sizeof(fd_pubkey_t) );
     618           0 :     peer_t * peer = peers_query( ctx->peers, id_key, NULL );
     619           0 :     if( FD_UNLIKELY( !peer || now<peer->ban_ts+QUIC_BAN_TIMEOUT_NS ) ) continue;
     620           0 :     ban_peer( ctx, peer, now );
     621           0 :   }
     622           0 : }
     623             : 
     624             : static void
     625             : quic_client_connect( fd_votor_tile_t *      ctx,
     626             :                      peer_t *               peer,
     627             :                      contact_info_t const * ci,
     628           0 :                      long                   now ) {
     629           0 :   if( FD_UNLIKELY( ctx->keyswitch_state ) ) return; /* halted for an identity switch, and the TLS handshake must sign */
     630           0 :   peer_t const * self = peers_query( ctx->peers, ctx->id_key, NULL );
     631           0 :   if( FD_UNLIKELY( !self || peer==self ) ) return;
     632           0 :   if( FD_UNLIKELY( self->curr_rank==USHORT_MAX ) ) { /* not voting yet: only connect ahead, within QUIC_CLIENT_CONN_AHEAD_NS of our first ranked epoch */
     633           0 :     ulong root = fd_votor_pool_finalized_slot( ctx->pool );
     634           0 :     if( FD_UNLIKELY( self->next_rank==USHORT_MAX || root==ULONG_MAX )                                                     ) return;
     635           0 :     if( FD_UNLIKELY( root<ctx->next_epoch_slot && (long)( ctx->next_epoch_slot-root )*ctx->ns_per_slot>QUIC_CLIENT_CONN_AHEAD_NS ) ) return;
     636           0 :   }
     637           0 :   if( FD_UNLIKELY( peer->prev_rank==USHORT_MAX && peer->curr_rank==USHORT_MAX && peer->next_rank==USHORT_MAX ) ) return;
     638           0 :   if( FD_UNLIKELY( peer->tx_conn ) ) return;
     639           0 :   if( FD_UNLIKELY( now<peer->ban_ts+QUIC_BAN_TIMEOUT_NS ) ) { /* redial when the ban lapses, nothing else would */
     640           0 :     if( FD_LIKELY( !peer->reconn_pending ) ) {
     641           0 :       reconn_t reconn = { .timeout = peer->ban_ts+QUIC_BAN_TIMEOUT_NS, .id_key = peer->id_key };
     642           0 :       reconn_prq_insert( ctx->reconn_prq, &reconn );
     643           0 :       peer->reconn_pending = 1;
     644           0 :     }
     645           0 :     return;
     646           0 :   }
     647             : 
     648           0 :   fd_quic_conn_t * conn = fd_quic_connect( ctx->quic_client, ci->ip4, ci->port, ctx->src_ip_addr, ctx->quic_client_listen_port, now );
     649           0 :   if( FD_UNLIKELY( !conn ) ) {
     650           0 :     if( FD_LIKELY( !peer->reconn_pending ) ) {
     651           0 :       reconn_t reconn = { .timeout = now+QUIC_CLIENT_CONN_BACKOFF_MIN_NS, .id_key = peer->id_key };
     652           0 :       reconn_prq_insert( ctx->reconn_prq, &reconn );
     653           0 :       peer->reconn_pending = 1;
     654           0 :     }
     655           0 :     return;
     656           0 :   }
     657             : 
     658           0 :   memcpy( conn->tls_hs->hs.cli.server_pubkey, peer->id_key.uc, sizeof(fd_pubkey_t) ); /* fail the handshake before authenticating to whoever else holds the peer's address */
     659           0 :   conn->tls_hs->hs.cli.server_pubkey_len = sizeof(fd_pubkey_t);
     660           0 :   conn->tls_hs->hs.cli.server_pubkey_pin = 1;
     661             : 
     662           0 :   peer->conn_ts = now;
     663           0 :   ctx->client_peer_id_keys[ conn->conn_idx ] = peer->id_key;
     664           0 :   fd_quic_conn_set_context( conn, &ctx->client_peer_id_keys[ conn->conn_idx ] );
     665           0 :   peer->tx_conn = conn;
     666           0 :   for( ulong i=0UL; i<REWARD_VOTE_MAX; i++ ) if( ctx->reward_votes[ i ].conn==conn ) ctx->reward_votes[ i ].conn = NULL;
     667           0 : }
     668             : 
     669             : static ulong
     670             : quic_client_datagram_tx( fd_votor_tile_t *   ctx,
     671             :                          fd_stem_context_t * stem,
     672             :                          fd_quic_conn_t *    conn,
     673             :                          uchar const *       buf,
     674           0 :                          ulong               buf_sz ) {
     675           0 :   uchar * packet_l2 = fd_chunk_to_laddr( ctx->net_out_mem, ctx->net_out_chunk );
     676           0 :   uchar * payload   = packet_l2 + sizeof(fd_ip4_udp_hdrs_t);
     677             : 
     678           0 :   ulong pkt_num;
     679           0 :   ulong pkt_sz = fd_quic_conn_tx_dgram( conn, payload, FD_NET_MTU-sizeof(fd_ip4_udp_hdrs_t), buf, buf_sz, &pkt_num );
     680           0 :   if( FD_UNLIKELY( !pkt_sz ) ) return ULONG_MAX;
     681             : 
     682           0 :   fd_ip4_udp_hdrs_t * hdr = (fd_ip4_udp_hdrs_t *)fd_type_pun( packet_l2 );
     683           0 :   *hdr = *ctx->hdr;
     684             : 
     685           0 :   hdr->ip4->daddr       = conn->peer[ 0 ].ip_addr;
     686           0 :   hdr->ip4->net_tot_len = fd_ushort_bswap( (ushort)( pkt_sz+sizeof(fd_ip4_hdr_t)+sizeof(fd_udp_hdr_t) ) );
     687           0 :   hdr->ip4->net_id      = fd_ushort_bswap( ctx->net_id++ );
     688           0 :   hdr->ip4->check       = 0;
     689           0 :   hdr->ip4->check       = fd_ip4_hdr_check_fast( hdr->ip4 );
     690             : 
     691           0 :   hdr->udp->net_dport = fd_ushort_bswap( conn->peer[ 0 ].udp_port );
     692           0 :   hdr->udp->net_len   = fd_ushort_bswap( (ushort)( pkt_sz+sizeof(fd_udp_hdr_t) ) );
     693           0 :   hdr->udp->check     = (ushort)0;
     694             : 
     695           0 :   uint  ip_dst = hdr->ip4->daddr;
     696           0 :   ulong sig    = fd_disco_netmux_sig( ip_dst, 0U, ip_dst, DST_PROTO_OUTGOING, FD_NETMUX_SIG_MIN_HDR_SZ );
     697           0 :   ulong sz_l2  = sizeof(fd_ip4_udp_hdrs_t) + pkt_sz;
     698           0 :   fd_stem_publish( stem, OUT_IDX_NET, sig, ctx->net_out_chunk, sz_l2, fd_frag_meta_ctl( 0UL, 1, 1, 0 ), 0L, 0L );
     699           0 :   ctx->net_out_chunk = fd_dcache_compact_next( ctx->net_out_chunk, FD_NET_MTU, ctx->net_out_chunk0, ctx->net_out_wmark );
     700           0 :   ctx->quic_client->metrics.net_tx_pkt_cnt++; /* bypasses fd_quic's aio send, which counts the rest */
     701           0 :   ctx->quic_client->metrics.net_tx_byte_cnt += sz_l2-sizeof(fd_eth_hdr_t); /* IP bytes, as fd_quic counts */
     702           0 :   return pkt_num;
     703           0 : }
     704             : 
     705             : /* QUIC callback */
     706             : 
     707             : static void
     708             : quic_sign( void *      signer_ctx,
     709             :            uchar       sig[ static FD_ED25519_SIG_SZ ],
     710           0 :            uchar const msg[ static FD_TLS_CV_SIGN_SZ ] ) {
     711           0 :   fd_votor_tile_t * ctx = signer_ctx;
     712           0 :   fd_keyguard_client_sign( ctx->keyguard_client, sig, msg, FD_TLS_CV_SIGN_SZ, FD_KEYGUARD_SIGN_TYPE_ED25519 );
     713           0 : }
     714             : 
     715             : /* QUIC callback */
     716             : 
     717             : static int
     718             : quic_aio_tx( void *                    _ctx,
     719             :              fd_aio_pkt_info_t const * batch,
     720             :              ulong                     batch_cnt,
     721             :              ulong *                   opt_batch_idx,
     722           0 :              int                       flush ) {
     723           0 :   (void)flush;
     724             : 
     725           0 :   fd_votor_tile_t * ctx = _ctx;
     726             : 
     727           0 :   for( ulong i=0UL; i<batch_cnt; i++ ) {
     728           0 :     if( FD_UNLIKELY( ctx->net_tx_cnt==FD_VOTOR_NET_BURST ) ) {
     729           0 :       if( FD_LIKELY( opt_batch_idx ) ) *opt_batch_idx = i;
     730           0 :       return FD_AIO_ERR_AGAIN;
     731           0 :     }
     732           0 :     if( FD_UNLIKELY( batch[ i ].buf_sz<FD_NETMUX_SIG_MIN_HDR_SZ ) ) continue;
     733             : 
     734           0 :     ulong const sz_l2 = sizeof(fd_eth_hdr_t) + batch[ i ].buf_sz;
     735           0 :     if( FD_UNLIKELY( sz_l2>FD_ETH_PAYLOAD_MAX ) ) continue;
     736             : 
     737           0 :     uint const ip_dst = FD_LOAD( uint, batch[ i ].buf+offsetof( fd_ip4_hdr_t, daddr_c ) );
     738           0 :     uchar * packet_l2 = fd_chunk_to_laddr( ctx->net_out_mem, ctx->net_out_chunk );
     739           0 :     uchar * packet_l3 = packet_l2 + sizeof(fd_eth_hdr_t);
     740           0 :     memset( packet_l2, 0, 12 );
     741           0 :     FD_STORE( ushort, packet_l2+offsetof( fd_eth_hdr_t, net_type ), fd_ushort_bswap( FD_ETH_HDR_TYPE_IP ) );
     742           0 :     fd_memcpy( packet_l3, batch[ i ].buf, batch[ i ].buf_sz );
     743             : 
     744           0 :     ctx->net_tx[ ctx->net_tx_cnt ].chunk = ctx->net_out_chunk;
     745           0 :     ctx->net_tx[ ctx->net_tx_cnt ].sz    = sz_l2;
     746           0 :     ctx->net_tx[ ctx->net_tx_cnt ].sig   = fd_disco_netmux_sig( ip_dst, 0U, ip_dst, DST_PROTO_OUTGOING, FD_NETMUX_SIG_MIN_HDR_SZ );
     747           0 :     ctx->net_tx_cnt++;
     748             : 
     749           0 :     ctx->net_out_chunk = fd_dcache_compact_next( ctx->net_out_chunk, FD_NET_MTU, ctx->net_out_chunk0, ctx->net_out_wmark );
     750           0 :   }
     751             : 
     752           0 :   if( FD_LIKELY( opt_batch_idx ) ) *opt_batch_idx = batch_cnt;
     753             : 
     754           0 :   return FD_AIO_SUCCESS;
     755           0 : }
     756             : 
     757             : /* QUIC callback */
     758             : 
     759             : static void
     760             : quic_client_conn_final( fd_quic_conn_t * conn,
     761           0 :                         void *           quic_ctx ) {
     762           0 :   fd_votor_tile_t *   ctx    = quic_ctx;
     763           0 :   fd_pubkey_t const * id_key = fd_quic_conn_get_context( conn ); /* NULL for conns we closed ourselves, which are not reconnected */
     764           0 :   if( FD_UNLIKELY( !id_key ) ) return;
     765           0 :   peer_t * peer = peers_query( ctx->peers, *id_key, NULL );
     766           0 :   if( FD_UNLIKELY( !peer ) ) return;
     767             : 
     768           0 :   long now = fd_clock_tile_now( ctx->clock );
     769           0 :   long pto = (long)( conn->rtt->smoothed_rtt + fmaxf( 4.0f*conn->rtt->var_rtt, (float)QUIC_K_GRANULARITY_NS ) + conn->peer_max_ack_delay_ns ); /* RFC 9002 PTO */
     770           0 :   peer->tx_conn      = NULL;
     771           0 :   peer->conn_backoff = fd_long_min( fd_long_max( 2L*peer->conn_backoff, pto ), QUIC_CLIENT_CONN_BACKOFF_MAX_NS );
     772           0 :   peer->conn_ts      = now;
     773           0 :   if( FD_LIKELY( !peer->reconn_pending ) ) {
     774           0 :     reconn_t reconn = { .timeout = now+peer->conn_backoff, .id_key = peer->id_key };
     775           0 :     reconn_prq_insert( ctx->reconn_prq, &reconn );
     776           0 :     peer->reconn_pending = 1;
     777           0 :   }
     778           0 : }
     779             : 
     780             : /* QUIC callback */
     781             : 
     782             : static void
     783             : quic_client_conn_hs_complete( fd_quic_conn_t * conn,
     784           0 :                               void *           quic_ctx ) {
     785           0 :   fd_votor_tile_t *   ctx    = quic_ctx;
     786           0 :   fd_pubkey_t const * id_key = fd_quic_conn_get_context( conn );
     787           0 :   if( FD_UNLIKELY( !id_key ) ) return;
     788             : 
     789           0 :   if( FD_LIKELY( !conn->tls_hs || memcmp( conn->tls_hs->hs.cli.server_pubkey, id_key->uc, sizeof(fd_pubkey_t) ) ) ) {
     790           0 :     fd_quic_conn_close( conn, QUIC_CLOSE_CODE_INVALID_IDENTITY );
     791           0 :     return;
     792           0 :   }
     793             : 
     794           0 :   peer_t * peer = peers_query( ctx->peers, *id_key, NULL );
     795           0 :   if( FD_LIKELY( peer ) ) peer->conn_backoff = 0L;
     796           0 : }
     797             : 
     798             : /* QUIC callback */
     799             : 
     800             : static void
     801             : quic_client_ack_range( fd_quic_conn_t * conn,
     802             :                        ulong            pkt_num_lo,
     803             :                        ulong            pkt_num_hi,
     804           0 :                        void *           quic_ctx ) {
     805           0 :   fd_votor_tile_t * ctx = quic_ctx;
     806           0 :   for( ulong i=0UL; i<REWARD_VOTE_MAX; i++ ) {
     807           0 :     reward_vote_t * rv = &ctx->reward_votes[ i ];
     808           0 :     if( FD_LIKELY( rv->slot==ULONG_MAX || rv->conn!=conn ) ) continue;
     809           0 :     for( ulong j=0UL; j<fd_ulong_min( rv->tx_cnt, REWARD_VOTE_TX_MAX ); j++ ) {
     810           0 :       if( FD_LIKELY(    rv->pkt_num[ j ]<pkt_num_lo
     811           0 :                      || rv->pkt_num[ j ]>pkt_num_hi ) ) continue;
     812           0 :       report_alpenglow_vote( ctx, NULL, &rv->vote, (uchar)( FD_VOTE_SERDE_TAG_NOTAR+rv->vote.kind ), FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_ACCEPTED, 0, FD_EVENT_ALPENGLOW_VOTE_REASON_REWARD_ACKED, 0L, 0L, NULL );
     813           0 :       rv->slot = ULONG_MAX;
     814           0 :       break;
     815           0 :     }
     816           0 :   }
     817           0 : }
     818             : 
     819             : /* QUIC callback */
     820             : 
     821             : static void
     822             : quic_server_conn_new( fd_quic_conn_t * conn,
     823           0 :                       void *           _ctx ) {
     824           0 :   if( FD_UNLIKELY( !conn->tls_hs ) ) return; /* no authenticated identity, so no votes will be attributed */
     825           0 :   fd_pubkey_t const * id_key = (fd_pubkey_t const *)fd_type_pun_const( conn->tls_hs->hs.srv.client_pubkey );
     826             : 
     827           0 :   fd_votor_tile_t * ctx  = _ctx;
     828           0 :   peer_t *          peer = peers_query( ctx->peers, *id_key, NULL );
     829           0 :   if( FD_LIKELY( ctx->curr_epoch_info ) && FD_UNLIKELY( !peer ) ) {
     830           0 :     fd_quic_conn_close( conn, QUIC_CLOSE_CODE_NOT_ADMITTED );
     831           0 :     return;
     832           0 :   }
     833           0 :   if( FD_UNLIKELY( peer && fd_clock_tile_now( ctx->clock )<peer->ban_ts+QUIC_BAN_TIMEOUT_NS ) ) {
     834           0 :     fd_quic_conn_close( conn, QUIC_CLOSE_CODE_BANNED );
     835           0 :     return;
     836           0 :   }
     837           0 :   ulong idx = 0UL;
     838           0 :   while( peer && idx<QUIC_SERVER_CONN_PER_PEER_MAX && peer->rx_conn[ idx ] ) idx++;
     839           0 :   if( FD_UNLIKELY( idx==QUIC_SERVER_CONN_PER_PEER_MAX ) ) { /* never the incumbents: another node's contact info can make the peer dial us */
     840           0 :     fd_quic_conn_close( conn, QUIC_CLOSE_CODE_TOO_MANY_CONNECTIONS );
     841           0 :     return;
     842           0 :   }
     843           0 :   ctx->server_peer_id_keys[ conn->conn_idx ] = *id_key;
     844           0 :   fd_quic_conn_set_context( conn, &ctx->server_peer_id_keys[ conn->conn_idx ] );
     845           0 :   if( FD_LIKELY( peer ) ) peer->rx_conn[ idx ] = conn;
     846           0 : }
     847             : 
     848             : /* QUIC callback */
     849             : 
     850             : static void
     851             : quic_server_conn_final( fd_quic_conn_t * conn,
     852           0 :                         void *           _ctx ) {
     853           0 :   fd_votor_tile_t *   ctx    = _ctx;
     854           0 :   fd_pubkey_t const * id_key = fd_quic_conn_get_context( conn );
     855           0 :   fd_quic_conn_set_context( conn, NULL ); /* a reused conn slot must not carry this peer's key */
     856           0 :   if( FD_UNLIKELY( !id_key ) ) return;
     857           0 :   peer_t * peer = peers_query( ctx->peers, *id_key, NULL );
     858           0 :   if( FD_UNLIKELY( !peer ) ) return;
     859           0 :   for( ulong i=0UL; i<QUIC_SERVER_CONN_PER_PEER_MAX; i++ ) if( FD_UNLIKELY( peer->rx_conn[ i ]==conn ) ) peer->rx_conn[ i ] = NULL;
     860           0 : }
     861             : 
     862             : /* QUIC callback */
     863             : 
     864             : static void
     865             : quic_server_datagram_rx( fd_quic_conn_t * conn,
     866             :                          uchar const *    data,
     867             :                          ulong            data_sz,
     868           0 :                          void *           _ctx ) {
     869             : 
     870           0 :   fd_votor_tile_t * ctx = _ctx;
     871           0 :   if( FD_UNLIKELY( !ctx->init  ) ) { ctx->metrics.datagram_rx[ FD_METRICS_ENUM_DATAGRAM_RX_RESULT_V_NOT_READY_IDX ]++; return; }
     872           0 :   if( FD_UNLIKELY( conn->state!=FD_QUIC_CONN_STATE_ACTIVE ) ) { ctx->metrics.datagram_rx[ FD_METRICS_ENUM_DATAGRAM_RX_RESULT_V_NOT_ADMITTED_IDX ]++; return; }
     873           0 :   if( FD_UNLIKELY( data_sz<2UL ) ) { ctx->metrics.datagram_rx[ FD_METRICS_ENUM_DATAGRAM_RX_RESULT_V_TOO_SMALL_IDX ]++; return; }
     874           0 :   uchar kind = data[ 1 ];
     875             : 
     876           0 :   switch( kind ) {
     877           0 :   case FD_VOTE_SERDE_TAG_NOTAR:
     878           0 :   case FD_VOTE_SERDE_TAG_FINAL:
     879           0 :   case FD_VOTE_SERDE_TAG_SKIP:
     880           0 :   case FD_VOTE_SERDE_TAG_NOTAR_FALLBACK:
     881           0 :   case FD_VOTE_SERDE_TAG_SKIP_FALLBACK: {
     882           0 :     ctx->metrics.datagram_rx[ FD_METRICS_ENUM_DATAGRAM_RX_RESULT_V_VOTE_IDX ]++;
     883           0 :     fd_pubkey_t const * id_key = fd_quic_conn_get_context( conn );
     884           0 :     if( FD_UNLIKELY( !id_key ) ) { ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_UNKNOWN_SIGNER_IDX ]++; report_alpenglow_vote( ctx, conn, NULL, kind, FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_UNKNOWN_PEER, 0, FD_EVENT_ALPENGLOW_VOTE_REASON_NOT_OUR_VOTE, 0L, 0L, NULL ); return; }
     885           0 :     peer_t * peer = peers_query( ctx->peers, *id_key, NULL );
     886           0 :     if( FD_UNLIKELY( !peer ) ) { ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_NOT_PEER_IDX ]++; report_alpenglow_vote( ctx, conn, NULL, kind, FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_UNKNOWN_PEER, 0, FD_EVENT_ALPENGLOW_VOTE_REASON_NOT_OUR_VOTE, 0L, 0L, NULL ); return; }
     887           0 :     if( FD_UNLIKELY( fd_clock_tile_now( ctx->clock )<peer->ban_ts+QUIC_BAN_TIMEOUT_NS ) ) {
     888           0 :       ctx->metrics.vote_rx[FD_METRICS_ENUM_VOTE_RX_RESULT_V_BANNED_IDX]++;
     889           0 :       report_alpenglow_vote( ctx, conn, NULL, kind, FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_BANNED_PEER, 0, FD_EVENT_ALPENGLOW_VOTE_REASON_NOT_OUR_VOTE, 0L, 0L, NULL );
     890           0 :       fd_quic_conn_close( conn, QUIC_CLOSE_CODE_BANNED );
     891           0 :       return;
     892           0 :     }
     893             : 
     894           0 :     int err = fd_vote_de( &ctx->scratch.vote, data, data_sz );
     895           0 :     switch( err ) {
     896           0 :     case FD_VOTE_DE_SUCCESS:   break;
     897           0 :     case FD_VOTE_DE_ERR_SZ:    ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_BAD_SIZE_IDX         ]++;                                              return;
     898           0 :     case FD_VOTE_DE_ERR_INVAL: ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_BAD_ENCODING_IDX     ]++;                                              return;
     899           0 :     case FD_VOTE_DE_ERR_SIG:   ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_SIGNATURE_FAILED_IDX ]++; ban_peer( ctx, peer, fd_clock_tile_now( ctx->clock ) ); return;
     900           0 :     default:                   FD_LOG_CRIT(( "unhandled fd_vote_de err %d", err ));
     901           0 :     }
     902           0 :     fd_vote_t * vote      = &ctx->scratch.vote;
     903           0 :     ulong       vote_slot = fd_vote_slot( vote );
     904           0 :     ushort      rank      = fd_ushort_if( vote_slot>=ctx->next_epoch_slot, peer->next_rank, fd_ushort_if( vote_slot>=ctx->curr_epoch_slot, peer->curr_rank, peer->prev_rank ) );
     905           0 :     switch( vote->kind ) {
     906           0 :     case FD_VOTE_KIND_NOTAR:          vote->notar.rank          = rank; break;
     907           0 :     case FD_VOTE_KIND_FINAL:          vote->final.rank          = rank; break;
     908           0 :     case FD_VOTE_KIND_SKIP:           vote->skip.rank           = rank; break;
     909           0 :     case FD_VOTE_KIND_NOTAR_FALLBACK: vote->notar_fallback.rank = rank; break;
     910           0 :     case FD_VOTE_KIND_SKIP_FALLBACK:  vote->skip_fallback.rank  = rank; break;
     911           0 :     default:                          FD_LOG_CRIT(( "unreachable" ));
     912           0 :     }
     913           0 :     if( FD_UNLIKELY( fd_vote_shred_version( vote )!=ctx->shred_version ) ) { ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_SHRED_VERSION_MISMATCHED_IDX ]++; report_alpenglow_vote( ctx, conn, vote, kind, FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_SHRED_VERSION_MISMATCH, 0, FD_EVENT_ALPENGLOW_VOTE_REASON_NOT_OUR_VOTE, 0L, 0L, NULL ); return; }
     914           0 :     fd_block_hash_t const * block_hash = fd_vote_block_hash( vote );
     915           0 :     if( FD_UNLIKELY( block_hash && !memcmp( block_hash, &fd_block_hash_null, sizeof(fd_block_hash_t) ) ) ) { ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_NULL_BLOCK_HASH_IDX ]++; return; } /* null is never a valid block hash */
     916             : 
     917           0 :     if( FD_UNLIKELY( rank==USHORT_MAX ) ) { ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_UNRANKED_IDX ]++; report_alpenglow_vote( ctx, conn, vote, kind, FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_UNRANKED_PEER, 0, FD_EVENT_ALPENGLOW_VOTE_REASON_NOT_OUR_VOTE, 0L, 0L, NULL ); return; } /* peer is not ranked in their vote slot's epoch */
     918           0 :     if( FD_UNLIKELY( vote_slot>fd_ulong_max( fd_votor_pool_finalized_slot( ctx->pool ), ctx->highest_parent_ready_slot )+VOTE_TOO_NEW ) ) { ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_SLOT_OUT_OF_RANGE_IDX ]++; report_alpenglow_vote( ctx, conn, vote, kind, FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_SLOT_TOO_NEW, 0, FD_EVENT_ALPENGLOW_VOTE_REASON_NOT_OUR_VOTE, 0L, 0L, NULL ); return; }
     919             : 
     920           0 :     long  aggregation_start_time = fd_clock_tile_now( ctx->clock );
     921           0 :     uchar quorum_reached;
     922           0 :     err = fd_votor_pool_add_vote( ctx->pool, &ctx->scratch.vote, 0, ctx->scratch.bad, &quorum_reached );
     923           0 :     int result;
     924           0 :     switch( err ) {
     925           0 :     case FD_VOTOR_POOL_SUCCESS:                ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_SUCCESS_IDX           ]++; result = FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_ACCEPTED;                                                                                                                         break;
     926           0 :     case FD_VOTOR_POOL_ERR_SLOT_TOO_OLD:       ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_SLOT_OUT_OF_RANGE_IDX ]++; result = FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_SLOT_TOO_OLD;                                                                                                                    break;
     927           0 :     case FD_VOTOR_POOL_ERR_SLOT_TOO_NEW:       ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_SLOT_OUT_OF_RANGE_IDX ]++; result = FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_SLOT_TOO_NEW;                                                                                                                    break;
     928           0 :     case FD_VOTOR_POOL_ERR_DUPLICATE:          ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_DUPLICATE_IDX         ]++; result = FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_DUPLICATE;                                                                                                                        break;
     929           0 :     case FD_VOTOR_POOL_ERR_SLASHABLE:          ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_SLASHABLE_IDX         ]++; result = FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_SLASHABLE;                                                                                                                        break;
     930           0 :     case FD_VOTOR_POOL_ERR_VOTE_VERIFY:        ctx->metrics.vote_rx[ FD_METRICS_ENUM_VOTE_RX_RESULT_V_SIGNATURE_FAILED_IDX  ]++; ban_peer( ctx, peer, fd_clock_tile_now( ctx->clock ) );                                                                                                                       return;
     931           0 :     default:
     932           0 :       FD_LOG_CRIT(( "unhandled kind" ));
     933           0 :     }
     934           0 :     report_alpenglow_vote( ctx, conn, vote, kind, result, quorum_reached, FD_EVENT_ALPENGLOW_VOTE_REASON_NOT_OUR_VOTE, aggregation_start_time, 0L, NULL );
     935           0 :     if( FD_UNLIKELY( !fd_bls_set_is_null( ctx->scratch.bad ) ) ) ban_bad_ranks( ctx, ctx->scratch.bad, vote_slot );
     936           0 :     reward_cert_t * rc = &ctx->reward_certs[ vote_slot%FD_VOTOR_SLOTS_PER_WINDOW ];
     937           0 :     if( FD_UNLIKELY( err==FD_VOTOR_POOL_SUCCESS && rc->slot==vote_slot && ( vote->kind==FD_VOTE_KIND_NOTAR || vote->kind==FD_VOTE_KIND_SKIP ) ) ) rc->dirty = 1;
     938           0 :     return;
     939           0 :   }
     940           0 :   case FD_CERT_SERDE_TAG_FINAL:
     941           0 :   case FD_CERT_SERDE_TAG_FAST_FINAL:
     942           0 :   case FD_CERT_SERDE_TAG_NOTAR:
     943           0 :   case FD_CERT_SERDE_TAG_NOTAR_FALLBACK:
     944           0 :   case FD_CERT_SERDE_TAG_SKIP: {
     945           0 :     ctx->metrics.datagram_rx[ FD_METRICS_ENUM_DATAGRAM_RX_RESULT_V_CERT_IDX ]++;
     946           0 :     fd_pubkey_t const * id_key = fd_quic_conn_get_context( conn );
     947           0 :     if( FD_UNLIKELY( !id_key ) ) { ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_UNKNOWN_SIGNER_IDX ]++; report_alpenglow_cert( ctx, conn, NULL, kind, FD_EVENT_ALPENGLOW_CERT_PROCESSING_RESULT_UNKNOWN_PEER, 0L, 0L ); return; }
     948           0 :     peer_t * peer = peers_query( ctx->peers, *id_key, NULL );
     949           0 :     if( FD_UNLIKELY( !peer ) ) { ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_NOT_PEER_IDX ]++; report_alpenglow_cert( ctx, conn, NULL, kind, FD_EVENT_ALPENGLOW_CERT_PROCESSING_RESULT_UNKNOWN_PEER, 0L, 0L ); return; }
     950           0 :     if( FD_UNLIKELY( fd_clock_tile_now( ctx->clock )<peer->ban_ts+QUIC_BAN_TIMEOUT_NS ) ) { ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_BANNED_IDX ]++; report_alpenglow_cert( ctx, conn, NULL, kind, FD_EVENT_ALPENGLOW_CERT_PROCESSING_RESULT_BANNED_PEER, 0L, 0L ); fd_quic_conn_close( conn, QUIC_CLOSE_CODE_BANNED ); return; }
     951             : 
     952           0 :     ulong bit_cnt;
     953           0 :     int   err = fd_cert_de( &ctx->scratch.cert, &bit_cnt, data, data_sz );
     954           0 :     if( FD_UNLIKELY( err ) ) {
     955           0 :       ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_BAD_SIZE_IDX     ] += (ulong)(err==FD_CERT_DE_ERR_SZ   );
     956           0 :       ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_BAD_ENCODING_IDX ] += (ulong)(err==FD_CERT_DE_ERR_INVAL);
     957           0 :       return;
     958           0 :     }
     959           0 :     fd_cert_t * cert = &ctx->scratch.cert;
     960           0 :     if( FD_UNLIKELY( fd_cert_shred_version( cert )!=ctx->shred_version ) ) { ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_SHRED_VERSION_MISMATCHED_IDX ]++; report_alpenglow_cert( ctx, conn, &ctx->scratch.cert, kind, FD_EVENT_ALPENGLOW_CERT_PROCESSING_RESULT_SHRED_VERSION_MISMATCH, 0L, 0L ); return; }
     961             : 
     962           0 :     ulong  cert_slot = fd_cert_slot( cert );
     963           0 :     ushort rank      = fd_ushort_if( cert_slot>=ctx->next_epoch_slot, peer->next_rank, fd_ushort_if( cert_slot>=ctx->curr_epoch_slot, peer->curr_rank, peer->prev_rank ) );
     964           0 :     if( FD_UNLIKELY( rank==USHORT_MAX ) ) { ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_UNRANKED_IDX ]++; report_alpenglow_cert( ctx, conn, &ctx->scratch.cert, kind, FD_EVENT_ALPENGLOW_CERT_PROCESSING_RESULT_UNRANKED_PEER, 0L, 0L ); return; } /* peer is not ranked in this cert slot's epoch */
     965           0 :     fd_epoch_info_t const * epoch_info = fd_ptr_if( cert_slot>=ctx->next_epoch_slot, ctx->next_epoch_info, fd_ptr_if( cert_slot>=ctx->curr_epoch_slot, ctx->curr_epoch_info, ctx->prev_epoch_info ) );
     966           0 :     if( FD_UNLIKELY( epoch_info && bit_cnt>epoch_info->validator_cnt ) ) { ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_BAD_ENCODING_IDX ]++; return; }
     967             : 
     968           0 :     int  final             = cert->kind==FD_CERT_KIND_FINAL || cert->kind==FD_CERT_KIND_FAST_FINAL;
     969           0 :     long verify_start_time = fd_clock_tile_now( ctx->clock );
     970           0 :     switch( fd_votor_pool_add_cert( ctx->pool, &ctx->scratch.cert, 0, ctx->scratch.bad ) ) {
     971           0 :     case FD_VOTOR_POOL_SUCCESS:
     972           0 :       ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_SUCCESS_IDX ]++;
     973           0 :       report_alpenglow_cert( ctx, conn, &ctx->scratch.cert, kind, FD_EVENT_ALPENGLOW_CERT_PROCESSING_RESULT_ACCEPTED, verify_start_time, 0L );
     974           0 :       break;
     975           0 :     case FD_VOTOR_POOL_ERR_SLOT_TOO_OLD: ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_SLOT_OUT_OF_RANGE_IDX ]++; break;
     976           0 :     case FD_VOTOR_POOL_ERR_SLOT_TOO_NEW:
     977           0 :       if( FD_LIKELY( ( cert_slot<=ctx->catchup_slot && ( !final || cert_slot<=ctx->catchup_final_slot ) ) || cert_slot>=ctx->next_epoch_slot+ctx->epoch_slot_cnt ) ) break;
     978           0 :       ctx->metrics.bls_verify++;
     979           0 :       if( FD_UNLIKELY( fd_cert_verify( cert, epoch_info )!=FD_CERT_VERIFY_SUCCESS ) ) {
     980           0 :         ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_SIGNATURE_FAILED_IDX ]++;
     981           0 :         report_alpenglow_cert( ctx, conn, &ctx->scratch.cert, kind, FD_EVENT_ALPENGLOW_CERT_PROCESSING_RESULT_FAILED_BLS_VERIFY, verify_start_time, 0L );
     982           0 :         ban_peer( ctx, peer, fd_clock_tile_now( ctx->clock ) );
     983           0 :         break;
     984           0 :       }
     985           0 :       ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_SLOT_OUT_OF_RANGE_IDX ]++;
     986           0 :       report_alpenglow_cert( ctx, conn, &ctx->scratch.cert, kind, FD_EVENT_ALPENGLOW_CERT_PROCESSING_RESULT_SLOT_TOO_NEW, verify_start_time, 0L );
     987           0 :       if( FD_UNLIKELY( final ) ) ctx->catchup_final_slot = cert_slot;
     988           0 :       ulong vote_slot = fd_votor_loop_advance_cert_wmark( ctx->votor, cert_slot, final );
     989           0 :       if( FD_UNLIKELY( vote_slot>ctx->catchup_vote_slot ) ) {
     990           0 :         ctx->catchup_vote_slot = vote_slot;
     991           0 :         for( ulong i=0UL; i<REWARD_VOTE_MAX; i++ ) {
     992           0 :           if( FD_UNLIKELY( ctx->reward_votes[ i ].slot<vote_slot ) ) ctx->reward_votes[ i ].slot = ULONG_MAX;
     993           0 :         }
     994           0 :       }
     995           0 :       if( FD_UNLIKELY( cert_slot<=ctx->catchup_slot ) ) break;
     996           0 :       ctx->catchup_slot = cert_slot;
     997           0 :       fd_votor_msg_t * chunk = fd_chunk_to_laddr( ctx->votor_out_mem, ctx->votor_out_chunk );
     998           0 :       chunk->repair = (fd_votor_repair_t){ .slot = cert_slot };
     999           0 :       fd_stem_publish( ctx->stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_REPAIR, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    1000           0 :       ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    1001           0 :       break;
    1002           0 :     case FD_VOTOR_POOL_ERR_DUPLICATE:
    1003           0 :       ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_DUPLICATE_IDX ]++;
    1004           0 :       if( FD_LIKELY( ctx->scratch.cert.kind==FD_CERT_KIND_NOTAR ) ) report_alpenglow_cert( ctx, conn, &ctx->scratch.cert, kind, FD_EVENT_ALPENGLOW_CERT_PROCESSING_RESULT_DUPLICATE, 0L, 0L );
    1005           0 :       break;
    1006           0 :     case FD_VOTOR_POOL_ERR_CERT_VERIFY:
    1007           0 :       ctx->metrics.cert_rx[ FD_METRICS_ENUM_CERT_RX_RESULT_V_SIGNATURE_FAILED_IDX ]++;
    1008           0 :       report_alpenglow_cert( ctx, conn, &ctx->scratch.cert, kind, FD_EVENT_ALPENGLOW_CERT_PROCESSING_RESULT_FAILED_BLS_VERIFY, verify_start_time, 0L );
    1009           0 :       ban_peer( ctx, peer, fd_clock_tile_now( ctx->clock ) );
    1010           0 :       break;
    1011           0 :     default:
    1012           0 :       FD_LOG_CRIT(( "unhandled kind" ));
    1013           0 :     }
    1014           0 :     if( FD_UNLIKELY( !fd_bls_set_is_null( ctx->scratch.bad ) ) ) ban_bad_ranks( ctx, ctx->scratch.bad, cert_slot );
    1015           0 :     return;
    1016           0 :   }
    1017           0 :   default:
    1018           0 :     ctx->metrics.datagram_rx[FD_METRICS_ENUM_DATAGRAM_RX_RESULT_V_UNKNOWN_TAG_IDX]++;
    1019           0 :     break;
    1020           0 :   }
    1021           0 : }
    1022             : 
    1023             : static peer_t const *
    1024             : reward_leader( fd_votor_tile_t *     ctx,
    1025             :                reward_vote_t const * rv,
    1026           0 :                long                  now ) {
    1027           0 :   fd_pubkey_t const * leader_key = fd_multi_epoch_leaders_get_leader_for_slot( ctx->mleaders, rv->slot+FD_VOTOR_REWARD_SLOT_DELTA );
    1028           0 :   peer_t *            leader     = leader_key ? peers_query( ctx->peers, *leader_key, NULL ) : NULL;
    1029           0 :   if( FD_UNLIKELY( !leader ) ) return NULL;
    1030           0 :   if( FD_LIKELY( leader->tx_conn && leader->tx_conn->state==FD_QUIC_CONN_STATE_ACTIVE ) ) return leader;
    1031           0 :   contact_info_t const * ci = contact_infos_query( ctx->contact_infos, leader->id_key, NULL );
    1032           0 :   if( FD_LIKELY( ci && now>=leader->conn_ts+REWARD_VOTE_RTT_MAX_NS ) ) quic_client_connect( ctx, leader, ci, now ); /* skip the reconnect backoff, the reward vote is only useful until we replay slot+8 */
    1033           0 :   return NULL;
    1034           0 : }
    1035             : 
    1036             : static void
    1037             : publish_reward_cert( fd_votor_tile_t *   ctx,
    1038             :                      fd_stem_context_t * stem,
    1039           0 :                      ulong               reward_slot ) {
    1040           0 :   fd_votor_msg_t *    chunk  = fd_chunk_to_laddr( ctx->votor_out_mem, ctx->votor_out_chunk );
    1041           0 :   fd_votor_reward_t * reward = &chunk->reward;
    1042           0 :   ctx->reward_certs[ reward_slot%FD_VOTOR_SLOTS_PER_WINDOW ] = (reward_cert_t){ .slot = reward_slot, .publish_ts = fd_clock_tile_now( ctx->clock ) };
    1043             : 
    1044           0 :   reward->slot     = reward_slot;
    1045           0 :   reward->block_id = (fd_hash_t){ 0 };
    1046             : 
    1047           0 :   fd_block_hash_t const * hash = fd_votor_pool_agg_rewards( ctx->pool, reward_slot, &reward->agg_notar, &reward->agg_skip, ctx->scratch.bad );
    1048           0 :   ban_bad_ranks( ctx, ctx->scratch.bad, reward_slot );
    1049           0 :   if( FD_LIKELY( hash ) ) memcpy( reward->block_id.uc, hash, sizeof(fd_hash_t) );
    1050             : 
    1051           0 :   fd_stem_publish( stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_REWARD, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    1052           0 :   ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    1053           0 : }
    1054             : 
    1055             : /* publish_reward_vote sends rv to peer, its reward leader, recording the
    1056             :    pkt_num an ACK must match and backing off the next retry. */
    1057             : 
    1058             : static void
    1059             : publish_reward_vote( fd_votor_tile_t *   ctx,
    1060             :                      fd_stem_context_t * stem,
    1061             :                      reward_vote_t *     rv,
    1062             :                      peer_t const *      peer,
    1063           0 :                      long                now ) {
    1064           0 :   long  broadcast_start_time = fd_clock_tile_now( ctx->clock );
    1065           0 :   ulong ser_sz               = fd_vote_ser( &rv->vote, ctx->scratch.ser );
    1066           0 :   ulong pkt_num              = quic_client_datagram_tx( ctx, stem, peer->tx_conn, ctx->scratch.ser, ser_sz );
    1067           0 :   if( FD_UNLIKELY( pkt_num==ULONG_MAX ) ) {
    1068           0 :     rv->retry_ts = now+REWARD_VOTE_RTT_MIN_NS;
    1069           0 :     return;
    1070           0 :   }
    1071             : 
    1072           0 :   if( FD_UNLIKELY( rv->conn!=peer->tx_conn ) ) {
    1073           0 :     rv->conn = peer->tx_conn;
    1074           0 :     for( ulong j=0UL; j<REWARD_VOTE_TX_MAX; j++ ) rv->pkt_num[ j ] = ULONG_MAX;
    1075           0 :   }
    1076           0 :   rv->pkt_num[ rv->tx_cnt ] = pkt_num;
    1077           0 :   rv->tx_cnt++;
    1078           0 :   report_alpenglow_vote( ctx, NULL, &rv->vote, ctx->scratch.ser[ 1 ], FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_ACCEPTED, 0, FD_EVENT_ALPENGLOW_VOTE_REASON_REWARD, 0L, broadcast_start_time, peer );
    1079           0 :   long pto     = (long)( peer->tx_conn->rtt->smoothed_rtt + fmaxf( 4.0f*peer->tx_conn->rtt->var_rtt, (float)QUIC_K_GRANULARITY_NS ) + peer->tx_conn->peer_max_ack_delay_ns ); /* RFC 9002 PTO */
    1080           0 :   rv->backoff  = fd_long_min( fd_long_max( fd_long_max( 2L*rv->backoff, pto ), REWARD_VOTE_RTT_MIN_NS ), REWARD_VOTE_RTT_MAX_NS ); /* double per unacked send, clamp between RTT_MIN, RTT_MAX */
    1081           0 :   rv->retry_ts = now + rv->backoff;
    1082           0 : }
    1083             : 
    1084             : static void
    1085             : load_keys( fd_votor_tile_t * ctx,
    1086           0 :            ulong             path_cnt ) {
    1087             : 
    1088             :   /* special case the identity.  We already know the bls pubkey */
    1089             : 
    1090           0 :   auth_vtr_key_t bls_key;
    1091           0 :   fd_keyguard_client_bls_pubkey( ctx->keyguard_client, bls_key.uc, ULONG_MAX );
    1092           0 :   auth_vtr_clear( ctx->auth_vtr );
    1093           0 :   auth_vtr_insert( ctx->auth_vtr, bls_key )->paths_idx = ULONG_MAX;
    1094             : 
    1095             :   /* For any of the other authorized voters, we need to request the BLS
    1096             :      pubkey from the sign tile. */
    1097             : 
    1098           0 :   for( ulong i=0UL; i<path_cnt; i++ ) {
    1099           0 :     fd_keyguard_client_bls_pubkey( ctx->keyguard_client, bls_key.uc, i );
    1100           0 :     auth_vtr_t const * exists = auth_vtr_query_const( ctx->auth_vtr, bls_key, NULL );
    1101           0 :     if( FD_UNLIKELY( exists ) ) {
    1102           0 :       if( FD_LIKELY( exists->paths_idx==ULONG_MAX ) ) continue; /* the identity is also an authorized voter */
    1103           0 :       FD_LOG_ERR(( "authorized voter key duplicate at index %lu", i ));
    1104           0 :     }
    1105           0 :     auth_vtr_t * auth_vtr = auth_vtr_insert( ctx->auth_vtr, bls_key );
    1106           0 :     auth_vtr->paths_idx = i;
    1107           0 :   }
    1108           0 :   ctx->auth_vtr_path_cnt = path_cnt;
    1109           0 : }
    1110             : 
    1111             : static void
    1112           0 : update_own_rank( fd_votor_tile_t * ctx ) {
    1113           0 :   fd_epoch_info_t const * epoch_infos[3] = { ctx->prev_epoch_info, ctx->curr_epoch_info, ctx->next_epoch_info };
    1114           0 :   ulong                   epoch_slots[3] = { ctx->prev_epoch_slot, ctx->curr_epoch_slot, ctx->next_epoch_slot };
    1115           0 :   for( ulong i=0UL; i<3UL; i++ ) {
    1116           0 :     fd_epoch_info_t const * epoch_info = epoch_infos[ i ];
    1117           0 :     if( FD_UNLIKELY( !epoch_info ) ) continue;
    1118           0 :     ushort own_rank = USHORT_MAX;
    1119           0 :     for( ulong rank=0UL; rank<epoch_info->validator_cnt; rank++ ) {
    1120           0 :       if( FD_UNLIKELY( !memcmp( epoch_info->validators[ rank ].id_key, ctx->id_key.uc, sizeof(fd_pubkey_t) ) ) ) own_rank = (ushort)rank;
    1121           0 :     }
    1122           0 :     if( FD_UNLIKELY( ctx->failover_enabled && !ctx->vote_authority ) ) own_rank = USHORT_MAX;
    1123           0 :     fd_votor_pool_update_own_rank( ctx->pool,  epoch_slots[ i ], own_rank );
    1124           0 :     fd_votor_loop_update_own_rank( ctx->votor, epoch_slots[ i ], own_rank );
    1125           0 :   }
    1126           0 : }
    1127             : 
    1128             : static void
    1129           0 : update_own_bls_key( fd_votor_tile_t * ctx ) {
    1130           0 :   fd_epoch_info_t const * epoch_infos[3] = { ctx->prev_epoch_info, ctx->curr_epoch_info, ctx->next_epoch_info };
    1131           0 :   ulong                   epoch_slots[3] = { ctx->prev_epoch_slot, ctx->curr_epoch_slot, ctx->next_epoch_slot };
    1132           0 :   for( ulong i=0UL; i<3UL; i++ ) {
    1133           0 :     fd_epoch_info_t const * epoch_info = epoch_infos[ i ];
    1134           0 :     if( FD_UNLIKELY( !epoch_info ) ) continue;
    1135           0 :     ushort own_rank = USHORT_MAX;
    1136           0 :     for( ulong rank=0UL; rank<epoch_info->validator_cnt; rank++ ) {
    1137           0 :       if( FD_UNLIKELY( !memcmp( epoch_info->validators[ rank ].id_key, ctx->id_key.uc, sizeof(fd_pubkey_t) ) ) ) own_rank = (ushort)rank;
    1138           0 :     }
    1139           0 :     if( FD_UNLIKELY( ctx->failover_enabled && !ctx->vote_authority ) ) own_rank = USHORT_MAX; /* with failover we stay unranked while we may not vote */
    1140           0 :     uchar const * own_bls_key = NULL; /* NULL if we are not ranked or cannot sign with our key, in which case we do not vote */
    1141           0 :     if( FD_LIKELY( own_rank!=USHORT_MAX ) ) {
    1142           0 :       fd_validator_info_t const * validator = &epoch_info->validators[ own_rank ];
    1143           0 :       FD_BASE58_ENCODE_32_BYTES( validator->vote_key, vote_key_b58 );
    1144           0 :       if( FD_LIKELY( auth_vtr_query_const( ctx->auth_vtr, *(auth_vtr_key_t const *)fd_type_pun_const( validator->bls_key ), NULL ) ) ) {
    1145           0 :         own_bls_key = validator->bls_key;
    1146           0 :         FD_LOG_INFO(( "voting as %s in the epoch starting at slot %lu", vote_key_b58, epoch_slots[ i ] ));
    1147           0 :       } else {
    1148           0 :         FD_LOG_WARNING(( "no identity or authorized voter keypair matches the BLS key of vote account %s, unable to vote", vote_key_b58 ));
    1149           0 :       }
    1150           0 :     }
    1151           0 :     fd_votor_loop_set_bls_key( ctx->votor, epoch_slots[ i ], own_bls_key );
    1152           0 :   }
    1153           0 : }
    1154             : 
    1155             : static void
    1156             : sign_vote( void *         signer_ctx,
    1157             :            fd_bls_sig_t * sig,
    1158             :            uchar const *  public_key,
    1159             :            uchar const *  payload,
    1160           0 :            ulong          payload_sz ) {
    1161           0 :   fd_votor_tile_t * ctx = signer_ctx;
    1162           0 :   if( FD_UNLIKELY( ctx->keyswitch_state ) ) {
    1163           0 :     memset( sig, 0, sizeof(fd_bls_sig_t) );
    1164           0 :     return;
    1165           0 :   }
    1166           0 :   auth_vtr_t const * auth_vtr = auth_vtr_query_const( ctx->auth_vtr, *(auth_vtr_key_t const *)fd_type_pun_const( public_key ), NULL );
    1167           0 :   if( FD_UNLIKELY( !auth_vtr ) ) FD_LOG_CRIT(( "no key derives the requested BLS public key" ));
    1168           0 :   uchar sig_bytes[ FD_BLS_SIG_SZ ];
    1169           0 :   fd_keyguard_client_ag_vote_sign( ctx->keyguard_client, sig_bytes, auth_vtr->paths_idx, payload, payload_sz );
    1170           0 :   if( FD_UNLIKELY( fd_bls_sig_de( sig, sig_bytes ) ) ) FD_LOG_CRIT(( "sign tile returned an invalid BLS signature" ));
    1171           0 : }
    1172             : 
    1173             : /* write_vote_history writes out an Agave-compatible vote history file.
    1174             :    Firedancer only writes out a single slot, the wait-to-vote slot.
    1175             : 
    1176             :    Examples:
    1177             : 
    1178             :    vote_history-A.bin          live
    1179             :    vote_history-A.bin.swp      staging, swapped with live on each write
    1180             :    vote_history-B.bin.bak      B as of the switch away from it, the spare
    1181             :                                the next switch reuses */
    1182             : 
    1183             : static void
    1184           0 : write_vote_history( fd_votor_tile_t * ctx ) {
    1185           0 :   FD_BASE58_ENCODE_32_BYTES( ctx->id_key.uc, id_key_b58 );
    1186           0 :   char swp[ PATH_MAX ];
    1187           0 :   char bin[ PATH_MAX ];
    1188           0 :   FD_TEST( fd_cstr_printf_check( swp, PATH_MAX, NULL, "vote_history-%s.bin.swp", id_key_b58 ) );
    1189           0 :   FD_TEST( fd_cstr_printf_check( bin, PATH_MAX, NULL, "vote_history-%s.bin",     id_key_b58 ) );
    1190             : 
    1191           0 :   uchar * buf = ctx->scratch.vote_history;
    1192           0 :   ulong   sz  = FD_VOTE_HISTORY_SER_SZ;
    1193           0 :   fd_vote_history_ser( ctx->id_key.uc, fd_first_slot_in_window( ctx->highest_vote_or_lead_slot )+FD_VOTOR_SLOTS_PER_WINDOW-1UL, buf );
    1194           0 :   fd_keyguard_client_sign( ctx->keyguard_client, buf+FD_VOTE_HISTORY_SERDE_SIG_OFF, buf+FD_VOTE_HISTORY_SERDE_DATA_OFF, sz-FD_VOTE_HISTORY_SERDE_DATA_OFF, FD_KEYGUARD_SIGN_TYPE_ED25519 );
    1195             : 
    1196           0 :   for( ulong off=0UL; off<sz; ) {
    1197           0 :     long n = pwritev2( ctx->vote_history_fd_swp, &(struct iovec){ .iov_base=buf+off, .iov_len=sz-off }, 1, (long)off, 0 );
    1198           0 :     if( FD_UNLIKELY( -1==n && errno==EINTR ) ) continue;
    1199           0 :     if( FD_UNLIKELY( n<=0 ) ) FD_LOG_ERR(( "pwritev2(%s) failed (%i-%s)", swp, errno, fd_io_strerror( errno ) ));
    1200           0 :     off += (ulong)n;
    1201           0 :   }
    1202           0 :   while( FD_UNLIKELY( ftruncate( ctx->vote_history_fd_swp, (long)sz ) ) ) {
    1203           0 :     if( FD_UNLIKELY( errno!=EINTR ) ) FD_LOG_ERR(( "ftruncate(%s) failed (%i-%s)", swp, errno, fd_io_strerror( errno ) ));
    1204           0 :   }
    1205             : 
    1206           0 :   if( FD_UNLIKELY( ctx->keyswitch_state==FD_KEYSWITCH_STATE_COMPLETED ) ) {
    1207           0 :     FD_BASE58_ENCODE_32_BYTES( ctx->id_key_bak.uc, bak_b58 );
    1208           0 :     char bak_swp[ PATH_MAX ];
    1209           0 :     FD_TEST( fd_cstr_printf_check( bak_swp, PATH_MAX, NULL, "vote_history-%s.bin.swp", bak_b58 ) );
    1210           0 :     if( FD_UNLIKELY( syscall( SYS_renameat2, ctx->vote_history_fd_dir, swp, ctx->vote_history_fd_dir, bin, RENAME_NOREPLACE ) && errno==EEXIST ) )
    1211           0 :       FD_LOG_WARNING(( "replacing vote history file %s, which was copied in.  set-identity takes the vote history from --vote-history-file", bin ));
    1212           0 :     if( FD_UNLIKELY( syscall( SYS_renameat2, ctx->vote_history_fd_dir, swp, ctx->vote_history_fd_dir, bin, 0 ) && errno!=ENOENT ) )
    1213           0 :       FD_LOG_ERR(( "renameat2(%s, %s) failed (%i-%s)", swp, bin, errno, fd_io_strerror( errno ) ));
    1214           0 :     if( FD_UNLIKELY( syscall( SYS_renameat2, ctx->vote_history_fd_dir, bak_swp, ctx->vote_history_fd_dir, swp, 0 ) ) )
    1215           0 :       FD_LOG_ERR(( "renameat2(%s, %s) failed (%i-%s)", bak_swp, swp, errno, fd_io_strerror( errno ) ));
    1216           0 :   } else if( FD_UNLIKELY( syscall( SYS_renameat2, ctx->vote_history_fd_dir, swp, ctx->vote_history_fd_dir, bin, RENAME_EXCHANGE ) ) ) {
    1217           0 :     FD_LOG_ERR(( "renameat2(%s, %s) failed (%i-%s)", swp, bin, errno, fd_io_strerror( errno ) ));
    1218           0 :   }
    1219           0 :   int fd = ctx->vote_history_fd_swp; ctx->vote_history_fd_swp = ctx->vote_history_fd; ctx->vote_history_fd = fd;
    1220             : 
    1221           0 :   ctx->metrics.vote_history_write++;
    1222           0 : }
    1223             : 
    1224             : /* read_vote_history returns the wait-to-vote slot of an Agave-compatible
    1225             :    vote history file, 0 if it is missing or empty. */
    1226             : 
    1227             : static ulong
    1228             : read_vote_history( fd_votor_tile_t * ctx,
    1229             :                    char const *      path,
    1230           0 :                    char const *      name ) {
    1231           0 :   int fd = openat( ctx->vote_history_fd_dir, name, O_RDONLY );
    1232           0 :   if( FD_UNLIKELY( -1==fd && errno==ENOENT ) ) return 0UL;
    1233           0 :   if( FD_UNLIKELY( -1==fd ) ) FD_LOG_ERR(( "open(`%s/%s`) failed (%i-%s)", path, name, errno, fd_io_strerror( errno ) ));
    1234           0 :   struct stat st;
    1235           0 :   if( FD_UNLIKELY( -1==fstat( fd, &st ) ) ) FD_LOG_ERR(( "fstat(`%s/%s`) failed (%i-%s)", path, name, errno, fd_io_strerror( errno ) ));
    1236           0 :   if( FD_UNLIKELY( !st.st_size ) ) { /* never written, the identity never voted from here */
    1237           0 :     if( FD_UNLIKELY( close( fd ) ) ) FD_LOG_ERR(( "close(`%s/%s`) failed (%i-%s)", path, name, errno, fd_io_strerror( errno ) ));
    1238           0 :     return 0UL;
    1239           0 :   }
    1240             : 
    1241           0 :   ulong         sz   = (ulong)st.st_size;
    1242           0 :   uchar const * file = mmap( NULL, sz, PROT_READ, MAP_PRIVATE, fd, 0 );
    1243           0 :   if( FD_UNLIKELY( file==MAP_FAILED ) ) FD_LOG_ERR(( "mmap(`%s/%s`) failed (%i-%s)", path, name, errno, fd_io_strerror( errno ) ));
    1244           0 :   if( FD_UNLIKELY( close( fd ) ) ) FD_LOG_ERR(( "close(`%s/%s`) failed (%i-%s)", path, name, errno, fd_io_strerror( errno ) ));
    1245           0 :   ulong vote_history_slot;
    1246           0 :   int   err = fd_vote_history_de( file, sz, ctx->id_key.uc, &vote_history_slot );
    1247           0 :   if( FD_UNLIKELY( munmap( (void *)file, sz ) ) ) FD_LOG_ERR(( "munmap(`%s/%s`) failed (%i-%s)", path, name, errno, fd_io_strerror( errno ) ));
    1248           0 :   if( FD_UNLIKELY( err ) ) FD_LOG_ERR(( "vote history file `%s/%s` is invalid (%i) or not for this identity. Please copy this identity's latest %s into %s.", path, name, err, name, path ));
    1249           0 :   return vote_history_slot;
    1250           0 : }
    1251             : 
    1252             : /* wfs_is_ready returns whether WFS permits votor to run.  The
    1253             :    classifier is a pure function of config, so it takes the configured
    1254             :    shred version, never the one ipecho observed.  ERROR is replay's
    1255             :    fatal to report, so just hold here. */
    1256             : 
    1257             : static int
    1258           0 : wfs_is_ready( fd_votor_tile_t const * ctx ) {
    1259           0 :   int mode = fd_wfs_mode( ctx->wfs_slot, ctx->wfs_hash_is_zero,
    1260           0 :                           (ulong)ctx->wfs_shred_version, ctx->boot_block_id.slot );
    1261           0 :   switch( mode ) {
    1262           0 :     case FD_WFS_MODE_DISABLED:
    1263           0 :     case FD_WFS_MODE_NOOP:       return 1;
    1264           0 :     case FD_WFS_MODE_MATCH:      return ctx->wfs_signalled;
    1265           0 :     case FD_WFS_MODE_UNRESOLVED:
    1266           0 :     case FD_WFS_MODE_ERROR:      return 0;
    1267           0 :     default: FD_LOG_CRIT(( "unexpected WFS mode %d", mode ));
    1268           0 :   }
    1269           0 : }
    1270             : 
    1271             : /* Whether the identity this machine runs is ranked in an epoch. */
    1272             : static int
    1273           0 : failover_is_ranked( fd_votor_tile_t const * ctx ) {
    1274           0 :   fd_epoch_info_t const * epoch_infos[3] = { ctx->prev_epoch_info, ctx->curr_epoch_info, ctx->next_epoch_info };
    1275           0 :   for( ulong i=0UL; i<3UL; i++ ) {
    1276           0 :     fd_epoch_info_t const * epoch_info = epoch_infos[ i ];
    1277           0 :     if( FD_UNLIKELY( !epoch_info ) ) continue;
    1278           0 :     for( ulong rank=0UL; rank<epoch_info->validator_cnt; rank++ ) {
    1279           0 :       if( FD_UNLIKELY( !memcmp( epoch_info->validators[ rank ].id_key, ctx->id_key.uc, sizeof(fd_pubkey_t) ) ) ) return 1;
    1280           0 :     }
    1281           0 :   }
    1282           0 :   return 0;
    1283           0 : }
    1284             : 
    1285             : /* Returns the highest slot whose window this identity may have led,
    1286             :    ULONG_MAX when there is none. */
    1287             : static ulong
    1288           0 : failover_leader_floor( fd_votor_tile_t const * ctx ) {
    1289           0 :   if( ctx->last_leader_slot==ULONG_MAX ) return ctx->adopted_last_leader_slot;
    1290           0 :   if( ctx->adopted_last_leader_slot==ULONG_MAX ) return ctx->last_leader_slot;
    1291           0 :   return fd_ulong_max( ctx->last_leader_slot, ctx->adopted_last_leader_slot );
    1292           0 : }
    1293             : 
    1294             : /* The end of the highest window in which our slot states may record a
    1295             :    vote that did not go out: under the restart floor, under the catch-up
    1296             :    floor, or dropped by this tile.  ULONG_MAX when there is none. */
    1297             : static ulong
    1298           0 : failover_unsent_bound( fd_votor_tile_t const * ctx ) {
    1299           0 :   ulong slots[ 3 ] = { ctx->vote_history_slot ? ctx->vote_history_slot-1UL : ULONG_MAX,
    1300           0 :                        ctx->catchup_vote_slot ? ctx->catchup_vote_slot-1UL : ULONG_MAX,
    1301           0 :                        ctx->highest_unsent_slot };
    1302           0 :   ulong bound = ULONG_MAX;
    1303           0 :   for( ulong i=0UL; i<3UL; i++ ) {
    1304           0 :     if( slots[ i ]==ULONG_MAX ) continue;
    1305           0 :     ulong end = fd_first_slot_in_window( slots[ i ] )+FD_VOTOR_SLOTS_PER_WINDOW-1UL;
    1306           0 :     bound = bound==ULONG_MAX ? end : fd_ulong_max( bound, end );
    1307           0 :   }
    1308           0 :   return bound;
    1309           0 : }
    1310             : 
    1311             : /* Publishes a votor_hist snapshot message to the failover tile, see
    1312             :    fd_votor_hist_msg. */
    1313             : static void
    1314             : failover_publish_hist( fd_votor_tile_t *   ctx,
    1315             :                        fd_stem_context_t * stem,
    1316           0 :                        int                 has_vote ) {
    1317           0 :   if( FD_UNLIKELY( ctx->hist_out_idx==ULONG_MAX ) ) return;
    1318           0 :   fd_votor_hist_msg_t * msg = fd_chunk_to_laddr( ctx->hist_out_mem, ctx->hist_out_chunk );
    1319           0 :   msg->identity    = ctx->id_key;
    1320           0 :   msg->replay_slot = ctx->highest_completed_slot ? ctx->highest_completed_slot : ULONG_MAX;
    1321           0 :   msg->root_slot   = ctx->root_slot;
    1322           0 :   msg->has_vote    = has_vote;
    1323           0 :   msg->ranked      = ctx->vote_authority && failover_is_ranked( ctx );
    1324           0 :   msg->truncated   = fd_votor_loop_failover_hist_export( ctx->votor, failover_leader_floor( ctx ), &msg->hist );
    1325           0 :   if( FD_UNLIKELY( msg->truncated && !ctx->hist_was_truncated ) ) FD_LOG_WARNING(( "vote history export dropped windows below slot %lu, finality is far behind our votes", fd_votor_hist_first_slot( msg->hist.anchor ) ));
    1326           0 :   ctx->hist_was_truncated = msg->truncated;
    1327           0 :   ulong unsent = failover_unsent_bound( ctx );
    1328           0 :   if( FD_UNLIKELY( unsent!=ULONG_MAX && ( msg->hist.vote_bound==ULONG_MAX || msg->hist.vote_bound<unsent ) ) ) msg->hist.vote_bound = unsent;
    1329           0 :   msg->vote_slot   = fd_votor_hist_tip( &msg->hist ); /* the failover tile checks the history ends here */
    1330           0 :   ulong tspub = fd_frag_meta_ts_comp( fd_tickcount() );
    1331           0 :   fd_stem_publish( stem, ctx->hist_out_idx, FD_VOTOR_HIST_SIG, ctx->hist_out_chunk, sizeof(fd_votor_hist_msg_t), 0UL, tspub, tspub );
    1332           0 :   ctx->hist_out_chunk = fd_dcache_compact_next( ctx->hist_out_chunk, sizeof(fd_votor_hist_msg_t), ctx->hist_out_chunk0, ctx->hist_out_wmark );
    1333           0 :   ctx->hist_seq       = stem->seqs[ ctx->hist_out_idx ];
    1334           0 : }
    1335             : 
    1336             : /* Raises the adopted leader floor to the window of slot, so we do not
    1337             :    lead that window or below it. The floor can only rise. */
    1338             : static void
    1339             : failover_raise_leader_floor( fd_votor_tile_t * ctx,
    1340           0 :                              ulong             slot ) {
    1341           0 :   if( FD_UNLIKELY( slot==ULONG_MAX ) ) return;
    1342           0 :   ulong window = fd_first_slot_in_window( slot );
    1343           0 :   if( FD_LIKELY( ctx->adopted_last_leader_slot==ULONG_MAX || ctx->adopted_last_leader_slot<window ) ) ctx->adopted_last_leader_slot = window;
    1344           0 : }
    1345             : 
    1346             : /* An empty request is shorter than any serialized history */
    1347             : FD_STATIC_ASSERT( FD_VOTOR_ADOPT_EMPTY_SZ<FD_VOTOR_HIST_HDR_SZ, adopt_empty_sz );
    1348             : 
    1349             : /* Adopts the peer's vote history, or an empty one, for the given target identity. */
    1350             : static fd_votor_adopt_result_t
    1351             : failover_adopt_hist( fd_votor_tile_t *   ctx,
    1352             :                      fd_pubkey_t const * target,
    1353             :                      uchar const *       req,
    1354           0 :                      ulong               req_sz ) {
    1355           0 :   fd_votor_adopt_result_t result = {
    1356           0 :     .result     = FD_VOTOR_ADOPT_ERR_DECODE,
    1357           0 :     .root       = ULONG_MAX,
    1358           0 :     .vote_slot  = ULONG_MAX,
    1359           0 :     .vote_bound = ULONG_MAX
    1360           0 :   };
    1361           0 :   fd_votor_hist_t hist[1];
    1362           0 :   int             empty = req_sz==FD_VOTOR_ADOPT_EMPTY_SZ;
    1363             : 
    1364             :   /* Decode the request. */
    1365           0 :   if( FD_UNLIKELY( !empty && ( req_sz>FD_VOTOR_HIST_SER_MAX || fd_votor_hist_de( req, req_sz, hist ) ) ) ) {
    1366           0 :     FD_LOG_WARNING(( "failover: refusing a vote history of %lu bytes that does not decode", req_sz ));
    1367           0 :     return result;
    1368           0 :   }
    1369             : 
    1370             :   /* Consensus must be up to adopt. */
    1371           0 :   result.result = FD_VOTOR_ADOPT_ERR_UNREPLAYED;
    1372           0 :   if( FD_UNLIKELY( !ctx->init ) ) {
    1373           0 :     FD_LOG_WARNING(( "failover: not adopting the vote history, consensus is not up yet" ));
    1374           0 :     return result;
    1375           0 :   }
    1376           0 :   result.result = FD_VOTOR_ADOPT_ERR_INVALID;
    1377             : 
    1378             :   /* An empty request assigns the vote bound and leader floor to the given slot. */
    1379           0 :   if( FD_UNLIKELY( empty ) ) {
    1380           0 :     ulong bound = FD_LOAD( ulong, req );
    1381           0 :     if( FD_UNLIKELY( bound==ULONG_MAX ) ) {
    1382           0 :       FD_LOG_WARNING(( "failover: refusing an empty vote history that has no bound slot" ));
    1383           0 :       return result;
    1384           0 :     }
    1385           0 :     fd_votor_loop_failover_set_vote_bound( ctx->votor, bound );
    1386           0 :     failover_raise_leader_floor( ctx, bound );
    1387           0 :     ctx->failover_hist_adopted = 1;
    1388           0 :     ctx->adopted_tip  = ULONG_MAX;
    1389           0 :     result.result     = FD_VOTOR_ADOPT_SUCCESS;
    1390           0 :     result.root       = fd_votor_loop_metrics( ctx->votor ).highest_final_slot;
    1391           0 :     result.vote_bound = fd_votor_loop_failover_get_vote_bound( ctx->votor );
    1392           0 :     FD_LOG_NOTICE(( "failover: starting from an empty vote history on anchor %lu, no vote at or below slot %lu", result.root, result.vote_bound ));
    1393           0 :     return result;
    1394           0 :   }
    1395             : 
    1396             :   /* A non-empty history must have votes in it. */
    1397           0 :   ulong tip = fd_votor_hist_tip( hist );
    1398           0 :   if( FD_UNLIKELY( tip==ULONG_MAX ) ) {
    1399           0 :     FD_LOG_WARNING(( "failover: refusing a vote history on anchor %lu that has no votes in it", hist->anchor ));
    1400           0 :     return result;
    1401           0 :   }
    1402             : 
    1403             :   /* Reject a history older than the votes we sent as THIS identity. */
    1404           0 :   result.result = FD_VOTOR_ADOPT_ERR_STALE;
    1405           0 :   if( FD_UNLIKELY( ctx->last_vote_slot!=ULONG_MAX && tip<ctx->last_vote_slot && fd_pubkey_eq( target, &ctx->last_vote_key ) ) ) {
    1406           0 :     FD_LOG_WARNING(( "failover: refusing a vote history through slot %lu, this machine already voted as this identity through slot %lu", tip, ctx->last_vote_slot ));
    1407           0 :     return result;
    1408           0 :   }
    1409             : 
    1410             :   /* Reject a finality anchor past the blocks we replayed. */
    1411           0 :   result.result = FD_VOTOR_ADOPT_ERR_UNREPLAYED_ROOT;
    1412           0 :   if( FD_UNLIKELY( ctx->highest_completed_slot && hist->anchor>ctx->highest_completed_slot ) ) {
    1413           0 :     FD_LOG_WARNING(( "failover: refusing a vote history on anchor %lu, replay has only reached slot %lu, retry the promotion once replay passes the anchor", hist->anchor, ctx->highest_completed_slot ));
    1414           0 :     return result;
    1415           0 :   }
    1416             : 
    1417             :   /* Adopt the history, rejecting if it exceeds the slot state capacity. */
    1418           0 :   ulong conflicts = fd_votor_loop_failover_hist_adopt( ctx->votor, hist );
    1419           0 :   if( FD_UNLIKELY( conflicts==ULONG_MAX ) ) {
    1420           0 :     result.result = FD_VOTOR_ADOPT_ERR_CAPACITY;
    1421           0 :     FD_LOG_WARNING(( "failover: vote history exceeds the available slot state capacity, retry as consensus prunes old slots" ));
    1422           0 :     return result;
    1423           0 :   }
    1424           0 :   if( FD_UNLIKELY( conflicts ) ) FD_LOG_WARNING(( "adopted vote history disagrees with %lu of our own notar hashes, theirs were the ones sent", conflicts ));
    1425           0 :   ctx->failover_hist_adopted = 1;
    1426           0 :   ctx->adopted_tip           = tip;
    1427           0 :   failover_raise_leader_floor( ctx, hist->last_leader_slot );
    1428           0 :   failover_raise_leader_floor( ctx, fd_votor_loop_failover_get_vote_bound( ctx->votor ) );
    1429           0 :   result.result     = FD_VOTOR_ADOPT_SUCCESS;
    1430           0 :   result.root       = fd_votor_loop_metrics( ctx->votor ).highest_final_slot;
    1431           0 :   result.vote_slot  = tip;
    1432           0 :   result.vote_bound = fd_votor_loop_failover_get_vote_bound( ctx->votor );
    1433           0 :   if( FD_LIKELY( result.vote_bound==ULONG_MAX ) ) FD_LOG_NOTICE(( "failover: adopted a vote history through slot %lu, the anchor is now %lu", tip, result.root ));
    1434           0 :   else                                            FD_LOG_NOTICE(( "failover: adopted a vote history through slot %lu, the anchor is now %lu, no vote at or below slot %lu", tip, result.root, result.vote_bound ));
    1435           0 :   return result;
    1436           0 : }
    1437             : 
    1438             : /* Applies the failover voting rule at the end of an identity switch.
    1439             :    Runs when the identity key actually changes and updates state. */
    1440             : static void
    1441           0 : failover_switched( fd_votor_tile_t * ctx ) {
    1442             :   /* Skip leader windows this identity has already led. */
    1443           0 :   ulong floor = failover_leader_floor( ctx );
    1444           0 :   if( FD_UNLIKELY( ctx->adopted_last_leader_slot!=ULONG_MAX ) ) {
    1445           0 :     ulong next_window  = fd_first_slot_in_window( ctx->highest_parent_ready_slot )+FD_VOTOR_SLOTS_PER_WINDOW;
    1446           0 :     ulong floor_window = fd_first_slot_in_window( floor )+FD_VOTOR_SLOTS_PER_WINDOW;
    1447           0 :     if( FD_UNLIKELY( floor_window>next_window ) ) {
    1448           0 :       ctx->next_leader_slot = fd_multi_epoch_leaders_get_next_slot( ctx->mleaders, fd_ulong_max( fd_ulong_max( ctx->curr_epoch_slot, floor_window ), ctx->vote_history_slot ), &ctx->id_key );
    1449           0 :     }
    1450           0 :   }
    1451           0 :   int operator = !FD_VOLATILE_CONST( ctx->id_keyswitch->failover );
    1452           0 :   ctx->vote_authority        = ( operator || ctx->failover_hist_adopted );
    1453           0 :   ctx->installed_by_failover = !operator;
    1454             : 
    1455           0 :   if( FD_UNLIKELY( ctx->vote_authority && !operator ) ) {
    1456           0 :     ulong slots[ 3 ] = { ctx->adopted_tip, fd_votor_loop_failover_get_vote_bound( ctx->votor ), floor };
    1457           0 :     for( ulong i=0UL; i<3UL; i++ ) {
    1458           0 :       if( FD_LIKELY( slots[ i ]!=ULONG_MAX ) ) ctx->highest_vote_or_lead_slot = fd_ulong_max( ctx->highest_vote_or_lead_slot, slots[ i ] );
    1459           0 :     }
    1460           0 :   }
    1461           0 :   if( FD_UNLIKELY( !operator ) ) {
    1462           0 :     FD_BASE58_ENCODE_32_BYTES( ctx->id_key.uc, id_key_b58 );
    1463           0 :     FD_LOG_NOTICE(( "failover: switched to identity `%s`, this machine %s", id_key_b58, ctx->vote_authority ? "votes as it" : "does not vote as it" ));
    1464           0 :   }
    1465           0 :   ctx->failover_hist_adopted = 0;
    1466           0 :   ctx->adopted_tip           = ULONG_MAX;
    1467           0 :   ctx->id_keyswitch->result  = ctx->hist_seq;
    1468           0 : }
    1469             : 
    1470             : /* Tracks the slot replay completed and its root. */
    1471             : static void
    1472             : failover_slot_completed( fd_votor_tile_t *                  ctx,
    1473           0 :                          fd_replay_slot_completed_t const * slot_completed ) {
    1474           0 :   ctx->highest_completed_slot = fd_ulong_max( ctx->highest_completed_slot, slot_completed->slot );
    1475           0 :   if( FD_LIKELY( slot_completed->root_slot!=ULONG_MAX ) ) ctx->root_slot = slot_completed->root_slot;
    1476           0 : }
    1477             : 
    1478             : /* Tracks a vote we built, sent or not, and publishes the history. */
    1479             : static void
    1480             : failover_after_vote( fd_votor_tile_t *   ctx,
    1481             :                      fd_stem_context_t * stem,
    1482             :                      ulong               vote_slot,
    1483           0 :                      int                 sent ) {
    1484           0 :   if( FD_LIKELY( sent ) ) {
    1485           0 :     if( FD_LIKELY( ctx->last_vote_slot==ULONG_MAX || vote_slot>ctx->last_vote_slot ) ) {
    1486           0 :       ctx->last_vote_slot = vote_slot;
    1487           0 :       ctx->last_vote_key  = ctx->id_key;
    1488           0 :     }
    1489           0 :   } else if( FD_UNLIKELY( ctx->highest_unsent_slot==ULONG_MAX || vote_slot>ctx->highest_unsent_slot ) ) {
    1490           0 :     ctx->highest_unsent_slot = vote_slot;
    1491           0 :   }
    1492           0 :   failover_publish_hist( ctx, stem, sent );
    1493           0 : }
    1494             : 
    1495             : /* Tracks our LEADER and publishes the history. */
    1496             : static void
    1497             : failover_after_leader( fd_votor_tile_t *   ctx,
    1498           0 :                        fd_stem_context_t * stem ) {
    1499           0 :   ctx->last_leader_slot = ctx->next_leader_slot;
    1500           0 :   failover_publish_hist( ctx, stem, 0 );
    1501           0 : }
    1502             : 
    1503             : /* failover_init initializes failover in the votor tile, all of it off
    1504             :    unless the topology has the failover links. */
    1505             : static void
    1506             : failover_init( fd_votor_tile_t *      ctx,
    1507             :                fd_topo_t const *      topo,
    1508           0 :                fd_topo_tile_t const * tile ) {
    1509             :   /* Without the failover links failover stays off. */
    1510           0 :   ulong failov_in_idx = fd_topo_find_tile_in_link ( topo, tile, "failov_votor", tile->kind_id );
    1511           0 :   ctx->hist_out_idx   = fd_topo_find_tile_out_link( topo, tile, "votor_hist",   tile->kind_id );
    1512           0 :   ctx->failov_out_idx = fd_topo_find_tile_out_link( topo, tile, "votor_failov", tile->kind_id );
    1513           0 :   ctx->failover_enabled = failov_in_idx!=ULONG_MAX;
    1514           0 :   if( FD_UNLIKELY( ( ctx->hist_out_idx!=ULONG_MAX )!=ctx->failover_enabled || ( ctx->failov_out_idx!=ULONG_MAX )!=ctx->failover_enabled ) ) {
    1515           0 :     FD_LOG_ERR(( "votor tile needs all of the failov_votor, votor_hist and votor_failov links or none of them" ));
    1516           0 :   }
    1517           0 :   if( FD_UNLIKELY( ctx->failover_enabled ) ) {
    1518           0 :     fd_topo_link_t const * hist_out = &topo->links[ tile->out_link_id[ ctx->hist_out_idx ] ];
    1519           0 :     ctx->hist_out_mem    = topo->workspaces[ topo->objs[ hist_out->dcache_obj_id ].wksp_id ].wksp;
    1520           0 :     ctx->hist_out_chunk0 = fd_dcache_compact_chunk0( ctx->hist_out_mem, hist_out->dcache );
    1521           0 :     ctx->hist_out_wmark  = fd_dcache_compact_wmark ( ctx->hist_out_mem, hist_out->dcache, hist_out->mtu );
    1522           0 :     ctx->hist_out_chunk  = ctx->hist_out_chunk0;
    1523           0 :     fd_topo_link_t const * failov_out = &topo->links[ tile->out_link_id[ ctx->failov_out_idx ] ];
    1524           0 :     ctx->failov_out_mem    = topo->workspaces[ topo->objs[ failov_out->dcache_obj_id ].wksp_id ].wksp;
    1525           0 :     ctx->failov_out_chunk0 = fd_dcache_compact_chunk0( ctx->failov_out_mem, failov_out->dcache );
    1526           0 :     ctx->failov_out_wmark  = fd_dcache_compact_wmark ( ctx->failov_out_mem, failov_out->dcache, failov_out->mtu );
    1527           0 :     ctx->failov_out_chunk  = ctx->failov_out_chunk0;
    1528           0 :   }
    1529             : 
    1530           0 :   ctx->installed_by_failover    = 0;
    1531           0 :   ctx->vote_authority           = 1;
    1532           0 :   ctx->highest_unsent_slot      = ULONG_MAX;
    1533           0 :   ctx->failover_hist_adopted    = 0;
    1534           0 :   ctx->adopted_tip              = ULONG_MAX;
    1535           0 :   ctx->hist_was_truncated       = 0;
    1536           0 :   ctx->last_leader_slot         = ULONG_MAX;
    1537           0 :   ctx->adopted_last_leader_slot = ULONG_MAX;
    1538           0 :   ctx->last_vote_slot           = ULONG_MAX;
    1539           0 :   ctx->root_slot                = ULONG_MAX;
    1540           0 :   ctx->adopt_req_sz             = 0UL;
    1541           0 :   ctx->hist_seq                 = 0UL;
    1542           0 :   ctx->highest_completed_slot   = 0UL;
    1543           0 : }
    1544             : 
    1545             : /* Copies an adoption request from the failover tile. */
    1546             : static void
    1547             : failover_adopt_copy( fd_votor_tile_t * ctx,
    1548             :                      ulong             in_idx,
    1549             :                      ulong             chunk,
    1550           0 :                      ulong             sz ) {
    1551           0 :   ctx->adopt_req_sz = sz;
    1552           0 :   if( FD_LIKELY( sz<=sizeof(ctx->adopt_req) ) ) fd_memcpy( ctx->adopt_req, fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk ), sz );
    1553           0 : }
    1554             : 
    1555             : /* Responds to an adoption request, echoing its sequence number. */
    1556             : static void
    1557             : failover_adopt_response( fd_votor_tile_t *   ctx,
    1558             :                        ulong               sig,
    1559           0 :                        fd_stem_context_t * stem ) {
    1560           0 :   fd_votor_adopt_result_t result;
    1561           0 :   if( FD_UNLIKELY( ctx->adopt_req_sz<FD_VOTOR_ADOPT_REQ_HDR_SZ || ctx->adopt_req_sz>sizeof(ctx->adopt_req) ) ) {
    1562           0 :     FD_LOG_WARNING(( "failover: refusing a vote history adoption of %lu bytes, it has no target identity", ctx->adopt_req_sz ));
    1563           0 :     result = (fd_votor_adopt_result_t){
    1564           0 :       .result     = FD_VOTOR_ADOPT_ERR_DECODE,
    1565           0 :       .root       = ULONG_MAX,
    1566           0 :       .vote_slot  = ULONG_MAX,
    1567           0 :       .vote_bound = ULONG_MAX
    1568           0 :     };
    1569           0 :   } else if( FD_UNLIKELY( ctx->keyswitch_state!=FD_KEYSWITCH_STATE_UNLOCKED ||
    1570           0 :                           fd_keyswitch_state_query( ctx->id_keyswitch )==FD_KEYSWITCH_STATE_SWITCH_PENDING ||
    1571           0 :                           fd_keyswitch_state_query( ctx->id_keyswitch )==FD_KEYSWITCH_STATE_UNHALT_PENDING ) ) {
    1572           0 :     FD_LOG_WARNING(( "failover: rejecting a vote history adoption, an identity switch is in progress" ));
    1573           0 :     result = (fd_votor_adopt_result_t){
    1574           0 :       .result     = FD_VOTOR_ADOPT_ERR_INVALID,
    1575           0 :       .root       = ULONG_MAX,
    1576           0 :       .vote_slot  = ULONG_MAX,
    1577           0 :       .vote_bound = ULONG_MAX
    1578           0 :     };
    1579           0 :   } else if( FD_UNLIKELY( ctx->vote_authority && ( ctx->installed_by_failover || failover_is_ranked( ctx ) ) ) ) {
    1580           0 :     FD_LOG_WARNING(( "failover: rejecting a vote history adoption, this machine votes as its identity" ));
    1581           0 :     result = (fd_votor_adopt_result_t){
    1582           0 :       .result=FD_VOTOR_ADOPT_ERR_INVALID,
    1583           0 :       .root=ULONG_MAX,
    1584           0 :       .vote_slot=ULONG_MAX,
    1585           0 :       .vote_bound=ULONG_MAX
    1586           0 :     };
    1587           0 :   } else {
    1588           0 :     ulong boot_bound = ULONG_MAX;
    1589           0 :     fd_votor_hist_t local;
    1590           0 :     fd_votor_loop_failover_hist_export( ctx->votor, ULONG_MAX, &local );
    1591           0 :     ulong tip = fd_votor_hist_tip( &local );
    1592           0 :     if( tip!=ULONG_MAX ) boot_bound = fd_first_slot_in_window( tip )+FD_VOTOR_SLOTS_PER_WINDOW-1UL;
    1593           0 :     result = failover_adopt_hist( ctx, (fd_pubkey_t const *)ctx->adopt_req, ctx->adopt_req+FD_VOTOR_ADOPT_REQ_HDR_SZ,
    1594           0 :                                   ctx->adopt_req_sz-FD_VOTOR_ADOPT_REQ_HDR_SZ );
    1595           0 :     if( FD_LIKELY( result.result==FD_VOTOR_ADOPT_SUCCESS ) ) {
    1596           0 :       if( boot_bound!=ULONG_MAX ) {
    1597           0 :         fd_votor_loop_failover_set_vote_bound( ctx->votor, boot_bound );
    1598           0 :         failover_raise_leader_floor( ctx, boot_bound );
    1599           0 :         result.vote_bound = fd_votor_loop_failover_get_vote_bound( ctx->votor );
    1600           0 :       }
    1601           0 :       ctx->vote_authority = 0;
    1602           0 :       update_own_rank( ctx );
    1603           0 :       update_own_bls_key( ctx );
    1604           0 :     }
    1605           0 :   }
    1606           0 :   fd_memcpy( fd_chunk_to_laddr( ctx->failov_out_mem, ctx->failov_out_chunk ), &result, sizeof(result) );
    1607           0 :   ulong tspub = fd_frag_meta_ts_comp( fd_tickcount() );
    1608           0 :   fd_stem_publish( stem, ctx->failov_out_idx, sig, ctx->failov_out_chunk, sizeof(result), 0UL, tspub, tspub );
    1609           0 :   ctx->failov_out_chunk = fd_dcache_compact_next( ctx->failov_out_chunk, sizeof(result), ctx->failov_out_chunk0, ctx->failov_out_wmark );
    1610           0 : }
    1611             : 
    1612             : static void
    1613             : handle_epoch( fd_votor_tile_t *           ctx,
    1614           0 :               fd_epoch_info_msg_t const * msg ) {
    1615             : 
    1616           0 :   fd_epoch_info_t * epoch_info;
    1617           0 :   if     ( FD_UNLIKELY( !ctx->curr_epoch_info ) ) epoch_info = &ctx->scratch.curr_epoch_info;
    1618           0 :   else if( FD_UNLIKELY( !ctx->next_epoch_info ) ) epoch_info = &ctx->scratch.next_epoch_info;
    1619           0 :   else if( FD_UNLIKELY( !ctx->prev_epoch_info ) ) epoch_info = &ctx->scratch.prev_epoch_info;
    1620           0 :   else                                            epoch_info = ctx->prev_epoch_info;
    1621             : 
    1622             :   /* rank voters */
    1623             : 
    1624           0 :   fd_vote_stake_weight_t const * stakes    = fd_epoch_info_msg_stake_weights( msg );
    1625           0 :   ulong                          stake_cnt = msg->staked_vote_cnt;
    1626           0 :   FD_TEST( stake_cnt<=FD_VOTOR_VAT_MAX );
    1627             : 
    1628           0 :   known_key_t known[ 2UL*FD_VOTOR_VAT_MAX ];
    1629           0 :   ulong       known_cnt = 0UL;
    1630           0 :   fd_epoch_info_t const * src[2] = { ctx->curr_epoch_info, ctx->next_epoch_info };
    1631           0 :   for( ulong j=0UL; j<2UL; j++ ) {
    1632           0 :     if( !src[ j ] || src[ j ]==epoch_info ) continue; /* epoch_info is overwritten below */
    1633           0 :     for( ulong r=0UL; r<src[ j ]->validator_cnt; r++ ) known[ known_cnt++ ] = (known_key_t){ .bls = src[ j ]->validators[ r ].bls_key, .pub = &src[ j ]->pubkeys[ r ] };
    1634           0 :   }
    1635           0 :   sort_known_key_inplace( known, known_cnt );
    1636             : 
    1637           0 :   sort_voter_t voters[FD_VOTOR_VAT_MAX];
    1638           0 :   ulong        voter_cnt = 0UL;
    1639           0 :   for( ulong i=0UL; i<stake_cnt; i++ ) {
    1640           0 :     if( FD_UNLIKELY( !stakes[i].stake ) ) continue;
    1641           0 :     ulong k = sort_known_key_split( known, known_cnt, (known_key_t){ .bls = stakes[i].bls_key } );
    1642           0 :     if( FD_LIKELY( k<known_cnt && !memcmp( known[ k ].bls, stakes[i].bls_key, FD_BLS_PUB_COMPRESSED_SZ ) ) ) voters[voter_cnt].pub = *known[ k ].pub;
    1643           0 :     else if( FD_UNLIKELY( fd_bls_pub_de( &voters[voter_cnt].pub, stakes[i].bls_key, FD_BLS_PUB_COMPRESSED_SZ ) ) ) continue;
    1644           0 :     voters[voter_cnt].bls   = stakes[i].bls_key;
    1645           0 :     voters[voter_cnt].id    = stakes[i].id_key.uc;
    1646           0 :     voters[voter_cnt].stake = stakes[i].stake;
    1647           0 :     voters[voter_cnt].idx   = i;
    1648           0 :     voters[voter_cnt].dup   = 0;
    1649           0 :     voter_cnt++;
    1650           0 :   }
    1651             : 
    1652           0 :   sort_voter_bls_inplace( voters, voter_cnt );
    1653           0 :   for( ulong i=1UL; i<voter_cnt; i++ ) if( FD_UNLIKELY( !memcmp( voters[i-1UL].bls, voters[i].bls, FD_BLS_PUB_COMPRESSED_SZ ) ) ) voters[i-1UL].dup = voters[i].dup = 1;
    1654           0 :   sort_voter_id_inplace( voters, voter_cnt );
    1655           0 :   for( ulong i=1UL; i<voter_cnt; i++ ) if( FD_UNLIKELY( !memcmp( voters[i-1UL].id,  voters[i].id,  sizeof(fd_pubkey_t)      ) ) ) voters[i-1UL].dup = voters[i].dup = 1;
    1656           0 :   epoch_info->validator_cnt = 0;
    1657           0 :   for( ulong i=0UL; i<voter_cnt; i++ ) if( FD_LIKELY( !voters[i].dup ) ) voters[epoch_info->validator_cnt++] = voters[i];
    1658           0 :   sort_voter_stake_inplace( voters, epoch_info->validator_cnt );
    1659             : 
    1660           0 :   epoch_info->total_stake = 0UL;
    1661           0 :   for( ulong i=0UL; i<epoch_info->validator_cnt; i++ ) {
    1662           0 :     ulong                 idx            = voters[i].idx;
    1663           0 :     fd_validator_info_t * validator_info = epoch_info->validators + i;
    1664           0 :     memset( validator_info, 0, sizeof(fd_validator_info_t) );
    1665           0 :     validator_info->id    = i;
    1666           0 :     validator_info->stake = stakes[idx].stake;
    1667           0 :     memcpy( validator_info->id_key,   stakes[idx].id_key.uc,   sizeof(fd_pubkey_t)      );
    1668           0 :     memcpy( validator_info->vote_key, stakes[idx].vote_key.uc, sizeof(fd_pubkey_t)      );
    1669           0 :     memcpy( validator_info->bls_key,  stakes[idx].bls_key,     FD_BLS_PUB_COMPRESSED_SZ );
    1670           0 :     epoch_info->pubkeys[i]   = voters[i].pub;
    1671           0 :     epoch_info->total_stake += validator_info->stake;
    1672           0 :   }
    1673             : 
    1674             :   /* swap pointers */
    1675             : 
    1676           0 :   if( FD_UNLIKELY( !ctx->curr_epoch_info ) ) {
    1677           0 :     ctx->curr_epoch_info = epoch_info;
    1678           0 :     ctx->curr_epoch_slot = msg->start_slot;
    1679           0 :   } else {
    1680           0 :     if( FD_LIKELY( ctx->next_epoch_info ) ) {
    1681           0 :       ctx->prev_epoch_info = ctx->curr_epoch_info;
    1682           0 :       ctx->prev_epoch_slot = ctx->curr_epoch_slot;
    1683           0 :       ctx->curr_epoch_info = ctx->next_epoch_info;
    1684           0 :       ctx->curr_epoch_slot = ctx->next_epoch_slot;
    1685           0 :     }
    1686           0 :     ctx->next_epoch_info = epoch_info;
    1687           0 :     ctx->next_epoch_slot = msg->start_slot;
    1688           0 :   }
    1689             : 
    1690             :   /* mark all for deletion */
    1691             : 
    1692           0 :   for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); slot++ ) {
    1693           0 :     peer_t * peer = &ctx->peers[ slot ];
    1694           0 :     if( FD_LIKELY( peers_key_inval( peer->id_key ) ) ) continue;
    1695           0 :     peer->prev_rank = USHORT_MAX;
    1696           0 :     peer->curr_rank = USHORT_MAX;
    1697           0 :     peer->next_rank = USHORT_MAX;
    1698           0 :   }
    1699             : 
    1700             :   /* unmark all ranked in prev epoch */
    1701             : 
    1702           0 :   ulong prev_cnt = ctx->prev_epoch_info ? ctx->prev_epoch_info->validator_cnt : 0UL;
    1703           0 :   for( ulong rank=0UL; rank<prev_cnt; rank++ ) {
    1704           0 :     fd_pubkey_t id_key;
    1705           0 :     memcpy( id_key.uc, ctx->prev_epoch_info->validators[ rank ].id_key, sizeof(fd_pubkey_t) );
    1706             : 
    1707           0 :     peer_t * peer = peers_query( ctx->peers, id_key, NULL );
    1708           0 :     if( FD_UNLIKELY( !peer ) ) {
    1709           0 :       peer                 = peers_insert( ctx->peers, id_key );
    1710           0 :       peer->curr_rank      = USHORT_MAX;
    1711           0 :       peer->next_rank      = USHORT_MAX;
    1712           0 :       peer->tx_conn        = NULL;
    1713           0 :       memset( peer->rx_conn, 0, sizeof(peer->rx_conn) );
    1714           0 :       peer->ban_ts         = 0L;
    1715           0 :       peer->conn_ts        = 0L;
    1716           0 :       peer->conn_backoff   = 0L;
    1717           0 :       peer->reconn_pending = 0;
    1718           0 :     }
    1719           0 :     peer->prev_rank = (ushort)rank;
    1720           0 :   }
    1721             : 
    1722             :   /* unmark all ranked in curr epoch */
    1723             : 
    1724           0 :   ushort own_rank = USHORT_MAX; /* our own rank in the new epoch */
    1725           0 :   for( ulong rank=0UL; rank<ctx->curr_epoch_info->validator_cnt; rank++ ) {
    1726           0 :     fd_pubkey_t id_key;
    1727           0 :     memcpy( id_key.uc, ctx->curr_epoch_info->validators[ rank ].id_key, sizeof(fd_pubkey_t) );
    1728           0 :     if( FD_UNLIKELY( ctx->curr_epoch_info==epoch_info && fd_pubkey_eq( &id_key, &ctx->id_key ) ) ) own_rank = (ushort)rank;
    1729             : 
    1730           0 :     peer_t * peer = peers_query( ctx->peers, id_key, NULL );
    1731           0 :     if( FD_UNLIKELY( !peer ) ) {
    1732           0 :       peer                 = peers_insert( ctx->peers, id_key );
    1733           0 :       peer->prev_rank      = USHORT_MAX;
    1734           0 :       peer->next_rank      = USHORT_MAX;
    1735           0 :       peer->tx_conn        = NULL;
    1736           0 :       memset( peer->rx_conn, 0, sizeof(peer->rx_conn) );
    1737           0 :       peer->ban_ts         = 0L;
    1738           0 :       peer->conn_ts        = 0L;
    1739           0 :       peer->conn_backoff   = 0L;
    1740           0 :       peer->reconn_pending = 0;
    1741           0 :     }
    1742           0 :     peer->curr_rank = (ushort)rank;
    1743           0 :   }
    1744             : 
    1745             :   /* unmark all ranked in next epoch */
    1746             : 
    1747           0 :   ulong next_cnt = ctx->next_epoch_info ? ctx->next_epoch_info->validator_cnt : 0UL;
    1748           0 :   for( ulong rank=0UL; rank<next_cnt; rank++ ) {
    1749           0 :     fd_pubkey_t id_key;
    1750           0 :     memcpy( id_key.uc, ctx->next_epoch_info->validators[ rank ].id_key, sizeof(fd_pubkey_t) );
    1751           0 :     if( FD_UNLIKELY( ctx->next_epoch_info==epoch_info && fd_pubkey_eq( &id_key, &ctx->id_key ) ) ) own_rank = (ushort)rank;
    1752             : 
    1753           0 :     peer_t * peer = peers_query( ctx->peers, id_key, NULL );
    1754           0 :     if( FD_UNLIKELY( !peer ) ) {
    1755           0 :       peer                 = peers_insert( ctx->peers, id_key );
    1756           0 :       peer->prev_rank      = USHORT_MAX;
    1757           0 :       peer->curr_rank      = USHORT_MAX;
    1758           0 :       peer->tx_conn        = NULL;
    1759           0 :       memset( peer->rx_conn, 0, sizeof(peer->rx_conn) );
    1760           0 :       peer->ban_ts         = 0L;
    1761           0 :       peer->conn_ts        = 0L;
    1762           0 :       peer->conn_backoff   = 0L;
    1763           0 :       peer->reconn_pending = 0;
    1764           0 :     }
    1765           0 :     peer->next_rank = (ushort)rank;
    1766           0 :   }
    1767             : 
    1768             :   /* quic_connect new peers */
    1769             : 
    1770           0 :   for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); slot++ ) {
    1771           0 :     peer_t * peer = &ctx->peers[ slot ];
    1772           0 :     if( FD_LIKELY( peers_key_inval( peer->id_key ) ) ) continue;
    1773           0 :     contact_info_t const * ci = contact_infos_query( ctx->contact_infos, peer->id_key, NULL );
    1774           0 :     if( FD_LIKELY( ci ) ) quic_client_connect( ctx, peer, ci, fd_clock_tile_now( ctx->clock ) );
    1775           0 :   }
    1776             : 
    1777             :   /* quic_conn_close evicted peers */
    1778             : 
    1779           0 :   for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); ) {
    1780           0 :     peer_t * peer = &ctx->peers[ slot ];
    1781           0 :     if( FD_LIKELY( peers_key_inval( peer->id_key ) ) ) {
    1782           0 :       slot++;
    1783           0 :       continue;
    1784           0 :     }
    1785           0 :     if( FD_LIKELY( peer->prev_rank != USHORT_MAX || peer->curr_rank != USHORT_MAX || peer->next_rank != USHORT_MAX ) ) {
    1786           0 :       slot++;
    1787           0 :       continue;
    1788           0 :     }
    1789           0 :     if( FD_LIKELY( peer->tx_conn ) ) {
    1790           0 :       fd_quic_conn_set_context( peer->tx_conn, NULL );
    1791           0 :       fd_quic_conn_close( peer->tx_conn, QUIC_CLOSE_CODE_NOT_ADMITTED );
    1792           0 :       peer->tx_conn = NULL;
    1793           0 :     }
    1794           0 :     for( ulong i=0UL; i<QUIC_SERVER_CONN_PER_PEER_MAX; i++ ) {
    1795           0 :       if( FD_UNLIKELY( !peer->rx_conn[ i ] ) ) continue;
    1796           0 :       fd_quic_conn_set_context( peer->rx_conn[ i ], NULL );
    1797           0 :       fd_quic_conn_close( peer->rx_conn[ i ], QUIC_CLOSE_CODE_NOT_ADMITTED );
    1798           0 :       peer->rx_conn[ i ] = NULL;
    1799           0 :     }
    1800           0 :     if( FD_UNLIKELY( peer->reconn_pending ) ) {
    1801           0 :       for( ulong i=0UL; i<reconn_prq_cnt( ctx->reconn_prq ); i++ ) {
    1802           0 :         if( FD_UNLIKELY( fd_pubkey_eq( &ctx->reconn_prq[i].id_key, &peer->id_key ) ) ) {
    1803           0 :           reconn_prq_remove( ctx->reconn_prq, i );
    1804           0 :           break;
    1805           0 :         }
    1806           0 :       }
    1807           0 :     }
    1808           0 :     contact_info_t * ci = contact_infos_query( ctx->contact_infos, peer->id_key, NULL );
    1809           0 :     if( FD_UNLIKELY( ci && ci->removed ) ) contact_infos_remove( ctx->contact_infos, ci );
    1810           0 :     peers_remove( ctx->peers, peer ); /* relocates, so reconsider the freed slot */
    1811           0 :   }
    1812             : 
    1813             :   /* The latest epoch's slot time, only for the connect-ahead estimate:
    1814             :      votor times each window's skip deadlines by its own epoch's. */
    1815             : 
    1816           0 :   ctx->ns_per_slot     = (long)msg->ns_per_slot;
    1817           0 :   ctx->epoch_slot_cnt  = msg->slot_cnt;
    1818             : 
    1819           0 :   if( FD_UNLIKELY( ctx->failover_enabled && !ctx->vote_authority ) ) own_rank = USHORT_MAX;
    1820           0 :   fd_votor_pool_advance_epoch( ctx->pool,  epoch_info,       own_rank, msg->start_slot );
    1821           0 :   fd_votor_loop_advance_epoch( ctx->votor, ctx->ns_per_slot, own_rank, msg->start_slot, NULL );
    1822           0 :   update_own_bls_key( ctx );
    1823             : 
    1824             :   /* update our leader schedule */
    1825             : 
    1826           0 :   fd_multi_epoch_leaders_epoch_msg_init( ctx->mleaders, msg );
    1827           0 :   fd_multi_epoch_leaders_epoch_msg_fini( ctx->mleaders );
    1828             :   /* Slot 0 is genesis.  Slot 1 is ParentReady on genesis (see
    1829             :      fd_parent_ready_tracker_mark_root) even though it does not start a
    1830             :      window. */
    1831           0 :   if( FD_UNLIKELY( ctx->next_leader_slot==ULONG_MAX ) ) ctx->next_leader_slot = fd_multi_epoch_leaders_get_next_slot( ctx->mleaders, fd_ulong_max( fd_ulong_max( msg->start_slot, 1UL ), ctx->vote_history_slot ), &ctx->id_key );
    1832             : 
    1833           0 :   ctx->init = !!ctx->next_epoch_info && fd_votor_pool_finalized_slot( ctx->pool )!=ULONG_MAX && !!ctx->shred_version && wfs_is_ready( ctx );
    1834           0 : }
    1835             : 
    1836             : static void
    1837             : handle_gossip( fd_votor_tile_t *                  ctx,
    1838             :                ulong                              sig,
    1839           0 :                fd_gossip_update_message_t const * msg ) {
    1840             : 
    1841           0 :   fd_pubkey_t id_key;
    1842           0 :   memcpy( id_key.uc, msg->origin, sizeof(fd_pubkey_t) );
    1843           0 :   if( FD_UNLIKELY( peers_key_inval( id_key ) ) ) return;
    1844             : 
    1845           0 :   contact_info_t * ci   = contact_infos_query( ctx->contact_infos, id_key, NULL );
    1846           0 :   peer_t *         peer = peers_query        ( ctx->peers,         id_key, NULL );
    1847             : 
    1848           0 :   switch( sig ) {
    1849           0 :   case FD_GOSSIP_UPDATE_TAG_CONTACT_INFO: {
    1850           0 :     fd_gossip_socket_t const * socket = &msg->contact_info->value->sockets[FD_GOSSIP_CONTACT_INFO_SOCKET_ALPENGLOW];
    1851           0 :     uint                       ip4    = fd_uint_if( !socket->is_ipv6, socket->ip4, 0U );
    1852           0 :     ushort                     port   = fd_ushort_bswap( socket->port );
    1853             : 
    1854             :     /* ip 0 or port 0 is invalid to connect to, remove them */
    1855             : 
    1856           0 :     if( FD_UNLIKELY( !ip4 || !port ) ) {
    1857           0 :       if( FD_LIKELY( ci ) ) contact_infos_remove( ctx->contact_infos, ci );
    1858           0 :       return;
    1859           0 :     }
    1860             : 
    1861             :     /* short-circuit ci, if it didn't change (common case) */
    1862             : 
    1863           0 :     if( FD_LIKELY( ci && ci->ip4==ip4 && ci->port==port ) ) { ci->removed = 0; return; }
    1864             : 
    1865             :     /* upsert the ci */
    1866             : 
    1867           0 :     if( FD_UNLIKELY( !ci ) ) ci = contact_infos_insert( ctx->contact_infos, id_key );
    1868           0 :     ci->ip4     = ip4;
    1869           0 :     ci->port    = port;
    1870           0 :     ci->removed = 0;
    1871           0 :     if( FD_LIKELY( !peer ) ) return;
    1872           0 :     if( FD_UNLIKELY( peer->tx_conn ) ) {
    1873           0 :       fd_quic_conn_set_context( peer->tx_conn, NULL );
    1874           0 :       fd_quic_conn_close( peer->tx_conn, 0U );
    1875           0 :       peer->tx_conn = NULL;
    1876           0 :     }
    1877           0 :     peer->conn_backoff = 0L;
    1878           0 :     quic_client_connect( ctx, peer, ci, fd_clock_tile_now( ctx->clock ) );
    1879           0 :     break;
    1880           0 :   }
    1881           0 :   case FD_GOSSIP_UPDATE_TAG_CONTACT_INFO_REMOVE:
    1882           0 :     if( FD_LIKELY  ( ci && !peer ) ) contact_infos_remove( ctx->contact_infos, ci );
    1883           0 :     if( FD_UNLIKELY( ci &&  peer ) ) ci->removed = 1; /* a peer's is kept, to redial its last address */
    1884           0 :     break;
    1885           0 :   default:
    1886           0 :     FD_LOG_ERR(( "unexpected gossip sig %lu", sig ));
    1887           0 :   }
    1888           0 : }
    1889             : 
    1890             : static void
    1891             : handle_replay( fd_votor_tile_t *           ctx,
    1892             :                ulong                       sig,
    1893           0 :                fd_replay_message_t const * replay ) {
    1894             : 
    1895           0 :   fd_block_footer_t const * footer = NULL;
    1896           0 :   switch( sig ) {
    1897           0 :   case REPLAY_SIG_SLOT_COMPLETED: {
    1898           0 :     fd_replay_slot_completed_t const * slot_completed  = &replay->slot_completed;
    1899           0 :     fd_block_id_t                      block_id        = fd_block_id( slot_completed->slot,        slot_completed->block_id.uc        );
    1900           0 :     fd_block_id_t                      parent_block_id = fd_block_id( slot_completed->parent_slot, slot_completed->parent_block_id.uc );
    1901           0 :     if( FD_UNLIKELY( ctx->failover_enabled ) ) failover_slot_completed( ctx, slot_completed );
    1902           0 :     if( FD_UNLIKELY( fd_votor_pool_finalized_slot( ctx->pool )==ULONG_MAX ) ) {
    1903           0 :       ctx->boot_block_id = block_id;
    1904             : 
    1905             :       /* A cluster restart, booting at the wait-for-supermajority slot,
    1906             :          starts a new fork, so votes before it no longer bind, as in
    1907             :          Agave's maybe_cluster_restart_with_hard_fork. */
    1908             : 
    1909           0 :       if( FD_UNLIKELY( fd_wfs_mode( ctx->wfs_slot, ctx->wfs_hash_is_zero, (ulong)ctx->wfs_shred_version, block_id.slot )==FD_WFS_MODE_MATCH && ctx->vote_history_slot ) ) {
    1910           0 :         FD_LOG_WARNING(( "cluster restart at slot %lu, discarding the vote history floor %lu", block_id.slot, ctx->vote_history_slot ));
    1911           0 :         ctx->vote_history_slot         = 0UL;
    1912           0 :         ctx->highest_vote_or_lead_slot = 0UL;
    1913           0 :         ctx->next_leader_slot          = fd_multi_epoch_leaders_get_next_slot( ctx->mleaders, fd_ulong_max( ctx->curr_epoch_slot, 1UL ), &ctx->id_key );
    1914           0 :       }
    1915             : 
    1916           0 :       if( block_id.slot==0UL ) fd_votor_pool_from_genesis ( ctx->pool, &block_id );
    1917           0 :       else                     fd_votor_pool_from_snapshot( ctx->pool, &block_id );
    1918           0 :       int wfs = wfs_is_ready( ctx );
    1919             :       /* Without ipecho's shred version, init must be deferred. */
    1920           0 :       if( FD_LIKELY( ctx->shred_version ) ) {
    1921           0 :         long now = fd_clock_tile_now( ctx->clock );
    1922           0 :         fd_votor_loop_init( ctx->votor, &block_id, now, ctx->ns_per_slot, ctx->shred_version, sign_vote, ctx );
    1923           0 :         ctx->highest_vote_or_lead_slot = fd_ulong_max( ctx->highest_vote_or_lead_slot, block_id.slot );
    1924           0 :         if( FD_LIKELY( wfs ) ) fd_votor_loop_arm_skip_timeouts( ctx->votor, now );
    1925           0 :       }
    1926           0 :       ctx->init = !!ctx->next_epoch_info && !!ctx->shred_version && wfs;
    1927           0 :     } else if( FD_UNLIKELY( block_id.slot!=0 ) ) {
    1928           0 :       fd_votor_pool_add_block( ctx->pool, &block_id, &parent_block_id, ctx->scratch.bad );
    1929           0 :       if( FD_UNLIKELY( !fd_bls_set_is_null( ctx->scratch.bad ) ) ) ban_bad_ranks( ctx, ctx->scratch.bad, block_id.slot );
    1930           0 :     }
    1931           0 :     fd_block_info_t block_info = { .parent = parent_block_id };
    1932           0 :     memcpy( &block_info.hash, &block_id.hash, sizeof(fd_block_hash_t) );
    1933           0 :     if( FD_LIKELY( ctx->init ) ) fd_votor_loop_process_replay( ctx->votor, block_id.slot, &block_info );
    1934             : 
    1935           0 :     ulong           reward_slot = block_id.slot-FD_VOTOR_REWARD_SLOT_DELTA;
    1936           0 :     reward_vote_t * rv          = &ctx->reward_votes[ reward_slot%REWARD_VOTE_MAX ];
    1937           0 :     if( FD_UNLIKELY( block_id.slot>=FD_VOTOR_REWARD_SLOT_DELTA && rv->slot==reward_slot ) ) rv->slot = ULONG_MAX;
    1938             : 
    1939           0 :     footer = &slot_completed->footer;
    1940           0 :     break;
    1941           0 :   }
    1942           0 :   case REPLAY_SIG_SLOT_DEAD:
    1943           0 :     footer = &replay->slot_dead.footer;
    1944           0 :     break;
    1945           0 :   default:
    1946           0 :     FD_LOG_ERR(( "unexpected replay sig %lu", sig ));
    1947           0 :   }
    1948             : 
    1949           0 :   if( FD_UNLIKELY( !ctx->init ) ) return;
    1950             : 
    1951             :   /* Replay verified these certs before publishing the footer (or, as
    1952             :      leader, built them from ours), so skip re-verifying them. */
    1953           0 :   fd_cert_t * cert = &ctx->scratch.cert;
    1954           0 :   if( FD_LIKELY( footer->has_fast_final_cert ) ) {
    1955           0 :     *cert = (fd_cert_t){ .kind = FD_CERT_KIND_FAST_FINAL, .fast_final = { .slot = footer->fast_final_cert.slot, .shred_version = ctx->shred_version } };
    1956           0 :     memcpy( &cert->fast_final.block_hash, footer->fast_final_cert.block_id.uc, sizeof(fd_block_hash_t) );
    1957           0 :     fd_bls_set_copy( cert->fast_final.agg.set, footer->fast_final_cert.signer_set );
    1958           0 :     FD_TEST( !fd_bls_sig_de_compressed( &cert->fast_final.agg.sig, footer->fast_final_cert.sig ) );
    1959           0 :     fd_votor_pool_add_cert( ctx->pool, cert, 1, ctx->scratch.bad );
    1960           0 :     if( FD_UNLIKELY( !fd_bls_set_is_null( ctx->scratch.bad ) ) ) ban_bad_ranks( ctx, ctx->scratch.bad, cert->fast_final.slot );
    1961           0 :   } else if( FD_LIKELY( footer->has_final_cert ) ) {
    1962           0 :     *cert = (fd_cert_t){ .kind = FD_CERT_KIND_FINAL, .final = { .slot = footer->final_cert.slot, .shred_version = ctx->shred_version } };
    1963           0 :     fd_bls_set_copy( cert->final.agg.set, footer->final_cert.signer_set );
    1964           0 :     FD_TEST( !fd_bls_sig_de_compressed( &cert->final.agg.sig, footer->final_cert.sig ) );
    1965           0 :     fd_votor_pool_add_cert( ctx->pool, cert, 1, ctx->scratch.bad );
    1966           0 :     if( FD_UNLIKELY( !fd_bls_set_is_null( ctx->scratch.bad ) ) ) ban_bad_ranks( ctx, ctx->scratch.bad, cert->final.slot );
    1967             : 
    1968           0 :     *cert = (fd_cert_t){ .kind = FD_CERT_KIND_NOTAR, .notar = { .slot = footer->notar_cert.slot, .shred_version = ctx->shred_version } };
    1969           0 :     memcpy( &cert->notar.block_hash, footer->notar_cert.block_id.uc, sizeof(fd_block_hash_t) );
    1970           0 :     fd_bls_set_copy( cert->notar.agg.set, footer->notar_cert.signer_set );
    1971           0 :     FD_TEST( !fd_bls_sig_de_compressed( &cert->notar.agg.sig, footer->notar_cert.sig ) );
    1972           0 :     fd_votor_pool_add_cert( ctx->pool, cert, 1, ctx->scratch.bad );
    1973           0 :     if( FD_UNLIKELY( !fd_bls_set_is_null( ctx->scratch.bad ) ) ) ban_bad_ranks( ctx, ctx->scratch.bad, cert->notar.slot );
    1974           0 :   }
    1975           0 : }
    1976             : 
    1977             : FD_FN_CONST static inline ulong
    1978           0 : scratch_align( void ) {
    1979           0 :   return fd_ulong_max( alignof(fd_votor_tile_t), fd_quic_align() );
    1980           0 : }
    1981             : 
    1982             : FD_FN_PURE static inline ulong
    1983           0 : scratch_footprint( fd_topo_tile_t const * tile ) {
    1984           0 :   ulong l = FD_LAYOUT_INIT;
    1985           0 :   l = FD_LAYOUT_APPEND( l, alignof(fd_votor_tile_t),       sizeof(fd_votor_tile_t)                                                 );
    1986           0 :   l = FD_LAYOUT_APPEND( l, auth_vtr_align(),               auth_vtr_footprint()                                                    );
    1987           0 :   l = FD_LAYOUT_APPEND( l, fd_quic_align(),                fd_quic_footprint( &quic_client_limits )                                );
    1988           0 :   l = FD_LAYOUT_APPEND( l, fd_quic_align(),                fd_quic_footprint( &quic_server_limits )                                );
    1989           0 :   l = FD_LAYOUT_APPEND( l, fd_votor_pool_align(),          fd_votor_pool_footprint( tile->votor.max_live_slots, QUIC_DGRAM_BURST ) );
    1990           0 :   l = FD_LAYOUT_APPEND( l, fd_votor_loop_align(),          fd_votor_loop_footprint( tile->votor.max_live_slots )                   );
    1991           0 :   l = FD_LAYOUT_APPEND( l, peers_align(),                  peers_footprint( PEERS_LG_SLOT_CNT )                                    );
    1992           0 :   l = FD_LAYOUT_APPEND( l, contact_infos_align(),          contact_infos_footprint( CONTACT_INFOS_LG_SLOT_CNT )                    );
    1993           0 :   l = FD_LAYOUT_APPEND( l, reconn_prq_align(),             reconn_prq_footprint( RECONN_MAX )                                      );
    1994           0 :   l = FD_LAYOUT_APPEND( l, fd_multi_epoch_leaders_align(), fd_multi_epoch_leaders_footprint()                                      );
    1995           0 :   return FD_LAYOUT_FINI( l, scratch_align() );
    1996           0 : }
    1997             : 
    1998             : static void
    1999           0 : during_housekeeping( fd_votor_tile_t * ctx ) {
    2000           0 :   if( FD_UNLIKELY( fd_clock_tile_recal_due( ctx->clock ) ) ) fd_clock_tile_recal( ctx->clock );
    2001             : 
    2002             :   /* Spread handshakes to newly ranked peers across 10 seconds. */
    2003             : 
    2004           0 :   if( FD_UNLIKELY( ctx->conn_ahead_slot!=ctx->next_epoch_slot ) ) {
    2005           0 :     peer_t const * self = peers_query( ctx->peers, ctx->id_key, NULL );
    2006           0 :     ulong          root = fd_votor_pool_finalized_slot( ctx->pool );
    2007           0 :     if( FD_UNLIKELY( !self || self->curr_rank!=USHORT_MAX || self->next_rank==USHORT_MAX ) ) {
    2008           0 :       ctx->conn_ahead_slot = ctx->next_epoch_slot;
    2009           0 :     } else if( FD_UNLIKELY( root!=ULONG_MAX && ( root>=ctx->next_epoch_slot || (long)( ctx->next_epoch_slot-root )*ctx->ns_per_slot<=QUIC_CLIENT_CONN_AHEAD_NS ) ) ) {
    2010           0 :       ctx->conn_ahead_slot = ctx->next_epoch_slot;
    2011           0 :       ulong cnt = 0UL;
    2012           0 :       for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); slot++ ) {
    2013           0 :         peer_t const * peer = &ctx->peers[ slot ];
    2014           0 :         cnt += (ulong)( !peers_key_inval( peer->id_key ) && peer!=self && !peer->tx_conn && !peer->reconn_pending && contact_infos_query( ctx->contact_infos, peer->id_key, NULL ) );
    2015           0 :       }
    2016           0 :       long  now = fd_clock_tile_now( ctx->clock );
    2017           0 :       ulong idx = 0UL;
    2018           0 :       for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); slot++ ) {
    2019           0 :         peer_t * peer = &ctx->peers[ slot ];
    2020           0 :         if( FD_UNLIKELY( peers_key_inval( peer->id_key ) || peer==self || peer->tx_conn || peer->reconn_pending || !contact_infos_query( ctx->contact_infos, peer->id_key, NULL ) ) ) continue;
    2021           0 :         reconn_t reconn = { .timeout = now+(long)idx*(QUIC_CLIENT_CONN_AHEAD_NS/2L)/(long)cnt, .id_key = peer->id_key };
    2022           0 :         reconn_prq_insert( ctx->reconn_prq, &reconn );
    2023           0 :         peer->reconn_pending = 1;
    2024           0 :         idx++;
    2025           0 :       }
    2026           0 :     }
    2027           0 :   }
    2028             : 
    2029           0 :   if( FD_UNLIKELY( fd_keyswitch_state_query( ctx->auth_vtr_keyswitch )==FD_KEYSWITCH_STATE_UNHALT_PENDING ) ) {
    2030           0 :     fd_keyswitch_state( ctx->auth_vtr_keyswitch, FD_KEYSWITCH_STATE_UNLOCKED );
    2031           0 :   }
    2032             : 
    2033             :   /* Important invariant is that the sign tile has already been updated
    2034             :      and that the votor is fully in sync with the sign tile. */
    2035             : 
    2036           0 :   if( FD_UNLIKELY( fd_keyswitch_state_query( ctx->auth_vtr_keyswitch )==FD_KEYSWITCH_STATE_SWITCH_PENDING ) ) {
    2037           0 :     ulong          param = fd_keyswitch_param_query( ctx->auth_vtr_keyswitch );
    2038           0 :     auth_vtr_key_t bls_key;
    2039           0 :     if( FD_LIKELY( param==FD_KEYSWITCH_PARAM_AV_ADD ) ) {
    2040             : 
    2041             :       /* For a new authorized voter, derive the BLS pubkey from the sign
    2042             :          tile and add to the auth voter map. */
    2043             : 
    2044           0 :       if( FD_UNLIKELY( ctx->auth_vtr_path_cnt==FD_KEYGUARD_AUTH_VOTERS_MAX ) ) FD_LOG_CRIT(( "keyswitch: too many authorized voters, keys not synced up with sign tile" ));
    2045           0 :       fd_keyguard_client_bls_pubkey( ctx->keyguard_client, bls_key.uc, ctx->auth_vtr_path_cnt );
    2046           0 :       auth_vtr_t const * exists = auth_vtr_query_const( ctx->auth_vtr, bls_key, NULL );
    2047           0 :       if( FD_UNLIKELY( exists && exists->paths_idx!=ULONG_MAX ) ) FD_LOG_CRIT(( "keyswitch: duplicate authorized voter key, keys not synced up with sign tile" ));
    2048           0 :       if( FD_LIKELY( !exists ) ) auth_vtr_insert( ctx->auth_vtr, bls_key )->paths_idx = ctx->auth_vtr_path_cnt;
    2049           0 :       ctx->auth_vtr_path_cnt++;
    2050             : 
    2051           0 :     } else if( FD_LIKELY( param==FD_KEYSWITCH_PARAM_AV_CLEAR ) ) {
    2052             : 
    2053             :       /* Nuke the entire set of auth voters and just rederive the BLS
    2054             :          pubkey for the identity from the sign tile. */
    2055             : 
    2056           0 :       load_keys( ctx, 0UL );
    2057           0 :     } else {
    2058           0 :       FD_LOG_CRIT(( "keyswitch: unexpected authorized voter operation %lu", param ));
    2059           0 :     }
    2060             : 
    2061             :     /* The epochs votor holds chose their keys when they advanced, so
    2062             :        choose them again for each of them. */
    2063             : 
    2064           0 :     FD_LOG_INFO(( "keyswitch: authorized voter count is now %lu", ctx->auth_vtr_path_cnt ));
    2065           0 :     update_own_bls_key( ctx );
    2066           0 :     fd_keyswitch_state( ctx->auth_vtr_keyswitch, FD_KEYSWITCH_STATE_COMPLETED );
    2067           0 :   }
    2068             : 
    2069             :   /* Identity key switch.  The admin tile halts votor right after replay
    2070             :      but there may be frags in flight.  Votor needs to consume up to and
    2071             :      including the latest recorded replay message.  Votor also needs to
    2072             :      wait for all outgoing votes to drain as well, and for queued pool
    2073             :      events, which the pool decided with the old identity's rank. */
    2074             : 
    2075           0 :   if( FD_UNLIKELY( fd_keyswitch_state_query( ctx->id_keyswitch )==FD_KEYSWITCH_STATE_SWITCH_PENDING ) ) {
    2076           0 :     if( FD_UNLIKELY( fd_seq_lt( ctx->replay_in_seq, fd_keyswitch_param_query( ctx->id_keyswitch ) ) ) ) return;
    2077             : 
    2078             :     /* Halt signing at first. */
    2079             : 
    2080           0 :     ctx->keyswitch_state = FD_KEYSWITCH_STATE_SWITCH_PENDING;
    2081             : 
    2082             :     /* If votes and pool events drained close quic conns and update
    2083             :        leader tracking.  The pool queue drains only under ctx->init,
    2084             :        so waiting on it while held never completes: a late ipecho
    2085             :        stalls there, and under WFS the boot ParentReady sits in
    2086             :        it for the whole wait.  Skipping it is safe because no vote
    2087             :        built while halted is signed, so none decided under the old
    2088             :        identity goes out. */
    2089             : 
    2090           0 :     if( FD_LIKELY( !fd_votor_loop_metrics( ctx->votor ).vote_events_cnt &&
    2091           0 :                    ( !ctx->init || !fd_votor_pool_metrics( ctx->pool ).pool_events_cnt ) ) ) {
    2092             : 
    2093             :       /* Save the votes drained since the halt as the old identity.  The
    2094             :          admin tile switches the sign tile only after this completes. */
    2095             : 
    2096           0 :       if( FD_LIKELY( ctx->vote_history_fd_dir!=-1 ) ) write_vote_history( ctx );
    2097             :       /* Leaving an identity saves its file as its .bak, and hands the
    2098             :          spare, the .bak votor holds, to the new identity as its staging
    2099             :          file.  The new identity's file is named only once it is written
    2100             :          at unhalt, so a restart before then finds no file and refuses to
    2101             :          boot rather than reading an empty one as never voted. */
    2102             : 
    2103           0 :       if( FD_LIKELY( ctx->vote_history_fd_dir!=-1 ) ) {
    2104           0 :         FD_BASE58_ENCODE_32_BYTES( ctx->id_key.uc,           id_key_b58 );
    2105           0 :         FD_BASE58_ENCODE_32_BYTES( ctx->id_keyswitch->bytes, switch_b58 );
    2106           0 :         FD_BASE58_ENCODE_32_BYTES( ctx->id_key_bak.uc,       spare_b58  );
    2107           0 :         char swp       [ PATH_MAX ];
    2108           0 :         char bin       [ PATH_MAX ];
    2109           0 :         char bak       [ PATH_MAX ];
    2110           0 :         char spare     [ PATH_MAX ];
    2111           0 :         char switch_swp[ PATH_MAX ];
    2112           0 :         char switch_bin[ PATH_MAX ];
    2113           0 :         char switch_bak[ PATH_MAX ];
    2114           0 :         FD_TEST( fd_cstr_printf_check( swp,        PATH_MAX, NULL, "vote_history-%s.bin.swp", id_key_b58 ) );
    2115           0 :         FD_TEST( fd_cstr_printf_check( bin,        PATH_MAX, NULL, "vote_history-%s.bin",     id_key_b58 ) );
    2116           0 :         FD_TEST( fd_cstr_printf_check( bak,        PATH_MAX, NULL, "vote_history-%s.bin.bak", id_key_b58 ) );
    2117           0 :         FD_TEST( fd_cstr_printf_check( spare,      PATH_MAX, NULL, "vote_history-%s.bin.bak", spare_b58  ) );
    2118           0 :         FD_TEST( fd_cstr_printf_check( switch_swp, PATH_MAX, NULL, "vote_history-%s.bin.swp", switch_b58 ) );
    2119           0 :         FD_TEST( fd_cstr_printf_check( switch_bin, PATH_MAX, NULL, "vote_history-%s.bin",     switch_b58 ) );
    2120           0 :         FD_TEST( fd_cstr_printf_check( switch_bak, PATH_MAX, NULL, "vote_history-%s.bin.bak", switch_b58 ) );
    2121           0 :         int spare_mine   = fd_pubkey_eq( &ctx->id_key_bak, &ctx->id_key );
    2122           0 :         int spare_switch = !memcmp( ctx->id_key_bak.uc, ctx->id_keyswitch->bytes, sizeof(fd_pubkey_t) );
    2123           0 :         if( FD_UNLIKELY( ctx->vote_history_bak_full && !spare_mine && !spare_switch ) ) {
    2124           0 :           FD_LOG_WARNING(( "reusing vote history file %s for %s.  Copy it out first to keep that identity's vote history", spare, switch_bin ));
    2125           0 :         }
    2126           0 :         FD_LOG_NOTICE(( "vote history file %s saved as %s", bin, bak ));
    2127           0 :         if( FD_UNLIKELY( !spare_switch && syscall( SYS_renameat2, ctx->vote_history_fd_dir, switch_bin, ctx->vote_history_fd_dir, switch_bak, 0 ) && errno!=ENOENT ) )
    2128           0 :           FD_LOG_ERR(( "renameat2(%s, %s) failed (%i-%s)", switch_bin, switch_bak, errno, fd_io_strerror( errno ) ));
    2129           0 :         if( FD_UNLIKELY( syscall( SYS_renameat2, ctx->vote_history_fd_dir, spare, ctx->vote_history_fd_dir, switch_swp, 0 ) ) )
    2130           0 :           FD_LOG_ERR(( "renameat2(%s, %s) failed (%i-%s)", spare, switch_swp, errno, fd_io_strerror( errno ) ));
    2131           0 :         if( FD_UNLIKELY( syscall( SYS_renameat2, ctx->vote_history_fd_dir, bin, ctx->vote_history_fd_dir, bak, 0 ) ) )
    2132           0 :           FD_LOG_ERR(( "renameat2(%s, %s) failed (%i-%s)", bin, bak, errno, fd_io_strerror( errno ) ));
    2133           0 :         int fd = ctx->vote_history_fd_bak;
    2134           0 :         ctx->vote_history_fd_bak   = ctx->vote_history_fd;
    2135           0 :         ctx->vote_history_fd       = ctx->vote_history_fd_swp;
    2136           0 :         ctx->vote_history_fd_swp   = fd;
    2137           0 :         ctx->id_key_bak            = ctx->id_key;
    2138           0 :         ctx->vote_history_bak_full = 1;
    2139           0 :       }
    2140           0 :       memcpy( ctx->id_key.uc, ctx->id_keyswitch->bytes, sizeof(fd_pubkey_t) );
    2141           0 :       ctx->vote_history_slot         = fd_ulong_max( FD_LOAD( ulong, ctx->id_keyswitch->bytes+32UL ), fd_first_slot_in_window( ctx->highest_vote_or_lead_slot )+FD_VOTOR_SLOTS_PER_WINDOW );
    2142           0 :       ctx->highest_vote_or_lead_slot = fd_ulong_max( ctx->highest_vote_or_lead_slot, fd_ulong_sat_sub( ctx->vote_history_slot, 1UL ) );
    2143           0 :       fd_quic_set_identity_public_key( ctx->quic_client, ctx->id_key.uc );
    2144           0 :       fd_quic_set_identity_public_key( ctx->quic_server, ctx->id_key.uc );
    2145           0 :       for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); slot++ ) {
    2146           0 :         peer_t * peer = &ctx->peers[ slot ];
    2147           0 :         if( FD_LIKELY( peers_key_inval( peer->id_key ) ) ) continue;
    2148           0 :         if( FD_LIKELY( peer->tx_conn ) ) {
    2149           0 :           fd_quic_conn_set_context( peer->tx_conn, NULL );
    2150           0 :           fd_quic_conn_close( peer->tx_conn, 0U );
    2151           0 :           peer->tx_conn = NULL;
    2152           0 :         }
    2153           0 :       }
    2154             : 
    2155             :       /* Keep established server conns, which identify the peer, not us.
    2156             :          Close handshakes in progress, which are not yet rx_conns and
    2157             :          would complete as the old identity. */
    2158             : 
    2159           0 :       fd_quic_state_t * server_state = fd_quic_get_state( ctx->quic_server );
    2160           0 :       for( ulong i=0UL; i<ctx->quic_server->limits.conn_cnt; i++ ) {
    2161           0 :         fd_quic_conn_t * conn = fd_quic_conn_at_idx( server_state, i );
    2162           0 :         if( FD_LIKELY( conn->state!=FD_QUIC_CONN_STATE_HANDSHAKE && conn->state!=FD_QUIC_CONN_STATE_HANDSHAKE_COMPLETE ) ) continue;
    2163           0 :         fd_quic_conn_set_context( conn, NULL );
    2164           0 :         fd_quic_conn_close( conn, 0U );
    2165           0 :       }
    2166           0 :       for( ulong i=0UL; i<REWARD_VOTE_MAX; i++ ) ctx->reward_votes[ i ].slot = ULONG_MAX;
    2167           0 :       for( ulong i=0UL; i<FD_VOTOR_SLOTS_PER_WINDOW; i++ ) ctx->reward_certs[ i ] = (reward_cert_t){ .slot = ULONG_MAX };
    2168             : 
    2169             :       /* Skip the window in progress, it may already have a leader, and
    2170             :          those below the floor, which the identity may have voted or led
    2171             :          in here or on another machine. */
    2172             : 
    2173           0 :       ulong next_window = fd_first_slot_in_window( ctx->highest_parent_ready_slot )+FD_VOTOR_SLOTS_PER_WINDOW;
    2174           0 :       ctx->next_leader_slot = fd_multi_epoch_leaders_get_next_slot( ctx->mleaders, fd_ulong_max( fd_ulong_max( ctx->curr_epoch_slot, next_window ), ctx->vote_history_slot ), &ctx->id_key );
    2175           0 :       if( FD_UNLIKELY( ctx->failover_enabled ) ) failover_switched( ctx );
    2176           0 :       ctx->keyswitch_state  = FD_KEYSWITCH_STATE_COMPLETED;
    2177           0 :       fd_keyswitch_state( ctx->id_keyswitch, FD_KEYSWITCH_STATE_COMPLETED );
    2178           0 :     }
    2179           0 :   }
    2180             : 
    2181             :   /* Once we can resume signing load auth voters and reconn to peers.
    2182             :      Votor signs nothing in slots it already voted in. */
    2183             : 
    2184           0 :   if( FD_UNLIKELY( fd_keyswitch_state_query( ctx->id_keyswitch )==FD_KEYSWITCH_STATE_UNHALT_PENDING ) ) {
    2185           0 :     FD_CHECK_CRIT( ctx->keyswitch_state==FD_KEYSWITCH_STATE_COMPLETED, "state machine corruption" );
    2186           0 :     load_keys( ctx, ctx->auth_vtr_path_cnt );
    2187             :     /* A failover promotion adopted its votes per slot, so it votes on in the adopted window. The file still covers it for a restart. */
    2188           0 :     if( FD_LIKELY( !ctx->installed_by_failover ) ) ctx->vote_history_slot = fd_ulong_max( ctx->vote_history_slot, fd_first_slot_in_window( ctx->highest_vote_or_lead_slot )+FD_VOTOR_SLOTS_PER_WINDOW );
    2189           0 :     if( FD_LIKELY( ctx->vote_history_fd_dir!=-1 ) ) write_vote_history( ctx ); /* the sign tile has the new key, so its floor is on disk before it votes */
    2190           0 :     ctx->keyswitch_state = FD_KEYSWITCH_STATE_UNLOCKED;
    2191           0 :     update_own_rank( ctx );
    2192           0 :     update_own_bls_key( ctx );
    2193           0 :     fd_votor_pool_standstill_iter_init( ctx->standstill_iter, ctx->pool ); /* its next vote was copied as the old identity */
    2194           0 :     for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); slot++ ) {
    2195           0 :       peer_t * peer = &ctx->peers[ slot ];
    2196           0 :       if( FD_LIKELY( peers_key_inval( peer->id_key ) ) ) continue;
    2197           0 :       contact_info_t const * ci = contact_infos_query( ctx->contact_infos, peer->id_key, NULL );
    2198           0 :       if( FD_LIKELY( ci ) ) quic_client_connect( ctx, peer, ci, fd_clock_tile_now( ctx->clock ) );
    2199           0 :     }
    2200           0 :     fd_keyswitch_state( ctx->id_keyswitch, FD_KEYSWITCH_STATE_COMPLETED );
    2201           0 :   }
    2202           0 : }
    2203             : 
    2204             : static inline long
    2205           0 : next_deadline( fd_votor_tile_t * ctx ) {
    2206           0 :   long reconn = reconn_prq_cnt( ctx->reconn_prq ) ? ctx->reconn_prq[ 0 ].timeout : LONG_MAX;
    2207           0 :   long next   = fd_long_min( fd_long_min( fd_quic_get_next_wakeup( ctx->quic_client ), fd_quic_get_next_wakeup( ctx->quic_server ) ), reconn );
    2208           0 :   if( FD_LIKELY( ctx->init ) ) {
    2209           0 :     next = fd_long_min( next, fd_votor_loop_next_skip_timeout( ctx->votor ) );
    2210           0 :     next = fd_long_min( next, ctx->standstill_ts );
    2211           0 :     for( ulong i=0UL; i<REWARD_VOTE_MAX; i++ ) {
    2212           0 :       reward_vote_t const * rv = &ctx->reward_votes[ i ];
    2213           0 :       if( FD_LIKELY( rv->slot==ULONG_MAX || rv->retry_ts>=next ) ) continue;
    2214           0 :       next = rv->retry_ts;
    2215           0 :     }
    2216           0 :     for( ulong i=0UL; i<FD_VOTOR_SLOTS_PER_WINDOW; i++ ) {
    2217           0 :       reward_cert_t const * rc = &ctx->reward_certs[ i ];
    2218           0 :       if( FD_LIKELY( rc->dirty ) ) next = fd_long_min( next, rc->publish_ts+REWARD_REPUBLISH_NS );
    2219           0 :     }
    2220           0 :   }
    2221           0 :   return next==LONG_MAX ? LONG_MAX : fd_clock_tile_wallclock_to_tickcount( ctx->clock, next );
    2222           0 : }
    2223             : 
    2224             : static void
    2225           0 : metrics_write( fd_votor_tile_t * ctx ) {
    2226           0 :   FD_MCNT_ENUM_COPY( VOTOR, DATAGRAM_RX, ctx->metrics.datagram_rx );
    2227           0 :   FD_MCNT_ENUM_COPY( VOTOR, VOTE_RX,     ctx->metrics.vote_rx     );
    2228           0 :   FD_MCNT_ENUM_COPY( VOTOR, CERT_RX,     ctx->metrics.cert_rx     );
    2229             : 
    2230           0 :   FD_MCNT_SET  ( VOTOR, VOTE_HISTORY_FILE_WRITTEN,    ctx->metrics.vote_history_write     );
    2231           0 :   FD_MGAUGE_SET( VOTOR, WAIT_TO_VOTE_SLOT,            ctx->vote_history_slot              );
    2232             : 
    2233           0 :   fd_votor_loop_metrics_t votor_metrics = fd_votor_loop_metrics( ctx->votor );
    2234           0 :   FD_MGAUGE_SET( VOTOR, VOTING_SLOT_USED,        votor_metrics.slot_state_pool_used );
    2235           0 :   FD_MGAUGE_SET( VOTOR, VOTING_SLOT_FREE,        votor_metrics.slot_state_pool_free );
    2236           0 :   FD_MGAUGE_SET( VOTOR, HIGHEST_FINAL_CERT_SLOT, fd_ulong_if( votor_metrics.highest_final_slot!=ULONG_MAX, votor_metrics.highest_final_slot, 0UL ) );
    2237             : 
    2238           0 :   fd_votor_pool_metrics_t pool_metrics = fd_votor_pool_metrics( ctx->pool );
    2239           0 :   FD_MGAUGE_SET( VOTOR, POOL_SLOT_USED,                    pool_metrics.slot_state_pool_used );
    2240           0 :   FD_MGAUGE_SET( VOTOR, POOL_SLOT_FREE,                    pool_metrics.slot_state_pool_free );
    2241           0 :   FD_MGAUGE_SET( VOTOR, HIGHEST_POOL_FINALIZED_SLOT,       fd_ulong_if( pool_metrics.finalized_slot!=ULONG_MAX, pool_metrics.finalized_slot, 0UL ) );
    2242           0 :   FD_MCNT_SET  ( VOTOR, BLS_SIGNATURE_CHECKED,             pool_metrics.bls_verify_cnt+ctx->metrics.bls_verify );
    2243           0 :   FD_MCNT_SET  ( VOTOR, LEADER_WINDOW_SUPERSEDED,          ctx->metrics.leader_window_superseded );
    2244           0 :   FD_MCNT_SET  ( VOTOR, CERT_TX_UNSTAKED_SKIPPED,          ctx->metrics.cert_tx_unstaked );
    2245             : 
    2246           0 :   peer_t const * self = peers_query( ctx->peers, ctx->id_key, NULL );
    2247           0 :   ulong rank = self && self->curr_rank!=USHORT_MAX ? self->curr_rank : ULONG_MAX;
    2248           0 :   FD_MGAUGE_SET( VOTOR, RANK, rank );
    2249             : 
    2250             : 
    2251             :   /* QUIC client (outbound conns) */
    2252             : 
    2253           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_PKT_RX_BYTES,                 ctx->quic_client->metrics.net_rx_byte_cnt+sizeof(fd_eth_hdr_t)*ctx->quic_client->metrics.net_rx_pkt_cnt );
    2254           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, CLIENT_FRAME_RX,                     ctx->quic_client->metrics.frame_rx_cnt            );
    2255           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_PKT_RX,                       ctx->quic_client->metrics.net_rx_pkt_cnt          );
    2256           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_PKT_TX,                       ctx->quic_client->metrics.net_tx_pkt_cnt          );
    2257           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_PKT_TX_BYTES,                 ctx->quic_client->metrics.net_tx_byte_cnt+sizeof(fd_eth_hdr_t)*ctx->quic_client->metrics.net_tx_pkt_cnt );
    2258           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, CLIENT_PKT_ACK_PROCESSED,            ctx->quic_client->metrics.ack_tx                  );
    2259           0 :   FD_MGAUGE_ENUM_COPY( VOTOR, CLIENT_CONN_USED,                    (ctx->quic_client->metrics.conn_state_cnt+1)      ); /* skip FD_QUIC_CONN_STATE_INVALID (free slots) */
    2260           0 :   FD_MGAUGE_SET      ( VOTOR, CLIENT_CONN_FREE,                    ctx->quic_client->limits.conn_cnt-ctx->quic_client->metrics.conn_alloc_cnt );
    2261           0 :   FD_MGAUGE_SET      ( VOTOR, CLIENT_CONN_CAPACITY,                ctx->quic_client->limits.conn_cnt                 );
    2262           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_CONN_CREATED,                 ctx->quic_client->metrics.conn_created_cnt        );
    2263           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_CONN_CLOSED,                  ctx->quic_client->metrics.conn_closed_cnt         );
    2264           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_CONN_ABORTED,                 ctx->quic_client->metrics.conn_aborted_cnt        );
    2265           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_CONN_TIMED_OUT,               ctx->quic_client->metrics.conn_timeout_cnt        );
    2266           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_CONN_NO_SLOT_REJECTED,        ctx->quic_client->metrics.conn_err_no_slots_cnt   );
    2267           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_CONN_RETRY_REJECTED,          ctx->quic_client->metrics.conn_err_retry_fail_cnt );
    2268           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, CLIENT_PKT_DECRYPT_FAILED,           ctx->quic_client->metrics.pkt_decrypt_fail_cnt    );
    2269           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, CLIENT_PKT_NO_KEY_DROPPED,           ctx->quic_client->metrics.pkt_no_key_cnt          );
    2270           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, CLIENT_PKT_NO_CONN_DROPPED,          ctx->quic_client->metrics.pkt_no_conn_cnt         );
    2271           0 :   ulong pkt_drop_client[ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_CNT ] = {
    2272           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_UNDERSIZE_IDX           ] = ctx->quic_client->metrics.pkt_undersz_cnt,
    2273           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_OVERSIZE_IDX            ] = ctx->quic_client->metrics.pkt_oversz_cnt,
    2274           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_SRC_IP_MISMATCH_IDX     ] = ctx->quic_client->metrics.pkt_wrong_src_cnt,
    2275           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_HEADER_INVALID_IDX      ] = ctx->quic_client->metrics.pkt_quic_hdr_err_cnt,
    2276           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_NET_HEADER_INVALID_IDX  ] = ctx->quic_client->metrics.pkt_net_hdr_err_cnt,
    2277           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_VERSION_UNSUPPORTED_IDX ] = ctx->quic_client->metrics.pkt_verneg_cnt,
    2278           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_DUPLICATE_IDX           ] = ctx->quic_client->metrics.pkt_dup_cnt,
    2279           0 :   };
    2280           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, CLIENT_PKT_DROPPED,                  pkt_drop_client                             );
    2281           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, CLIENT_PKT_META_ACQUIRE_ATTEMPTED,   ctx->quic_client->metrics.frame_tx_alloc_cnt      );
    2282           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, CLIENT_PKT_RETRANSMITTED,            ctx->quic_client->metrics.pkt_retransmissions_cnt );
    2283           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_HANDSHAKE_CREATED,            ctx->quic_client->metrics.hs_created_cnt          );
    2284           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_HANDSHAKE_POOL_FULL_REJECTED, ctx->quic_client->metrics.hs_err_alloc_fail_cnt   );
    2285           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_HANDSHAKE_EVICTED,            ctx->quic_client->metrics.hs_evicted_cnt          );
    2286           0 :   FD_MCNT_SET        ( VOTOR, CLIENT_FRAME_PARSE_FAILED,           ctx->quic_client->metrics.frame_rx_err_cnt        );
    2287           0 :   FD_MHIST_COPY      ( VOTOR, CLIENT_SERVICE_DURATION_NANOS,       ctx->quic_client->metrics.service_duration        );
    2288           0 :   FD_MHIST_COPY      ( VOTOR, CLIENT_PKT_RX_DURATION_NANOS,        ctx->quic_client->metrics.receive_duration        );
    2289             : 
    2290             :   /* QUIC server (inbound conns) */
    2291             : 
    2292           0 :   FD_MCNT_SET        ( VOTOR, SERVER_PKT_RX_BYTES,                 ctx->quic_server->metrics.net_rx_byte_cnt+sizeof(fd_eth_hdr_t)*ctx->quic_server->metrics.net_rx_pkt_cnt );
    2293           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, SERVER_FRAME_RX,                     ctx->quic_server->metrics.frame_rx_cnt            );
    2294           0 :   FD_MCNT_SET        ( VOTOR, SERVER_PKT_RX,                       ctx->quic_server->metrics.net_rx_pkt_cnt          );
    2295           0 :   FD_MCNT_SET        ( VOTOR, SERVER_PKT_TX,                       ctx->quic_server->metrics.net_tx_pkt_cnt          );
    2296           0 :   FD_MCNT_SET        ( VOTOR, SERVER_PKT_TX_BYTES,                 ctx->quic_server->metrics.net_tx_byte_cnt+sizeof(fd_eth_hdr_t)*ctx->quic_server->metrics.net_tx_pkt_cnt );
    2297           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, SERVER_PKT_ACK_PROCESSED,            ctx->quic_server->metrics.ack_tx                  );
    2298           0 :   FD_MGAUGE_ENUM_COPY( VOTOR, SERVER_CONN_USED,                    (ctx->quic_server->metrics.conn_state_cnt+1)      ); /* skip FD_QUIC_CONN_STATE_INVALID (free slots) */
    2299           0 :   FD_MGAUGE_SET      ( VOTOR, SERVER_CONN_FREE,                    ctx->quic_server->limits.conn_cnt-ctx->quic_server->metrics.conn_alloc_cnt );
    2300           0 :   FD_MGAUGE_SET      ( VOTOR, SERVER_CONN_CAPACITY,                ctx->quic_server->limits.conn_cnt                 );
    2301           0 :   FD_MCNT_SET        ( VOTOR, SERVER_CONN_CREATED,                 ctx->quic_server->metrics.conn_created_cnt        );
    2302           0 :   FD_MCNT_SET        ( VOTOR, SERVER_CONN_CLOSED,                  ctx->quic_server->metrics.conn_closed_cnt         );
    2303           0 :   FD_MCNT_SET        ( VOTOR, SERVER_CONN_ABORTED,                 ctx->quic_server->metrics.conn_aborted_cnt        );
    2304           0 :   FD_MCNT_SET        ( VOTOR, SERVER_CONN_TIMED_OUT,               ctx->quic_server->metrics.conn_timeout_cnt        );
    2305           0 :   FD_MCNT_SET        ( VOTOR, SERVER_CONN_NO_SLOT_REJECTED,        ctx->quic_server->metrics.conn_err_no_slots_cnt   );
    2306           0 :   FD_MCNT_SET        ( VOTOR, SERVER_CONN_RETRY_REJECTED,          ctx->quic_server->metrics.conn_err_retry_fail_cnt );
    2307           0 :   FD_MCNT_SET        ( VOTOR, SERVER_CONN_RETRY_EXPIRED_REJECTED,  ctx->quic_server->metrics.conn_err_retry_expired_cnt );
    2308           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, SERVER_PKT_DECRYPT_FAILED,           ctx->quic_server->metrics.pkt_decrypt_fail_cnt    );
    2309           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, SERVER_PKT_NO_KEY_DROPPED,           ctx->quic_server->metrics.pkt_no_key_cnt          );
    2310           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, SERVER_PKT_NO_CONN_DROPPED,          ctx->quic_server->metrics.pkt_no_conn_cnt         );
    2311           0 :   ulong pkt_drop_server[ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_CNT ] = {
    2312           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_UNDERSIZE_IDX           ] = ctx->quic_server->metrics.pkt_undersz_cnt,
    2313           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_OVERSIZE_IDX            ] = ctx->quic_server->metrics.pkt_oversz_cnt,
    2314           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_SRC_IP_MISMATCH_IDX     ] = ctx->quic_server->metrics.pkt_wrong_src_cnt,
    2315           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_HEADER_INVALID_IDX      ] = ctx->quic_server->metrics.pkt_quic_hdr_err_cnt,
    2316           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_NET_HEADER_INVALID_IDX  ] = ctx->quic_server->metrics.pkt_net_hdr_err_cnt,
    2317           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_VERSION_UNSUPPORTED_IDX ] = ctx->quic_server->metrics.pkt_verneg_cnt,
    2318           0 :     [ FD_METRICS_ENUM_QUIC_PKT_DROP_REASON_V_DUPLICATE_IDX           ] = ctx->quic_server->metrics.pkt_dup_cnt,
    2319           0 :   };
    2320           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, SERVER_PKT_DROPPED,                  pkt_drop_server                             );
    2321           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, SERVER_PKT_META_ACQUIRE_ATTEMPTED,   ctx->quic_server->metrics.frame_tx_alloc_cnt      );
    2322           0 :   FD_MCNT_ENUM_COPY  ( VOTOR, SERVER_PKT_RETRANSMITTED,            ctx->quic_server->metrics.pkt_retransmissions_cnt );
    2323           0 :   FD_MCNT_SET        ( VOTOR, SERVER_HANDSHAKE_CREATED,            ctx->quic_server->metrics.hs_created_cnt          );
    2324           0 :   FD_MCNT_SET        ( VOTOR, SERVER_HANDSHAKE_POOL_FULL_REJECTED, ctx->quic_server->metrics.hs_err_alloc_fail_cnt   );
    2325           0 :   FD_MCNT_SET        ( VOTOR, SERVER_HANDSHAKE_EVICTED,            ctx->quic_server->metrics.hs_evicted_cnt          );
    2326           0 :   FD_MCNT_SET        ( VOTOR, SERVER_FRAME_PARSE_FAILED,           ctx->quic_server->metrics.frame_rx_err_cnt        );
    2327           0 :   FD_MHIST_COPY      ( VOTOR, SERVER_SERVICE_DURATION_NANOS,       ctx->quic_server->metrics.service_duration        );
    2328           0 :   FD_MHIST_COPY      ( VOTOR, SERVER_PKT_RX_DURATION_NANOS,        ctx->quic_server->metrics.receive_duration        );
    2329           0 : }
    2330             : 
    2331             : /* after_credit is the tile's event loop.  Each step handles at most
    2332             :    one item per pass, at most 9 votor_out frags in all:
    2333             : 
    2334             :    1. notify if we can become leader
    2335             :    2. retry un-acked reward votes
    2336             :    3. republish reward certs new votes widened (one per tile loop)
    2337             :    4. poll pool, repair, timeout events (can result in new votes, one per tile loop)
    2338             :    5. broadcast new votes (one per tile loop)
    2339             :    6. standstill re-broadcast */
    2340             : 
    2341             : static inline void
    2342             : after_credit( fd_votor_tile_t *   ctx,
    2343             :               fd_stem_context_t * stem,
    2344             :               int *               opt_poll_in,
    2345           0 :               int *               charge_busy ) {
    2346             : 
    2347           0 :   long now = fd_clock_tile_now( ctx->clock );
    2348             : 
    2349             :   /* Reconnect any dropped QUIC conns. */
    2350             : 
    2351           0 :   while( FD_UNLIKELY( reconn_prq_cnt( ctx->reconn_prq ) && ctx->reconn_prq[ 0 ].timeout<=now ) ) {
    2352           0 :     fd_pubkey_t id_key = ctx->reconn_prq[ 0 ].id_key;
    2353           0 :     reconn_prq_remove_min( ctx->reconn_prq );
    2354           0 :     peer_t * peer = peers_query( ctx->peers, id_key, NULL );
    2355           0 :     if( FD_UNLIKELY( !peer ) ) continue;
    2356           0 :     peer->reconn_pending = 0;
    2357           0 :     contact_info_t const * ci = contact_infos_query( ctx->contact_infos, id_key, NULL );
    2358           0 :     if( FD_UNLIKELY( !ci ) ) continue;
    2359           0 :     if( FD_UNLIKELY( now<peer->conn_ts+peer->conn_backoff ) ) {
    2360           0 :       reconn_t reconn = { .timeout = peer->conn_ts+peer->conn_backoff, .id_key = id_key };
    2361           0 :       reconn_prq_insert( ctx->reconn_prq, &reconn );
    2362           0 :       peer->reconn_pending = 1;
    2363           0 :       continue;
    2364           0 :     }
    2365           0 :     quic_client_connect( ctx, peer, ci, now );
    2366           0 :     *charge_busy = 1;
    2367           0 :   }
    2368             : 
    2369             :   /* Service both QUIC client and server. */
    2370             : 
    2371           0 :   *charge_busy = fd_quic_service( ctx->quic_client, now ) | fd_quic_service( ctx->quic_server, now );
    2372           0 :   for( ulong i=0UL; i<ctx->net_tx_cnt; i++ ) fd_stem_publish( stem, OUT_IDX_NET, ctx->net_tx[ i ].sig, ctx->net_tx[ i ].chunk, ctx->net_tx[ i ].sz, fd_frag_meta_ctl( 0UL, 1, 1, 0 ), 0L, 0L );
    2373           0 :   ctx->net_tx_cnt = 0UL;
    2374             : 
    2375             :   /* Not initialized. */
    2376             : 
    2377           0 :   if( FD_UNLIKELY( !ctx->init ) ) return;
    2378             : 
    2379             :   /* 1. Notify if we can become leader. */
    2380             : 
    2381           0 :   while( FD_UNLIKELY(    ctx->next_leader_slot!=ULONG_MAX
    2382           0 :                       && ( ctx->next_leader_slot<=fd_votor_pool_finalized_slot( ctx->pool )
    2383           0 :                         || ctx->next_leader_slot+ctx->slot_max<=ctx->catchup_slot
    2384           0 :                         || ctx->next_leader_slot<ctx->vote_history_slot
    2385           0 :                         || ctx->next_leader_slot<fd_votor_pool_highest_parent_ready( ctx->pool ) ) ) ) {
    2386           0 :     ctx->metrics.leader_window_superseded += (ulong)( ctx->next_leader_slot<fd_votor_pool_highest_parent_ready( ctx->pool ) );
    2387           0 :     ctx->next_leader_slot = fd_multi_epoch_leaders_get_next_slot( ctx->mleaders, fd_first_slot_in_window( ctx->next_leader_slot )+FD_VOTOR_SLOTS_PER_WINDOW, &ctx->id_key );
    2388           0 :   }
    2389           0 :   fd_block_id_t parent = { .slot = ULONG_MAX }; /* never will be leader, schedule exhausted, or the pool has not granted parent ready yet */
    2390           0 :   if( FD_LIKELY( ctx->next_leader_slot!=ULONG_MAX && ( !ctx->failover_enabled || ctx->vote_authority ) ) )
    2391           0 :     parent = fd_votor_pool_wait_for_parent_ready( ctx->pool, ctx->next_leader_slot );
    2392           0 :   if( FD_UNLIKELY( parent.slot!=ULONG_MAX && !ctx->keyswitch_state ) ) {
    2393           0 :     ctx->highest_vote_or_lead_slot = fd_ulong_max( ctx->highest_vote_or_lead_slot, fd_first_slot_in_window( ctx->next_leader_slot )+FD_VOTOR_SLOTS_PER_WINDOW-1UL );
    2394           0 :     if( FD_LIKELY( ctx->vote_history_fd_dir!=-1 ) ) write_vote_history( ctx ); /* a restart does not lead the window again */
    2395           0 :     fd_votor_msg_t * chunk = fd_chunk_to_laddr( ctx->votor_out_mem, ctx->votor_out_chunk );
    2396           0 :     chunk->leader = (fd_votor_leader_t){ .slot = ctx->next_leader_slot, .parent_slot = parent.slot, .parent_block_id = FD_LOAD( fd_hash_t, parent.hash.uc ), .parent_ready_ns = now };
    2397           0 :     fd_stem_publish( stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_LEADER, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    2398           0 :     ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    2399             : 
    2400           0 :     ulong reward_slot = fd_ulong_sat_sub( ctx->next_leader_slot, FD_NUM_SLOTS_FOR_REWARD );
    2401           0 :     for( ulong i=0UL; i<FD_VOTOR_SLOTS_PER_WINDOW; i++ ) publish_reward_cert( ctx, stem, reward_slot+i );
    2402             : 
    2403           0 :     if( FD_UNLIKELY( ctx->failover_enabled ) ) failover_after_leader( ctx, stem );
    2404           0 :     ctx->next_leader_slot = fd_multi_epoch_leaders_get_next_slot( ctx->mleaders, fd_first_slot_in_window( ctx->next_leader_slot )+FD_VOTOR_SLOTS_PER_WINDOW, &ctx->id_key );
    2405           0 :     *charge_busy = 1;
    2406           0 :   }
    2407             : 
    2408             :   /* 2. Retry un-acked reward votes. */
    2409             : 
    2410           0 :   for( ulong i=0UL; i<REWARD_VOTE_MAX; i++ ) {
    2411           0 :     reward_vote_t * rv = &ctx->reward_votes[ i ];
    2412           0 :     if( FD_LIKELY( rv->slot==ULONG_MAX || now<rv->retry_ts ) ) continue;
    2413           0 :     if( FD_UNLIKELY( rv->tx_cnt==REWARD_VOTE_TX_MAX ) ) { rv->slot = ULONG_MAX; continue; } /* slot+8's footer has sealed */
    2414           0 :     peer_t const * peer = reward_leader( ctx, rv, now );
    2415           0 :     if( FD_UNLIKELY( !peer ) ) {
    2416           0 :       rv->retry_ts = now+REWARD_VOTE_RTT_MIN_NS;
    2417           0 :       continue;
    2418           0 :     }
    2419           0 :     publish_reward_vote( ctx, stem, rv, peer, now );
    2420           0 :     *charge_busy = 1;
    2421           0 :   }
    2422             : 
    2423             :   /* 3. Republish reward certs new votes widened. */
    2424             : 
    2425           0 :   for( ulong i=0UL; i<FD_VOTOR_SLOTS_PER_WINDOW; i++ ) {
    2426           0 :     reward_cert_t * rc = &ctx->reward_certs[ i ];
    2427           0 :     if( FD_LIKELY( !rc->dirty || now<rc->publish_ts+REWARD_REPUBLISH_NS ) ) continue;
    2428           0 :     if( FD_UNLIKELY( ctx->highest_parent_ready_slot>=fd_first_slot_in_window( rc->slot+FD_VOTOR_REWARD_SLOT_DELTA )+FD_VOTOR_SLOTS_PER_WINDOW ) ) { rc->slot = ULONG_MAX; rc->dirty = 0; continue; } /* our leader window is over */
    2429           0 :     publish_reward_cert( ctx, stem, rc->slot );
    2430           0 :     *charge_busy = 1;
    2431           0 :     break;
    2432           0 :   }
    2433             : 
    2434             :   /* 4a. Poll pool events. */
    2435             : 
    2436           0 :   int pool_event = fd_votor_pool_poll_pool_event( ctx->pool, &ctx->scratch.pool_event );
    2437           0 :   if( FD_UNLIKELY( pool_event ) ) {
    2438           0 :     fd_votor_pool_event_t const * event = &ctx->scratch.pool_event;
    2439           0 :     fd_cert_t const * broadcast = NULL;
    2440           0 :     if( FD_LIKELY( event->kind!=FD_VOTOR_POOL_EVENT_IMPLICITLY_FINALIZED && event->kind!=FD_VOTOR_POOL_EVENT_IMPLICITLY_SKIPPED ) ) broadcast = fd_votor_loop_handle_pool_event( ctx->votor, event, now );
    2441           0 :     ulong          cert_slot = broadcast ? fd_cert_slot( broadcast ) : 0UL;
    2442           0 :     peer_t const * self      = broadcast ? peers_query( ctx->peers, ctx->id_key, NULL ) : NULL;
    2443           0 :     int            unstaked  = !self || USHORT_MAX==fd_ushort_if( cert_slot>=ctx->next_epoch_slot, self->next_rank, fd_ushort_if( cert_slot>=ctx->curr_epoch_slot, self->curr_rank, self->prev_rank ) ); /* peers only accept staked conns */
    2444           0 :     if( FD_UNLIKELY( broadcast && cert_slot>=ctx->catchup_vote_slot && unstaked ) ) ctx->metrics.cert_tx_unstaked++;
    2445           0 :     if( FD_UNLIKELY( broadcast && cert_slot>=ctx->catchup_vote_slot && !unstaked ) ) {
    2446           0 :       ulong ser_sz               = fd_cert_ser( broadcast, ctx->scratch.ser );
    2447           0 :       long  broadcast_start_time = fd_clock_tile_now( ctx->clock );
    2448           0 :       for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); slot++ ) {
    2449           0 :         peer_t const * peer = &ctx->peers[ slot ];
    2450           0 :         if( FD_LIKELY( peers_key_inval( peer->id_key ) || !peer->tx_conn || peer->tx_conn->state!=FD_QUIC_CONN_STATE_ACTIVE ) ) continue;
    2451           0 :         quic_client_datagram_tx( ctx, stem, peer->tx_conn, ctx->scratch.ser, ser_sz );
    2452           0 :       }
    2453             : 
    2454           0 :       ulong stake;
    2455           0 :       switch( broadcast->kind ) {
    2456           0 :       case FD_CERT_KIND_FINAL:          stake = broadcast->final.stake;          break;
    2457           0 :       case FD_CERT_KIND_FAST_FINAL:     stake = broadcast->fast_final.stake;     break;
    2458           0 :       case FD_CERT_KIND_NOTAR:          stake = broadcast->notar.stake;          break;
    2459           0 :       case FD_CERT_KIND_NOTAR_FALLBACK: stake = broadcast->notar_fallback.stake; break;
    2460           0 :       case FD_CERT_KIND_SKIP:           stake = broadcast->skip.stake;           break;
    2461           0 :       default:                          FD_LOG_CRIT(( "unreachable" ));
    2462           0 :       }
    2463           0 :       if( FD_UNLIKELY( stake ) ) report_alpenglow_cert( ctx, NULL, broadcast, ctx->scratch.ser[ 1 ], FD_EVENT_ALPENGLOW_CERT_PROCESSING_RESULT_ACCEPTED, 0L, broadcast_start_time );
    2464           0 :     }
    2465             : 
    2466           0 :     if( FD_UNLIKELY( event->kind==FD_VOTOR_POOL_EVENT_SAFE_TO_NOTAR || event->kind==FD_VOTOR_POOL_EVENT_IMPLICITLY_FINALIZED || event->kind==FD_VOTOR_POOL_EVENT_IMPLICITLY_SKIPPED ) ) {
    2467           0 :       fd_votor_quorum_t * quorum = &((fd_votor_msg_t *)fd_chunk_to_laddr( ctx->votor_out_mem, ctx->votor_out_chunk ))->quorum;
    2468           0 :       *quorum = (fd_votor_quorum_t){0};
    2469           0 :       switch( event->kind ) {
    2470           0 :       case FD_VOTOR_POOL_EVENT_SAFE_TO_NOTAR:
    2471           0 :         quorum->kind     = FD_VOTOR_QUORUM_KIND_SAFE_TO_NOTAR;
    2472           0 :         quorum->slot     = event->safe_to_notar.slot;
    2473           0 :         quorum->block_id = FD_LOAD( fd_hash_t, event->safe_to_notar.hash.uc );
    2474           0 :         break;
    2475           0 :       case FD_VOTOR_POOL_EVENT_IMPLICITLY_FINALIZED:
    2476           0 :         quorum->kind     = FD_VOTOR_QUORUM_KIND_IMPLICITLY_FINALIZED;
    2477           0 :         quorum->slot     = event->implicitly_finalized.slot;
    2478           0 :         quorum->block_id = FD_LOAD( fd_hash_t, event->implicitly_finalized.hash.uc );
    2479           0 :         break;
    2480           0 :       case FD_VOTOR_POOL_EVENT_IMPLICITLY_SKIPPED:
    2481           0 :         quorum->kind = FD_VOTOR_QUORUM_KIND_IMPLICITLY_SKIPPED;
    2482           0 :         quorum->slot = event->implicitly_skipped;
    2483           0 :         break;
    2484           0 :       default:
    2485           0 :         FD_LOG_CRIT(( "unreachable" ));
    2486           0 :       }
    2487           0 :       fd_stem_publish( stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_QUORUM, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    2488           0 :       ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    2489           0 :     }
    2490           0 :     if( FD_UNLIKELY( ctx->scratch.pool_event.kind==FD_VOTOR_POOL_EVENT_PARENT_READY && ctx->scratch.pool_event.parent_ready.slot>ctx->highest_parent_ready_slot ) ) {
    2491           0 :       ctx->highest_parent_ready_slot = ctx->scratch.pool_event.parent_ready.slot;
    2492           0 :       fd_votor_msg_t * msg = fd_chunk_to_laddr( ctx->votor_out_mem, ctx->votor_out_chunk );
    2493           0 :       msg->parent_ready = (fd_votor_parent_ready_t){ .slot = ctx->highest_parent_ready_slot }; /* a LEADER already sent may now be stale */
    2494           0 :       fd_stem_publish( stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_PARENT_READY, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    2495           0 :       ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    2496           0 :     }
    2497             : 
    2498           0 :     fd_cert_t const * cert = &ctx->scratch.pool_event.cert_created;
    2499           0 :     if( FD_UNLIKELY( ctx->scratch.pool_event.kind==FD_VOTOR_POOL_EVENT_CERT_CREATED ) ) {
    2500           0 :       ulong               slot   = fd_cert_slot( cert );
    2501           0 :       fd_votor_msg_t *    chunk  = fd_chunk_to_laddr( ctx->votor_out_mem, ctx->votor_out_chunk );
    2502           0 :       fd_votor_certed_t * certed = &chunk->certed;
    2503           0 :       switch( cert->kind ) {
    2504           0 :       case FD_CERT_KIND_FINAL: {
    2505           0 :         fd_cert_final_t   final_cert;
    2506           0 :         fd_cert_notar_t   notar_cert;
    2507           0 :         fd_cert_final_t * final = fd_votor_pool_final_cert( ctx->pool, slot, &final_cert );
    2508           0 :         fd_cert_notar_t * notar = fd_votor_pool_notar_cert( ctx->pool, slot, &notar_cert );
    2509           0 :         if( FD_LIKELY( final && notar && slot>ctx->highest_certed_final_slot ) ) {
    2510           0 :           *certed = (fd_votor_certed_t){ .kind = cert->kind, .slot = slot, .block_id = FD_LOAD( fd_hash_t, notar->block_hash.uc ), .agg = final->agg, .agg2 = notar->agg };
    2511           0 :           fd_stem_publish( stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_CERTED, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    2512           0 :           ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    2513           0 :           ctx->highest_certed_final_slot = slot;
    2514           0 :         }
    2515           0 :         break;
    2516           0 :       }
    2517           0 :       case FD_CERT_KIND_FAST_FINAL:
    2518           0 :         *certed = (fd_votor_certed_t){ .kind = cert->kind, .slot = slot, .block_id = FD_LOAD( fd_hash_t, cert->fast_final.block_hash.uc ), .agg = cert->fast_final.agg };
    2519           0 :         fd_stem_publish( stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_CERTED, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    2520           0 :         ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    2521           0 :         break;
    2522           0 :       case FD_CERT_KIND_NOTAR: {
    2523           0 :         *certed = (fd_votor_certed_t){ .kind = cert->kind, .slot = slot, .block_id = FD_LOAD( fd_hash_t, cert->notar.block_hash.uc ), .agg = cert->notar.agg };
    2524           0 :         fd_stem_publish( stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_CERTED, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    2525           0 :         ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    2526             : 
    2527             : 
    2528           0 :         fd_cert_final_t   final_cert;
    2529           0 :         fd_cert_final_t * final = fd_votor_pool_final_cert( ctx->pool, slot, &final_cert );
    2530           0 :         if( FD_UNLIKELY( final && slot>ctx->highest_certed_final_slot ) ) {
    2531           0 :           chunk   = fd_chunk_to_laddr( ctx->votor_out_mem, ctx->votor_out_chunk );
    2532           0 :           certed  = &chunk->certed;
    2533           0 :           *certed = (fd_votor_certed_t){ .kind = FD_CERT_KIND_FINAL, .slot = slot, .block_id = FD_LOAD( fd_hash_t, cert->notar.block_hash.uc ), .agg = final->agg, .agg2 = cert->notar.agg };
    2534           0 :           fd_stem_publish( stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_CERTED, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    2535           0 :           ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    2536           0 :           ctx->highest_certed_final_slot = slot;
    2537           0 :         }
    2538           0 :         break;
    2539           0 :       }
    2540           0 :       case FD_CERT_KIND_NOTAR_FALLBACK:
    2541           0 :         *certed = (fd_votor_certed_t){ .kind = cert->kind, .slot = slot, .block_id = FD_LOAD( fd_hash_t, cert->notar_fallback.block_hash.uc ), .agg = cert->notar_fallback.agg_notar, .agg2 = cert->notar_fallback.agg_notar_fallback };
    2542           0 :         fd_stem_publish( stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_CERTED, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    2543           0 :         ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    2544           0 :         break;
    2545           0 :       case FD_CERT_KIND_SKIP:
    2546           0 :         *certed = (fd_votor_certed_t){ .kind = cert->kind, .slot = slot, .agg = cert->skip.agg_skip, .agg2 = cert->skip.agg_skip_fallback };
    2547           0 :         fd_stem_publish( stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_CERTED, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    2548           0 :         ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    2549           0 :         break;
    2550           0 :       default:
    2551           0 :         FD_LOG_CRIT(( "unreachable" ));
    2552           0 :       }
    2553           0 :     }
    2554           0 :     *opt_poll_in = 0;
    2555           0 :     *charge_busy = 1;
    2556           0 :   }
    2557             : 
    2558             :   /* 4b. Poll repair events. */
    2559             : 
    2560           0 :   int repair_event = fd_votor_pool_poll_repair_event( ctx->pool, &ctx->scratch.repair_event );
    2561           0 :   if( FD_UNLIKELY( repair_event ) ) {
    2562           0 :     fd_votor_msg_t * chunk = fd_chunk_to_laddr( ctx->votor_out_mem, ctx->votor_out_chunk );
    2563           0 :     chunk->repair = (fd_votor_repair_t){ .slot = ctx->scratch.repair_event.slot, .block_id = FD_LOAD( fd_hash_t, ctx->scratch.repair_event.hash.uc ) };
    2564           0 :     fd_stem_publish( stem, OUT_IDX_VOTOR, FD_VOTOR_SIG_REPAIR, ctx->votor_out_chunk, sizeof(fd_votor_msg_t), 0UL, fd_frag_meta_ts_comp( fd_tickcount() ), fd_frag_meta_ts_comp( fd_tickcount() ) );
    2565           0 :     ctx->votor_out_chunk = fd_dcache_compact_next( ctx->votor_out_chunk, sizeof(fd_votor_msg_t), ctx->votor_out_chunk0, ctx->votor_out_wmark );
    2566           0 :     *opt_poll_in = 0;
    2567           0 :     *charge_busy = 1;
    2568           0 :   }
    2569             : 
    2570             : 
    2571             :   /* 4c. Poll skip timeouts. */
    2572             : 
    2573           0 :   ulong timeout_slot;
    2574           0 :   if( FD_UNLIKELY( fd_votor_loop_poll_skip_timeout( ctx->votor, now, &timeout_slot ) ) ) { /* a timeout we set on ParentReady */
    2575           0 :     fd_votor_loop_handle_skip_timeout( ctx->votor, timeout_slot );
    2576           0 :     *opt_poll_in = 0;
    2577           0 :     *charge_busy = 1;
    2578           0 :   }
    2579             : 
    2580             :   /* 5. Broadcast new votes. */
    2581             : 
    2582           0 :   uchar reason;
    2583           0 :   if( FD_UNLIKELY( !pool_event && !repair_event && fd_votor_loop_poll_vote( ctx->votor, &ctx->scratch.vote, &reason ) ) ) {
    2584           0 :     ulong                   vote_slot  = fd_vote_slot( &ctx->scratch.vote );
    2585           0 :     fd_epoch_info_t const * epoch_info = fd_ptr_if( vote_slot>=ctx->next_epoch_slot, ctx->next_epoch_info, fd_ptr_if( vote_slot>=ctx->curr_epoch_slot, ctx->curr_epoch_info, ctx->prev_epoch_info ) );
    2586           0 :     ulong                   rank       = fd_vote_rank( &ctx->scratch.vote );
    2587           0 :     ctx->highest_vote_or_lead_slot = fd_ulong_max( ctx->highest_vote_or_lead_slot, vote_slot );
    2588           0 :     int sent = epoch_info && rank<epoch_info->validator_cnt && vote_slot>=ctx->vote_history_slot && vote_slot>=ctx->catchup_vote_slot && !fd_bls_sig_is_inf( fd_vote_sig( &ctx->scratch.vote ) );
    2589           0 :     if( FD_LIKELY( sent ) ) {
    2590           0 :       if( FD_LIKELY( ctx->vote_history_fd_dir!=-1 ) ) write_vote_history( ctx );
    2591           0 :       ulong ser_sz               = fd_vote_ser( &ctx->scratch.vote, ctx->scratch.ser );
    2592           0 :       long  broadcast_start_time = fd_clock_tile_now( ctx->clock );
    2593             : 
    2594           0 :       uint                kind                 = ctx->scratch.vote.kind;
    2595           0 :       fd_pubkey_t const * reward_leader_pubkey = fd_multi_epoch_leaders_get_leader_for_slot( ctx->mleaders, vote_slot+FD_VOTOR_REWARD_SLOT_DELTA );
    2596           0 :       peer_t const *      leader               = NULL;
    2597           0 :       if( FD_LIKELY(    reward_leader_pubkey
    2598           0 :                      && !fd_pubkey_eq( reward_leader_pubkey, &ctx->id_key )
    2599           0 :                      && (kind==FD_VOTE_KIND_NOTAR || kind==FD_VOTE_KIND_SKIP) ) ) {
    2600           0 :         leader = peers_query( ctx->peers, *reward_leader_pubkey, NULL );
    2601           0 :       }
    2602           0 :       if( FD_LIKELY( leader ) ) {
    2603           0 :         reward_vote_t * rv = &ctx->reward_votes[ vote_slot%REWARD_VOTE_MAX ];
    2604           0 :         rv->slot     = vote_slot;
    2605           0 :         rv->retry_ts = now;
    2606           0 :         rv->backoff  = 0L;
    2607           0 :         rv->tx_cnt   = 0UL;
    2608           0 :         rv->conn     = NULL;
    2609           0 :         rv->vote     = ctx->scratch.vote;
    2610           0 :         peer_t const * peer = reward_leader( ctx, rv, now );
    2611           0 :         if( FD_LIKELY( peer ) ) publish_reward_vote( ctx, stem, rv, peer, now ); /* the reward leader first, tracked so its ACK clears the retry */
    2612           0 :       }
    2613             : 
    2614           0 :       for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); slot++ ) {
    2615           0 :         peer_t const * peer = &ctx->peers[ slot ];
    2616           0 :         if( FD_LIKELY(    peers_key_inval( peer->id_key )
    2617           0 :                        || !peer->tx_conn
    2618           0 :                        || peer->tx_conn->state!=FD_QUIC_CONN_STATE_ACTIVE
    2619           0 :                        || peer==leader ) ) continue;
    2620           0 :         quic_client_datagram_tx( ctx, stem, peer->tx_conn, ctx->scratch.ser, ser_sz );
    2621           0 :       }
    2622             : 
    2623           0 :       long  aggregation_start_time = fd_clock_tile_now( ctx->clock );
    2624           0 :       uchar quorum_reached;
    2625           0 :       int   err = fd_votor_pool_add_vote( ctx->pool, &ctx->scratch.vote, 1, ctx->scratch.bad, &quorum_reached );
    2626           0 :       if( FD_UNLIKELY( !fd_bls_set_is_null( ctx->scratch.bad ) ) ) ban_bad_ranks( ctx, ctx->scratch.bad, vote_slot );
    2627           0 :       reward_cert_t * rc = &ctx->reward_certs[ vote_slot%FD_VOTOR_SLOTS_PER_WINDOW ];
    2628           0 :       if( FD_UNLIKELY( err==FD_VOTOR_POOL_SUCCESS && rc->slot==vote_slot && ( ctx->scratch.vote.kind==FD_VOTE_KIND_NOTAR || ctx->scratch.vote.kind==FD_VOTE_KIND_SKIP ) ) ) rc->dirty = 1;
    2629             : 
    2630           0 :       int result;
    2631           0 :       switch( err ) {
    2632           0 :       case FD_VOTOR_POOL_SUCCESS:                result = FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_ACCEPTED;                                                                                                                         break;
    2633           0 :       case FD_VOTOR_POOL_ERR_SLOT_TOO_OLD:       result = FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_SLOT_TOO_OLD;                                                                                                                    break;
    2634           0 :       case FD_VOTOR_POOL_ERR_SLOT_TOO_NEW:       result = FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_SLOT_TOO_NEW;                                                                                                                    break;
    2635           0 :       case FD_VOTOR_POOL_ERR_DUPLICATE:          result = FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_DUPLICATE;                                                                                                                        break;
    2636           0 :       case FD_VOTOR_POOL_ERR_SLASHABLE:          result = FD_EVENT_ALPENGLOW_VOTE_PROCESSING_RESULT_SLASHABLE;                                                                                                                        break;
    2637           0 :       default:
    2638           0 :         FD_LOG_CRIT(( "unhandled kind" ));
    2639           0 :       }
    2640           0 :       report_alpenglow_vote( ctx, NULL, &ctx->scratch.vote, ctx->scratch.ser[ 1 ], result, quorum_reached, FD_EVENT_ALPENGLOW_VOTE_REASON_BLOCK_REPLAYED+reason, aggregation_start_time, broadcast_start_time, leader );
    2641           0 :       if( FD_UNLIKELY( leader && ( !leader->tx_conn || leader->tx_conn->state!=FD_QUIC_CONN_STATE_ACTIVE ) ) ) report_alpenglow_vote( ctx, NULL, &ctx->scratch.vote, ctx->scratch.ser[ 1 ], result, 0, FD_EVENT_ALPENGLOW_VOTE_REASON_REWARD_NO_CONNECTION, 0L, 0L, leader );
    2642           0 :     }
    2643           0 :     if( FD_UNLIKELY( ctx->failover_enabled ) ) failover_after_vote( ctx, stem, vote_slot, sent );
    2644           0 :     *opt_poll_in = 0;
    2645           0 :     *charge_busy = 1;
    2646           0 :   }
    2647             : 
    2648             :   /* 6. Standstill re-broadcast, staked only: peers refuse unstaked
    2649             :      conns.  Unstaked, it stays unarmed. */
    2650             : 
    2651           0 :   ulong          finalized_slot = fd_votor_pool_finalized_slot( ctx->pool );
    2652           0 :   peer_t const * self           = peers_query( ctx->peers, ctx->id_key, NULL );
    2653           0 :   if( FD_UNLIKELY( !self || USHORT_MAX==fd_ushort_if( finalized_slot>=ctx->next_epoch_slot, self->next_rank, fd_ushort_if( finalized_slot>=ctx->curr_epoch_slot, self->curr_rank, self->prev_rank ) ) ) ) {
    2654           0 :     ctx->standstill_ts = LONG_MAX;
    2655           0 :     return;
    2656           0 :   }
    2657           0 :   if( FD_UNLIKELY( finalized_slot>ctx->standstill_slot || ctx->standstill_ts==LONG_MAX ) ) {
    2658           0 :     ctx->standstill_slot = finalized_slot;
    2659           0 :     ctx->standstill_ts   = now+FD_VOTOR_DELTA_STANDSTILL_NS;
    2660           0 :   }
    2661           0 :   if( FD_LIKELY( now<ctx->standstill_ts ) ) return;
    2662             : 
    2663           0 :   fd_votor_pool_standstill_iter_t * standstill_iter = ctx->standstill_iter;
    2664           0 :   if( FD_UNLIKELY( standstill_iter->finalized!=finalized_slot ) ) FD_LOG_WARNING(( "standstill at finalized slot %lu, re-broadcasting", finalized_slot ));
    2665           0 :   if( FD_UNLIKELY( fd_votor_pool_standstill_iter_done( standstill_iter ) || standstill_iter->finalized!=finalized_slot ) ) fd_votor_pool_standstill_iter_init( standstill_iter, ctx->pool );
    2666           0 :   if( FD_LIKELY( !fd_votor_pool_standstill_iter_done( standstill_iter ) && ( standstill_iter->is_vote ? fd_vote_slot( &standstill_iter->vote ) : fd_cert_slot( &standstill_iter->cert ) )<ctx->catchup_vote_slot ) ) { /* stale while catching up */
    2667           0 :     fd_votor_pool_standstill_iter_next( standstill_iter, ctx->pool );
    2668           0 :   } else if( FD_LIKELY( !fd_votor_pool_standstill_iter_done( standstill_iter ) ) ) {
    2669           0 :     ulong ser_sz = standstill_iter->is_vote ? fd_vote_ser( &standstill_iter->vote, ctx->scratch.ser ) : fd_cert_ser( &standstill_iter->cert, ctx->scratch.ser );
    2670           0 :     for( ulong slot=0UL; slot<peers_slot_cnt( ctx->peers ); slot++ ) {
    2671           0 :       peer_t const * peer = &ctx->peers[ slot ];
    2672           0 :       if( FD_LIKELY( peers_key_inval( peer->id_key ) || !peer->tx_conn || peer->tx_conn->state!=FD_QUIC_CONN_STATE_ACTIVE ) ) continue;
    2673           0 :       quic_client_datagram_tx( ctx, stem, peer->tx_conn, ctx->scratch.ser, ser_sz );
    2674           0 :     }
    2675           0 :     fd_votor_pool_standstill_iter_next( standstill_iter, ctx->pool );
    2676           0 :     *charge_busy = 1;
    2677           0 :   }
    2678           0 :   ctx->standstill_ts = now+fd_long_if( fd_votor_pool_standstill_iter_done( standstill_iter ), STANDSTILL_CYCLE_INTERVAL_NS, STANDSTILL_TX_INTERVAL_NS );
    2679           0 : }
    2680             : 
    2681             : static int
    2682             : before_frag( fd_votor_tile_t * ctx,
    2683             :              ulong             in_idx,
    2684             :              ulong             seq,
    2685           0 :              ulong             sig ) {
    2686           0 :   switch( ctx->in_kind[ in_idx ] ) {
    2687           0 :   case IN_KIND_EPOCH:
    2688           0 :     return 0;
    2689           0 :   case IN_KIND_GOSSIP:
    2690           0 :     return sig!=FD_GOSSIP_UPDATE_TAG_CONTACT_INFO && sig!=FD_GOSSIP_UPDATE_TAG_CONTACT_INFO_REMOVE;
    2691           0 :   case IN_KIND_IPECHO:
    2692           0 :     return 0;
    2693           0 :   case IN_KIND_NET: {
    2694           0 :     if( FD_UNLIKELY( !ctx->curr_epoch_info || ctx->keyswitch_state ) ) return 1; /* halted, no TLS handshake may sign */
    2695           0 :     ulong proto = fd_disco_netmux_sig_proto( sig );
    2696           0 :     return proto!=DST_PROTO_VOTOR_CLIENT && proto!=DST_PROTO_VOTOR_SERVER;
    2697           0 :   }
    2698           0 :   case IN_KIND_REPLAY:
    2699           0 :     if( FD_LIKELY( sig==REPLAY_SIG_SLOT_COMPLETED || sig==REPLAY_SIG_SLOT_DEAD ) ) {
    2700           0 :       if( FD_UNLIKELY( !ctx->curr_epoch_info ) ) return -1;
    2701           0 :       ctx->replay_in_seq = seq+1UL;
    2702           0 :       return 0;
    2703           0 :     }
    2704             :     /* Handled here, not accepted: do not backpressure replay_slot. */
    2705           0 :     ctx->replay_in_seq = seq+1UL;
    2706           0 :     if( FD_LIKELY( sig!=REPLAY_SIG_WFS_DONE || ctx->wfs_signalled ) ) return 1;
    2707           0 :     ctx->wfs_signalled = 1;
    2708           0 :     FD_LOG_NOTICE(( "wait for supermajority complete, resuming" ));
    2709           0 :     if( FD_LIKELY( wfs_is_ready( ctx ) && fd_votor_pool_finalized_slot( ctx->pool )!=ULONG_MAX && ctx->shred_version ) ) {
    2710           0 :       fd_votor_loop_arm_skip_timeouts( ctx->votor, fd_clock_tile_now( ctx->clock ) );
    2711           0 :       ctx->init = !!ctx->next_epoch_info;
    2712           0 :     }
    2713           0 :     return 1;
    2714           0 :   case IN_KIND_FAILOV:
    2715             :     /* Drain votes and pool events produced under the current identity
    2716             :        before changing the history or removing its rank. */
    2717           0 :     if( FD_UNLIKELY( ctx->init && ( fd_votor_loop_metrics( ctx->votor ).vote_events_cnt || fd_votor_pool_metrics( ctx->pool ).pool_events_cnt ) ) ) return -1;
    2718           0 :     return 0;
    2719           0 :   default:
    2720           0 :     FD_LOG_ERR(( "unexpected in_kind %d", ctx->in_kind[ in_idx ] ));
    2721           0 :   }
    2722           0 : }
    2723             : 
    2724             : static void
    2725             : during_frag( fd_votor_tile_t * ctx,
    2726             :              ulong             in_idx,
    2727             :              ulong             seq,
    2728             :              ulong             sig,
    2729             :              ulong             chunk,
    2730             :              ulong             sz,
    2731           0 :              ulong             ctl ) {
    2732           0 :   (void)seq;
    2733             : 
    2734           0 :   switch( ctx->in_kind[ in_idx ] ) {
    2735           0 :   case IN_KIND_EPOCH:
    2736           0 :     handle_epoch( ctx, fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk ) );
    2737           0 :     break;
    2738           0 :   case IN_KIND_GOSSIP:
    2739           0 :     handle_gossip( ctx, sig, fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk ) );
    2740           0 :     break;
    2741           0 :   case IN_KIND_IPECHO:
    2742             :     /* unreliable link, handled in after_frag */
    2743           0 :     break;
    2744           0 :   case IN_KIND_NET:
    2745           0 :     fd_memcpy( ctx->net_buf, fd_net_rx_translate_frag( &ctx->net_in_bounds[ in_idx ], chunk, ctl, sz ), sz );
    2746           0 :     break;
    2747           0 :   case IN_KIND_REPLAY:
    2748           0 :     handle_replay( ctx, sig, fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk ) );
    2749           0 :     break;
    2750           0 :   case IN_KIND_FAILOV:
    2751           0 :     failover_adopt_copy( ctx, in_idx, chunk, sz );
    2752           0 :     break;
    2753           0 :   default:
    2754           0 :     FD_LOG_ERR(( "unexpected in_kind %d", ctx->in_kind[ in_idx ] ));
    2755           0 :   }
    2756           0 : }
    2757             : 
    2758             : static void
    2759             : after_frag( fd_votor_tile_t *   ctx,
    2760             :             ulong               in_idx,
    2761             :             ulong               seq,
    2762             :             ulong               sig,
    2763             :             ulong               sz,
    2764             :             ulong               tsorig,
    2765             :             ulong               tspub,
    2766           0 :             fd_stem_context_t * stem ) {
    2767           0 :   (void)seq; (void)tsorig; (void)tspub;
    2768             : 
    2769           0 :   switch( ctx->in_kind[ in_idx ] ) {
    2770           0 :   case IN_KIND_EPOCH:
    2771             :     /* reliable link, handled in during_frag */
    2772           0 :     break;
    2773           0 :   case IN_KIND_GOSSIP:
    2774             :     /* reliable link, handled in during_frag */
    2775           0 :     break;
    2776           0 :   case IN_KIND_IPECHO:
    2777           0 :     FD_TEST( sig && sig<=USHORT_MAX );
    2778           0 :     int wfs = wfs_is_ready( ctx ); /* config only, so the assignment below cannot change it */
    2779           0 :     if( FD_UNLIKELY( !ctx->shred_version && fd_votor_pool_finalized_slot( ctx->pool )!=ULONG_MAX ) ) {
    2780           0 :       long now = fd_clock_tile_now( ctx->clock );
    2781           0 :       fd_votor_loop_init( ctx->votor, &ctx->boot_block_id, now, ctx->ns_per_slot, (ushort)sig, sign_vote, ctx );
    2782           0 :       ctx->highest_vote_or_lead_slot = fd_ulong_max( ctx->highest_vote_or_lead_slot, ctx->boot_block_id.slot );
    2783           0 :       if( FD_LIKELY( wfs ) ) fd_votor_loop_arm_skip_timeouts( ctx->votor, now );
    2784           0 :     }
    2785           0 :     ctx->shred_version = (ushort)sig;
    2786           0 :     ctx->init = !!ctx->next_epoch_info && fd_votor_pool_finalized_slot( ctx->pool )!=ULONG_MAX && wfs;
    2787           0 :     break;
    2788           0 :   case IN_KIND_NET: {
    2789           0 :     if( FD_UNLIKELY( sz<sizeof(fd_eth_hdr_t)+sizeof(fd_ip4_hdr_t)+sizeof(fd_udp_hdr_t) ) ) break;
    2790           0 :     fd_quic_t * quic = fd_ptr_if( fd_disco_netmux_sig_proto( sig )==DST_PROTO_VOTOR_CLIENT, ctx->quic_client, ctx->quic_server );
    2791           0 :     ctx->stem = stem;
    2792           0 :     fd_quic_process_packet( quic, ctx->net_buf+sizeof(fd_eth_hdr_t), sz-sizeof(fd_eth_hdr_t), fd_clock_tile_now( ctx->clock ) );
    2793           0 :     for( ulong i=0UL; i<ctx->net_tx_cnt; i++ ) fd_stem_publish( stem, OUT_IDX_NET, ctx->net_tx[ i ].sig, ctx->net_tx[ i ].chunk, ctx->net_tx[ i ].sz, fd_frag_meta_ctl( 0UL, 1, 1, 0 ), 0L, 0L );
    2794           0 :     ctx->net_tx_cnt = 0UL;
    2795           0 :     break;
    2796           0 :   }
    2797           0 :   case IN_KIND_REPLAY:
    2798             :     /* reliable link, handled in during_frag */
    2799           0 :     if( FD_UNLIKELY( ctx->failover_enabled && sig==REPLAY_SIG_SLOT_COMPLETED ) ) failover_publish_hist( ctx, stem, 0 ); /* keeps the failover deadlines ticking */
    2800           0 :     break;
    2801           0 :   case IN_KIND_FAILOV:
    2802           0 :     failover_adopt_response( ctx, sig, stem );
    2803           0 :     break;
    2804           0 :   default:
    2805           0 :     FD_LOG_ERR(( "unexpected in_kind %d", ctx->in_kind[ in_idx ] ));
    2806           0 :   }
    2807           0 : }
    2808             : 
    2809             : static void
    2810             : privileged_init( fd_topo_t const *      topo,
    2811           0 :                  fd_topo_tile_t const * tile ) {
    2812           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    2813             : 
    2814           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    2815           0 :   fd_votor_tile_t * ctx      = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_votor_tile_t), sizeof(fd_votor_tile_t) );
    2816           0 :   void *            auth_vtr = FD_SCRATCH_ALLOC_APPEND( l, auth_vtr_align(),         auth_vtr_footprint()    );
    2817             : 
    2818           0 :   if( FD_UNLIKELY( !strcmp( tile->votor.identity_key_path, "" ) ) )
    2819           0 :     FD_LOG_ERR(( "identity_key_path not set" ));
    2820             : 
    2821           0 :   ctx->auth_vtr = auth_vtr_join( auth_vtr_new( auth_vtr ) );
    2822           0 :   ctx->id_key   = *(fd_pubkey_t const *)fd_type_pun_const( fd_keyload_load( tile->votor.identity_key_path, /* pubkey only: */ 1 ) );
    2823             : 
    2824           0 :   ctx->vote_history_fd_dir       = -1;
    2825           0 :   ctx->vote_history_fd           = -1;
    2826           0 :   ctx->vote_history_fd_swp       = -1;
    2827           0 :   ctx->vote_history_fd_bak       = -1;
    2828           0 :   ctx->id_key_bak                = ctx->id_key;
    2829           0 :   ctx->vote_history_bak_full     = 0;
    2830           0 :   ctx->vote_history_slot         = 0UL;
    2831           0 :   ctx->highest_vote_or_lead_slot = 0UL;
    2832           0 :   if( FD_LIKELY( tile->votor.vote_history_path[ 0 ] ) ) {
    2833           0 :     FD_BASE58_ENCODE_32_BYTES( ctx->id_key.uc, id_key_b58 );
    2834           0 :     char bin[ PATH_MAX ];
    2835           0 :     char swp[ PATH_MAX ];
    2836           0 :     char bak[ PATH_MAX ];
    2837           0 :     FD_TEST( fd_cstr_printf_check( bin, PATH_MAX, NULL, "vote_history-%s.bin",     id_key_b58 ) );
    2838           0 :     FD_TEST( fd_cstr_printf_check( swp, PATH_MAX, NULL, "vote_history-%s.bin.swp", id_key_b58 ) );
    2839           0 :     FD_TEST( fd_cstr_printf_check( bak, PATH_MAX, NULL, "vote_history-%s.bin.bak", id_key_b58 ) );
    2840             : 
    2841           0 :     ctx->vote_history_fd_dir = open( tile->votor.vote_history_path, O_RDONLY|O_DIRECTORY );
    2842           0 :     if( FD_UNLIKELY( -1==ctx->vote_history_fd_dir ) ) FD_LOG_ERR(( "open(`%s`) failed (%i-%s)", tile->votor.vote_history_path, errno, fd_io_strerror( errno ) ));
    2843             : 
    2844             :     /* Without the identity's file, the directory must hold no other
    2845             :        vote history file, which may hold the identity's votes under
    2846             :        another name, like the .bak a set-identity away from it saves, or
    2847             :        the file an earlier version renamed to the new identity. */
    2848             : 
    2849           0 :     int should_scan = strcmp( tile->votor.identity_key_path, FD_KEYLOAD_FAILOVER_JUNK );
    2850           0 :     if( FD_UNLIKELY( -1==faccessat( ctx->vote_history_fd_dir, bin, F_OK, 0 ) ) ) {
    2851           0 :       if( FD_UNLIKELY( errno!=ENOENT ) ) FD_LOG_ERR(( "faccessat(`%s/%s`) failed (%i-%s)", tile->votor.vote_history_path, bin, errno, fd_io_strerror( errno ) ));
    2852           0 :       DIR * dir = should_scan ? opendir( tile->votor.vote_history_path ) : NULL;
    2853           0 :       if( FD_UNLIKELY( should_scan && !dir ) ) FD_LOG_ERR(( "opendir(`%s`) failed (%i-%s)", tile->votor.vote_history_path, errno, fd_io_strerror( errno ) ));
    2854           0 :       errno = 0;
    2855           0 :       for( struct dirent * ent; dir && (ent = readdir( dir )); ) {
    2856           0 :         if( FD_LIKELY( strncmp( ent->d_name, "vote_history-", sizeof("vote_history-")-1UL ) ) ) continue;
    2857           0 :         FD_LOG_ERR(( "Booting as %s, but detected %s in %s, which is missing %s. Please either copy %s into %s or remove the vote_history-* files there if you wish to boot without a vote history file.",
    2858           0 :                      id_key_b58, ent->d_name, tile->votor.vote_history_path, bin, bin, tile->votor.vote_history_path ));
    2859           0 :       }
    2860           0 :       if( FD_UNLIKELY( errno ) ) FD_LOG_ERR(( "readdir(`%s`) failed (%i-%s)", tile->votor.vote_history_path, errno, fd_io_strerror( errno ) ));
    2861           0 :       if( FD_UNLIKELY( dir && closedir( dir ) ) ) FD_LOG_ERR(( "closedir(`%s`) failed (%i-%s)", tile->votor.vote_history_path, errno, fd_io_strerror( errno ) ));
    2862           0 :       FD_LOG_WARNING(( "vote history file `%s/%s` does not exist, creating it.  This identity is assumed to have never voted.", tile->votor.vote_history_path, bin ));
    2863           0 :     }
    2864           0 :     ctx->vote_history_slot         = read_vote_history( ctx, tile->votor.vote_history_path, bin );
    2865           0 :     ctx->highest_vote_or_lead_slot = fd_ulong_sat_sub( ctx->vote_history_slot, 1UL );
    2866           0 :     if( FD_LIKELY( ctx->vote_history_slot ) ) FD_LOG_NOTICE(( "vote history file `%s/%s` has votes, waiting to vote until slot %lu", tile->votor.vote_history_path, bin, ctx->vote_history_slot ));
    2867             : 
    2868             :     /* Switch to non-root uid/gid for file creation. */
    2869           0 :     struct stat st;
    2870           0 :     gid_t gid = getgid();
    2871           0 :     uid_t uid = getuid();
    2872           0 :     if( FD_LIKELY( !gid && -1==syscall( __NR_setresgid, -1, tile->votor.target_gid, -1 ) ) ) FD_LOG_ERR(( "setresgid() failed (%i-%s)", errno, fd_io_strerror( errno ) ));
    2873           0 :     if( FD_LIKELY( !uid && -1==syscall( __NR_setresuid, -1, tile->votor.target_uid, -1 ) ) ) FD_LOG_ERR(( "setresuid() failed (%i-%s)", errno, fd_io_strerror( errno ) ));
    2874             : 
    2875           0 :     ctx->vote_history_fd = openat( ctx->vote_history_fd_dir, bin, O_WRONLY|O_CREAT, 0644 );
    2876           0 :     if( FD_UNLIKELY( -1==ctx->vote_history_fd ) ) FD_LOG_ERR(( "open(`%s/%s`) failed (%i-%s), make sure the configured user owns it", tile->votor.vote_history_path, bin, errno, fd_io_strerror( errno ) ));
    2877           0 :     if( FD_UNLIKELY( -1==fstat( ctx->vote_history_fd, &st ) ) ) FD_LOG_ERR(( "fstat(`%s/%s`) failed (%i-%s)", tile->votor.vote_history_path, bin, errno, fd_io_strerror( errno ) ));
    2878           0 :     if( FD_UNLIKELY( st.st_uid!=tile->votor.target_uid ) ) {
    2879           0 :       FD_LOG_ERR(( "vote history file `%s/%s` is owned by uid %u but the configured user is uid %u, chown it to the configured user", tile->votor.vote_history_path, bin, st.st_uid, tile->votor.target_uid ));
    2880           0 :     }
    2881           0 :     ctx->vote_history_fd_swp = openat( ctx->vote_history_fd_dir, swp, O_WRONLY|O_CREAT, 0644 );
    2882           0 :     if( FD_UNLIKELY( -1==ctx->vote_history_fd_swp ) ) FD_LOG_ERR(( "open(`%s/%s`) failed (%i-%s), make sure the configured user owns it", tile->votor.vote_history_path, swp, errno, fd_io_strerror( errno ) ));
    2883           0 :     if( FD_UNLIKELY( -1==fstat( ctx->vote_history_fd_swp, &st ) ) ) FD_LOG_ERR(( "fstat(`%s/%s`) failed (%i-%s)", tile->votor.vote_history_path, swp, errno, fd_io_strerror( errno ) ));
    2884           0 :     if( FD_UNLIKELY( st.st_uid!=tile->votor.target_uid ) ) {
    2885           0 :       FD_LOG_ERR(( "vote history file `%s/%s` is owned by uid %u but the configured user is uid %u, chown it to the configured user", tile->votor.vote_history_path, swp, st.st_uid, tile->votor.target_uid ));
    2886           0 :     }
    2887           0 :     ctx->vote_history_fd_bak = openat( ctx->vote_history_fd_dir, bak, O_WRONLY|O_CREAT, 0644 );
    2888           0 :     if( FD_UNLIKELY( -1==ctx->vote_history_fd_bak ) ) FD_LOG_ERR(( "open(`%s/%s`) failed (%i-%s), make sure the configured user owns it", tile->votor.vote_history_path, bak, errno, fd_io_strerror( errno ) ));
    2889           0 :     if( FD_UNLIKELY( -1==fstat( ctx->vote_history_fd_bak, &st ) ) ) FD_LOG_ERR(( "fstat(`%s/%s`) failed (%i-%s)", tile->votor.vote_history_path, bak, errno, fd_io_strerror( errno ) ));
    2890           0 :     ctx->vote_history_bak_full = !!st.st_size;
    2891           0 :     if( FD_UNLIKELY( st.st_uid!=tile->votor.target_uid ) ) {
    2892           0 :       FD_LOG_ERR(( "vote history file `%s/%s` is owned by uid %u but the configured user is uid %u, chown it to the configured user", tile->votor.vote_history_path, bak, st.st_uid, tile->votor.target_uid ));
    2893           0 :     }
    2894             : 
    2895           0 :     if( FD_UNLIKELY( -1==syscall( __NR_setresuid, -1, uid, -1 ) ) ) FD_LOG_ERR(( "setresuid() failed (%i-%s)", errno, fd_io_strerror( errno ) ));
    2896           0 :     if( FD_UNLIKELY( -1==syscall( __NR_setresgid, -1, gid, -1 ) ) ) FD_LOG_ERR(( "setresgid() failed (%i-%s)", errno, fd_io_strerror( errno ) ));
    2897           0 :   }
    2898             : 
    2899           0 :   fd_log_wallclock();
    2900           0 : }
    2901             : 
    2902             : static void
    2903             : unprivileged_init( fd_topo_t const *      topo,
    2904           0 :                    fd_topo_tile_t const * tile ) {
    2905             : 
    2906           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    2907             : 
    2908           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    2909           0 :   fd_votor_tile_t * ctx           = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_votor_tile_t),       sizeof(fd_votor_tile_t)                                                 );
    2910           0 :   void *            auth_vtr      = FD_SCRATCH_ALLOC_APPEND( l, auth_vtr_align(),               auth_vtr_footprint()                                                    );
    2911           0 :   void *            quic_client   = FD_SCRATCH_ALLOC_APPEND( l, fd_quic_align(),                fd_quic_footprint( &quic_client_limits )                                );
    2912           0 :   void *            quic_server   = FD_SCRATCH_ALLOC_APPEND( l, fd_quic_align(),                fd_quic_footprint( &quic_server_limits )                                );
    2913           0 :   void *            pool          = FD_SCRATCH_ALLOC_APPEND( l, fd_votor_pool_align(),          fd_votor_pool_footprint( tile->votor.max_live_slots, QUIC_DGRAM_BURST ) );
    2914           0 :   void *            votor         = FD_SCRATCH_ALLOC_APPEND( l, fd_votor_loop_align(),          fd_votor_loop_footprint( tile->votor.max_live_slots )                   );
    2915           0 :   void *            peers         = FD_SCRATCH_ALLOC_APPEND( l, peers_align(),                  peers_footprint( PEERS_LG_SLOT_CNT )                                    );
    2916           0 :   void *            contact_infos = FD_SCRATCH_ALLOC_APPEND( l, contact_infos_align(),          contact_infos_footprint( CONTACT_INFOS_LG_SLOT_CNT )                    );
    2917           0 :   void *            reconn_prq    = FD_SCRATCH_ALLOC_APPEND( l, reconn_prq_align(),             reconn_prq_footprint( RECONN_MAX )                                      );
    2918           0 :   void *            mleaders      = FD_SCRATCH_ALLOC_APPEND( l, fd_multi_epoch_leaders_align(), fd_multi_epoch_leaders_footprint()                                      );
    2919           0 :   ulong scratch_top = FD_SCRATCH_ALLOC_FINI( l, scratch_align() );
    2920           0 :   if( FD_UNLIKELY( scratch_top > (ulong)scratch + scratch_footprint( tile ) ) ) {
    2921           0 :     FD_LOG_ERR(( "scratch overflow %lu %lu %lu", scratch_top - (ulong)scratch - scratch_footprint( tile ), scratch_top, (ulong)scratch + scratch_footprint( tile ) ));
    2922           0 :   }
    2923             : 
    2924           0 :   (void)auth_vtr; /* privileged_init */
    2925             : 
    2926           0 :   ctx->shred_version = (ushort)0;
    2927             : 
    2928           0 :   memset( &ctx->metrics, 0, sizeof(ctx->metrics) );
    2929             : 
    2930           0 :   ulong seed;
    2931           0 :   FD_TEST( fd_rng_secure( &seed, sizeof(seed) ) );
    2932             : 
    2933           0 :   ctx->pool = fd_votor_pool_join( fd_votor_pool_new( pool, tile->votor.max_live_slots, QUIC_DGRAM_BURST, seed ) );
    2934           0 :   FD_TEST( ctx->pool );
    2935             : 
    2936           0 :   ctx->votor = fd_votor_loop_join( fd_votor_loop_new( votor, tile->votor.max_live_slots, seed ) );
    2937           0 :   FD_TEST( ctx->votor );
    2938             : 
    2939           0 :   ctx->prev_epoch_info = NULL;
    2940           0 :   ctx->prev_epoch_slot = ULONG_MAX;
    2941           0 :   ctx->curr_epoch_info = NULL;
    2942           0 :   ctx->curr_epoch_slot = ULONG_MAX;
    2943           0 :   ctx->next_epoch_info = NULL;
    2944           0 :   ctx->next_epoch_slot = ULONG_MAX;
    2945           0 :   ctx->conn_ahead_slot = ULONG_MAX;
    2946           0 :   memset( ctx->client_peer_id_keys, 0, sizeof(ctx->client_peer_id_keys) );
    2947           0 :   memset( ctx->server_peer_id_keys, 0, sizeof(ctx->server_peer_id_keys) );
    2948             : 
    2949           0 :   if( FD_UNLIKELY( !tile->votor.quic_client_listen_port ) )
    2950           0 :     FD_LOG_ERR(( "[development.votor.quic_client_listen_port] must be non-zero when alpenglow is enabled" ));
    2951           0 :   if( FD_UNLIKELY( tile->votor.quic_client_listen_port==tile->votor.quic_server_listen_port ) )
    2952           0 :     FD_LOG_ERR(( "[development.votor.quic_client_listen_port] %hu must differ from [development.votor.quic_server_listen_port]",
    2953           0 :                  tile->votor.quic_client_listen_port ));
    2954             : 
    2955           0 :   ctx->quic_client_listen_port = tile->votor.quic_client_listen_port;
    2956           0 :   ctx->src_ip_addr             = tile->votor.ip_addr;
    2957           0 :   ctx->net_id                  = (ushort)0;
    2958           0 :   fd_ip4_udp_hdr_init( ctx->hdr, FD_NET_MTU, ctx->src_ip_addr, ctx->quic_client_listen_port );
    2959             : 
    2960             : 
    2961           0 :   ulong peers_seed;         FD_TEST( fd_rng_secure( &peers_seed,         sizeof(ulong) ) );
    2962           0 :   ulong contact_infos_seed; FD_TEST( fd_rng_secure( &contact_infos_seed, sizeof(ulong) ) );
    2963             : 
    2964           0 :   ctx->peers = peers_join( peers_new( peers, PEERS_LG_SLOT_CNT, peers_seed ) );
    2965           0 :   FD_TEST( ctx->peers );
    2966             : 
    2967           0 :   ctx->contact_infos = contact_infos_join( contact_infos_new( contact_infos, CONTACT_INFOS_LG_SLOT_CNT, contact_infos_seed ) );
    2968           0 :   FD_TEST( ctx->contact_infos );
    2969             : 
    2970           0 :   ctx->reconn_prq = reconn_prq_join( reconn_prq_new( reconn_prq, RECONN_MAX ) );
    2971           0 :   FD_TEST( ctx->reconn_prq );
    2972             : 
    2973           0 :   ctx->mleaders = fd_multi_epoch_leaders_join( fd_multi_epoch_leaders_new( mleaders ) );
    2974           0 :   FD_TEST( ctx->mleaders );
    2975             : 
    2976           0 :   for( ulong i=0UL; i<REWARD_VOTE_MAX; i++ ) ctx->reward_votes[ i ].slot = ULONG_MAX;
    2977           0 :   for( ulong i=0UL; i<FD_VOTOR_SLOTS_PER_WINDOW; i++ ) ctx->reward_certs[ i ] = (reward_cert_t){ .slot = ULONG_MAX };
    2978             : 
    2979           0 :   ctx->init                      = 0;
    2980           0 :   ctx->boot_block_id             = (fd_block_id_t){ .slot = ULONG_MAX };
    2981           0 :   ctx->wfs_slot                  = tile->votor.wait_for_supermajority_at_slot;
    2982           0 :   ctx->wfs_hash_is_zero          = tile->votor.wait_for_supermajority_hash_is_zero;
    2983           0 :   ctx->wfs_shred_version         = tile->votor.expected_shred_version;
    2984           0 :   ctx->wfs_signalled             = 0;
    2985           0 :   ctx->net_tx_cnt                = 0UL;
    2986           0 :   ctx->next_leader_slot          = ULONG_MAX;
    2987           0 :   ctx->ns_per_slot               = 400000000L; /* until epoch info */
    2988           0 :   ctx->epoch_slot_cnt            = 0UL;
    2989           0 :   ctx->highest_parent_ready_slot = 0UL;
    2990           0 :   ctx->highest_certed_final_slot = 0UL;
    2991           0 :   ctx->catchup_slot              = 0UL;
    2992           0 :   ctx->catchup_final_slot        = 0UL;
    2993           0 :   ctx->catchup_vote_slot         = 0UL;
    2994           0 :   ctx->slot_max                  = tile->votor.max_live_slots;
    2995           0 :   ctx->standstill_slot           = ULONG_MAX;
    2996           0 :   ctx->standstill_ts             = LONG_MAX;
    2997           0 :   fd_votor_pool_standstill_iter_init( ctx->standstill_iter, ctx->pool );
    2998             : 
    2999           0 :   FD_TEST( tile->in_cnt<=sizeof(ctx->in_kind)/sizeof(ctx->in_kind[0]) );
    3000           0 :   for( ulong i=0UL; i<tile->in_cnt; i++ ) {
    3001           0 :     fd_topo_link_t const * link = &topo->links[ tile->in_link_id[ i ] ];
    3002             : 
    3003           0 :     if     ( FD_LIKELY( !strcmp( link->name, "replay_epoch"  ) ) ) ctx->in_kind[ i ] = IN_KIND_EPOCH;
    3004           0 :     else if( FD_LIKELY( !strcmp( link->name, "gossip_ciaddr" ) ) ) ctx->in_kind[ i ] = IN_KIND_GOSSIP;
    3005           0 :     else if( FD_LIKELY( !strcmp( link->name, "ipecho_out"    ) ) ) ctx->in_kind[ i ] = IN_KIND_IPECHO;
    3006           0 :     else if( FD_LIKELY( !strcmp( link->name, "net_votor"     ) ) ) {
    3007           0 :       ctx->in_kind[ i ] = IN_KIND_NET;
    3008           0 :       fd_net_rx_bounds_init( &ctx->net_in_bounds[ i ], link->dcache );
    3009           0 :     }
    3010           0 :     else if( FD_LIKELY( !strcmp( link->name, "replay_slot"  ) ) ) ctx->in_kind[ i ] = IN_KIND_REPLAY;
    3011           0 :     else if( FD_LIKELY( !strcmp( link->name, "sign_votor"   ) ) ) ctx->in_kind[ i ] = IN_KIND_SIGN;
    3012           0 :     else if( FD_LIKELY( !strcmp( link->name, "failov_votor" ) ) ) ctx->in_kind[ i ] = IN_KIND_FAILOV;
    3013           0 :     else FD_LOG_ERR(( "votor tile has unexpected input link %lu %s", i, link->name ));
    3014             : 
    3015           0 :     if( FD_LIKELY( link->mtu ) ) ctx->in[ i ].mem = topo->workspaces[ topo->objs[ link->dcache_obj_id ].wksp_id ].wksp;
    3016           0 :   }
    3017             : 
    3018           0 :   FD_TEST( tile->out_cnt>OUT_IDX_NET );
    3019           0 :   fd_topo_link_t const * votor_out = &topo->links[ tile->out_link_id[ OUT_IDX_VOTOR ] ];
    3020           0 :   FD_TEST( !strcmp( votor_out->name, "votor_out" ) );
    3021           0 :   ctx->votor_out_mem    = topo->workspaces[ topo->objs[ votor_out->dcache_obj_id ].wksp_id ].wksp;
    3022           0 :   ctx->votor_out_chunk0 = fd_dcache_compact_chunk0( ctx->votor_out_mem, votor_out->dcache );
    3023           0 :   ctx->votor_out_wmark  = fd_dcache_compact_wmark ( ctx->votor_out_mem, votor_out->dcache, votor_out->mtu );
    3024           0 :   ctx->votor_out_chunk  = ctx->votor_out_chunk0;
    3025             : 
    3026           0 :   fd_topo_link_t const * net_out = &topo->links[ tile->out_link_id[ OUT_IDX_NET ] ];
    3027           0 :   FD_TEST( !strcmp( net_out->name, "votor_net" ) );
    3028           0 :   FD_TEST( net_out->burst>=FD_VOTOR_NET_BURST );
    3029           0 :   ctx->net_out_mem    = topo->workspaces[ topo->objs[ net_out->dcache_obj_id ].wksp_id ].wksp;
    3030           0 :   ctx->net_out_chunk0 = fd_dcache_compact_chunk0( ctx->net_out_mem, net_out->dcache );
    3031           0 :   ctx->net_out_wmark  = fd_dcache_compact_wmark ( ctx->net_out_mem, net_out->dcache, net_out->mtu );
    3032           0 :   ctx->net_out_chunk  = ctx->net_out_chunk0;
    3033             : 
    3034           0 :   failover_init( ctx, topo, tile );
    3035             : 
    3036           0 :   ulong sign_in_idx  = fd_topo_find_tile_in_link ( topo, tile, "sign_votor", tile->kind_id );
    3037           0 :   ulong sign_out_idx = fd_topo_find_tile_out_link( topo, tile, "votor_sign", tile->kind_id );
    3038           0 :   FD_TEST( sign_in_idx !=ULONG_MAX );
    3039           0 :   FD_TEST( sign_out_idx!=ULONG_MAX );
    3040           0 :   fd_topo_link_t const * sign_in  = &topo->links[ tile->in_link_id [ sign_in_idx  ] ];
    3041           0 :   fd_topo_link_t const * sign_out = &topo->links[ tile->out_link_id[ sign_out_idx ] ];
    3042             : 
    3043           0 :   fd_sleep_t * sleep = NULL;
    3044           0 :   if( FD_UNLIKELY( topo->sleep_obj_id!=ULONG_MAX ) ) {
    3045           0 :     sleep = fd_sleep_join( fd_topo_obj_laddr( topo, topo->sleep_obj_id ) );
    3046           0 :     FD_TEST( sleep );
    3047           0 :   }
    3048             : 
    3049           0 :   if( FD_UNLIKELY( !fd_keyguard_client_join( fd_keyguard_client_new( ctx->keyguard_client,
    3050           0 :           sign_out->mcache,
    3051           0 :           sign_out->dcache,
    3052           0 :           sign_in->mcache,
    3053           0 :           sign_in->dcache,
    3054           0 :           sign_out->mtu,
    3055           0 :           sign_in->mtu,
    3056           0 :           sleep,
    3057           0 :           sign_out->id,
    3058           0 :           fd_topo_find_link_consumer( topo, sign_out ) ) ) ) ) {
    3059           0 :     FD_LOG_ERR(( "failed to construct keyguard client" ));
    3060           0 :   }
    3061           0 :   load_keys( ctx, tile->votor.authorized_voter_paths_cnt );
    3062             : 
    3063           0 :   ctx->auth_vtr_keyswitch = fd_keyswitch_join( fd_topo_obj_laddr( topo, tile->av_keyswitch_obj_id ) );
    3064           0 :   FD_TEST( ctx->auth_vtr_keyswitch );
    3065           0 :   ctx->id_keyswitch = fd_keyswitch_join( fd_topo_obj_laddr( topo, tile->id_keyswitch_obj_id ) );
    3066           0 :   FD_TEST( ctx->id_keyswitch );
    3067           0 :   ctx->keyswitch_state   = FD_KEYSWITCH_STATE_UNLOCKED;
    3068           0 :   ctx->replay_in_seq     = 0UL;
    3069             : 
    3070           0 :   fd_aio_t * quic_tx_aio = fd_aio_join( fd_aio_new( ctx->quic_tx_aio, ctx, quic_aio_tx ) );
    3071           0 :   FD_TEST( quic_tx_aio );
    3072             : 
    3073           0 :   ctx->quic_client = fd_quic_join( fd_quic_new( quic_client, &quic_client_limits ) );
    3074           0 :   FD_TEST( ctx->quic_client );
    3075           0 :   fd_quic_set_aio_net_tx( ctx->quic_client, quic_tx_aio );
    3076             : 
    3077           0 :   ctx->quic_client->config.role                       = FD_QUIC_ROLE_CLIENT;
    3078           0 :   ctx->quic_client->config.retry                      = 0;
    3079           0 :   ctx->quic_client->config.keep_alive                 = 1;
    3080           0 :   ctx->quic_client->config.idle_timeout               = 5L*1000L*1000L*1000L;
    3081           0 :   ctx->quic_client->config.ack_delay                  = 2L*1000L*1000L;
    3082           0 :   memcpy( ctx->quic_client->config.identity_public_key, ctx->id_key.uc, 32UL );
    3083           0 :   ctx->quic_client->config.sign                       = quic_sign;
    3084           0 :   ctx->quic_client->config.sign_ctx                   = ctx;
    3085           0 :   ctx->quic_client->config.alpn[ 0 ]                  = 0x0c;
    3086           0 :   memcpy( ctx->quic_client->config.alpn+1, "alpenglow-v1", 12UL );
    3087           0 :   ctx->quic_client->config.alpn_sz                    = 13UL;
    3088           0 :   ctx->quic_client->config.initial_rx_max_stream_data = 0UL;
    3089             : 
    3090           0 :   ctx->quic_client->cb.quic_ctx         = ctx;
    3091           0 :   ctx->quic_client->cb.conn_hs_complete = quic_client_conn_hs_complete;
    3092           0 :   ctx->quic_client->cb.conn_final       = quic_client_conn_final;
    3093           0 :   ctx->quic_client->cb.ack_range        = quic_client_ack_range;
    3094             : 
    3095           0 :   FD_TEST( fd_quic_init( ctx->quic_client ) );
    3096             : 
    3097           0 :   ctx->quic_server = fd_quic_join( fd_quic_new( quic_server, &quic_server_limits ) );
    3098           0 :   FD_TEST( ctx->quic_server );
    3099           0 :   fd_clock_tile_init( ctx->clock );
    3100           0 :   fd_quic_set_aio_net_tx( ctx->quic_server, quic_tx_aio );
    3101             : 
    3102           0 :   ctx->quic_server->config.role                       = FD_QUIC_ROLE_SERVER;
    3103           0 :   ctx->quic_server->config.retry                      = 1;
    3104           0 :   ctx->quic_server->config.idle_timeout               = 5L*1000L*1000L*1000L;
    3105           0 :   ctx->quic_server->config.ack_delay                  = 2L*1000L*1000L;
    3106           0 :   memcpy( ctx->quic_server->config.identity_public_key, ctx->id_key.uc, 32UL );
    3107           0 :   ctx->quic_server->config.sign                       = quic_sign;
    3108           0 :   ctx->quic_server->config.sign_ctx                   = ctx;
    3109           0 :   ctx->quic_server->config.req_client_cert            = 1;
    3110           0 :   ctx->quic_server->config.alpn[ 0 ]                  = 0x0c;
    3111           0 :   memcpy( ctx->quic_server->config.alpn+1, "alpenglow-v1", 12UL );
    3112           0 :   ctx->quic_server->config.alpn_sz                    = 13UL;
    3113           0 :   ctx->quic_server->config.initial_rx_max_stream_data = 0UL;
    3114           0 :   ctx->quic_server->config.max_datagram_frame_size    = 1280UL;
    3115             : 
    3116           0 :   ctx->quic_server->cb.quic_ctx    = ctx;
    3117           0 :   ctx->quic_server->cb.conn_new    = quic_server_conn_new;
    3118           0 :   ctx->quic_server->cb.conn_final  = quic_server_conn_final;
    3119           0 :   ctx->quic_server->cb.datagram_rx = quic_server_datagram_rx;
    3120             : 
    3121           0 :   FD_TEST( fd_quic_init( ctx->quic_server ) );
    3122             : 
    3123           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->quic_client->metrics.service_duration, FD_MHIST_EDGES_NS( VOTOR, CLIENT_SERVICE_DURATION_NANOS ) ) );
    3124           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->quic_client->metrics.receive_duration, FD_MHIST_EDGES_NS( VOTOR, CLIENT_PKT_RX_DURATION_NANOS  ) ) );
    3125           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->quic_server->metrics.service_duration, FD_MHIST_EDGES_NS( VOTOR, SERVER_SERVICE_DURATION_NANOS ) ) );
    3126           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->quic_server->metrics.receive_duration, FD_MHIST_EDGES_NS( VOTOR, SERVER_PKT_RX_DURATION_NANOS  ) ) );
    3127           0 : }
    3128             : 
    3129             : static ulong
    3130             : populate_allowed_seccomp( fd_topo_t const *      topo,
    3131             :                           fd_topo_tile_t const * tile,
    3132             :                           ulong                  out_cnt,
    3133           0 :                           struct sock_filter *   out ) {
    3134           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    3135           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    3136           0 :   fd_votor_tile_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_votor_tile_t), sizeof(fd_votor_tile_t) );
    3137             : 
    3138           0 :   populate_sock_filter_policy_fd_votor_tile( out_cnt, out, (uint)fd_log_private_logfile_fd(), (uint)ctx->vote_history_fd_dir, (uint)ctx->vote_history_fd_swp, (uint)ctx->vote_history_fd, (uint)ctx->vote_history_fd_bak );
    3139           0 :   return sock_filter_policy_fd_votor_tile_instr_cnt;
    3140           0 : }
    3141             : 
    3142             : static ulong
    3143             : populate_allowed_fds( fd_topo_t const *      topo,
    3144             :                       fd_topo_tile_t const * tile,
    3145             :                       ulong                  out_fds_cnt,
    3146           0 :                       int *                  out_fds ) {
    3147           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    3148           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    3149           0 :   fd_votor_tile_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_votor_tile_t), sizeof(fd_votor_tile_t) );
    3150             : 
    3151           0 :   if( FD_UNLIKELY( out_fds_cnt<6UL ) ) FD_LOG_ERR(( "out_fds_cnt %lu", out_fds_cnt ));
    3152             : 
    3153           0 :   ulong out_cnt = 0UL;
    3154           0 :   out_fds[ out_cnt++ ] = 2;
    3155           0 :   if( FD_LIKELY( -1!=fd_log_private_logfile_fd() ) )
    3156           0 :     out_fds[ out_cnt++ ] = fd_log_private_logfile_fd();
    3157           0 :   if( FD_LIKELY( -1!=ctx->vote_history_fd_dir ) ) {
    3158           0 :     out_fds[ out_cnt++ ] = ctx->vote_history_fd_dir;
    3159           0 :     out_fds[ out_cnt++ ] = ctx->vote_history_fd_swp;
    3160           0 :     out_fds[ out_cnt++ ] = ctx->vote_history_fd;
    3161           0 :     out_fds[ out_cnt++ ] = ctx->vote_history_fd_bak;
    3162           0 :   }
    3163           0 :   return out_cnt;
    3164           0 : }
    3165             : 
    3166           0 : #define STEM_BURST FD_VOTOR_OUT_BURST /* votor_out only; EXCLUDES VOTOR_NET (has no reliable consumers) */
    3167           0 : #define STEM_LAZY  (128L*3000L)
    3168             : 
    3169           0 : #define STEM_CALLBACK_CONTEXT_TYPE  fd_votor_tile_t
    3170           0 : #define STEM_CALLBACK_CONTEXT_ALIGN alignof(fd_votor_tile_t)
    3171           0 : #define STEM_CALLBACK_DURING_HOUSEKEEPING during_housekeeping
    3172           0 : #define STEM_CALLBACK_NEXT_DEADLINE       next_deadline
    3173           0 : #define STEM_CALLBACK_METRICS_WRITE       metrics_write
    3174           0 : #define STEM_CALLBACK_AFTER_CREDIT        after_credit
    3175           0 : #define STEM_CALLBACK_BEFORE_FRAG         before_frag
    3176           0 : #define STEM_CALLBACK_DURING_FRAG         during_frag
    3177           0 : #define STEM_CALLBACK_AFTER_FRAG          after_frag
    3178             : 
    3179             : #include "../../disco/stem/fd_stem.c"
    3180             : 
    3181             : static ulong
    3182           0 : max_event_sz( fd_topo_tile_t const * tile FD_PARAM_UNUSED ) {
    3183           0 :   return fd_ulong_max( sizeof(fd_event_alpenglow_vote_t), sizeof(fd_event_alpenglow_cert_t) );
    3184           0 : }
    3185             : 
    3186             : fd_topo_run_tile_t fd_tile_votor = {
    3187             :   .name                     = "votor",
    3188             :   .allow_renameat           = 1, /* write_vote_history */
    3189             :   .max_event_sz             = max_event_sz,
    3190             :   .populate_allowed_seccomp = populate_allowed_seccomp,
    3191             :   .populate_allowed_fds     = populate_allowed_fds,
    3192             :   .scratch_align            = scratch_align,
    3193             :   .scratch_footprint        = scratch_footprint,
    3194             :   .privileged_init          = privileged_init,
    3195             :   .unprivileged_init        = unprivileged_init,
    3196             :   .run                      = stem_run,
    3197             : };

Generated by: LCOV version 1.14