LCOV - code coverage report
Current view: top level - disco/shred - fd_shred_tile.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 0 870 0.0 %
Date: 2026-10-22 18:10:43 Functions: 0 15 0.0 %

          Line data    Source code
       1             : #define _GNU_SOURCE
       2             : #include "../tiles.h"
       3             : 
       4             : #if FD_HAS_X86
       5             : #include <x86intrin.h>
       6             : #endif
       7             : 
       8             : #include <errno.h>
       9             : #include <fcntl.h>
      10             : #include <unistd.h>
      11             : 
      12             : #include <linux/futex.h>
      13             : #include "generated/fd_shred_tile_seccomp.h"
      14             : #include "../../util/pod/fd_pod_format.h"
      15             : #include "fd_shredder.h"
      16             : #include "fd_shred_batch.h"
      17             : #include "fd_shred_dest.h"
      18             : #include "fd_fec_resolver.h"
      19             : #include "fd_stake_ci.h"
      20             : #include "fd_rnonce_ss.h"
      21             : #include "fd_shred_tile.h"
      22             : #include "../store/fd_store.h"
      23             : #include "../keyguard/fd_keyload.h"
      24             : #include "../keyguard/fd_keyguard.h"
      25             : #include "../keyguard/fd_keyswitch.h"
      26             : #include "../fd_disco.h"
      27             : #include "../net/fd_net_tile.h"
      28             : #include "fd_shred_dest_resolver.h"
      29             : #include "../../flamenco/leaders/fd_leaders.h"
      30             : #include "../../util/net/fd_net_headers.h"
      31             : #include "../../flamenco/gossip/fd_gossip_message.h"
      32             : #include "../../flamenco/runtime/sysvar/fd_sysvar_epoch_schedule.h"
      33             : #include "../../flamenco/runtime/fd_slot_params.h"
      34             : #include "../../discof/replay/fd_replay_tile.h"
      35             : #if FD_HAS_AVX
      36             : #include "../../util/simd/fd_nt_memcpy.h"
      37             : #else
      38             : #define fd_memcpy_tn         fd_memcpy
      39             : #define fd_memcpy_nt_nofence fd_memcpy
      40             : #define _mm_sfence()         do {} while( 0 )
      41             : #endif
      42             : 
      43             : /* The shred tile handles shreds from two data sources: shreds generated
      44             :    from microblocks from the leader pipeline, and shreds retransmitted
      45             :    from the network.
      46             : 
      47             :    They have rather different semantics, but at the end of the day, they
      48             :    both result in a bunch of shreds and FEC sets that need to be sent to
      49             :    the blockstore and on the network, which is why one tile handles
      50             :    both.
      51             : 
      52             :    We segment the memory for the two types of shreds into two halves of
      53             :    a dcache because they follow somewhat different flow control
      54             :    patterns. For flow control, the normal guarantee we want to provide
      55             :    is that the dcache entry is not overwritten unless the mcache entry
      56             :    has also been overwritten.  The normal way to do this when using both
      57             :    cyclically and with a 1-to-1 mapping is to make the dcache at least
      58             :    `burst` entries bigger than the mcache.
      59             : 
      60             :    The FEC arena uses an exposure window e.  Data is copied out before
      61             :    after_frag returns, so e is a small bound.
      62             : 
      63             :    Leader pipeline: Every entry creates up to FD_SHRED_BATCH_FEC_SETS_MAX
      64             :    FEC sets, and a set stays in the ring from its creation until the
      65             :    sign tile's response completes it, so up to FD_SHRED_SIGN_PEND_MAX
      66             :    are created but not yet exposed.  The leader section therefore needs
      67             :    e+FD_SHRED_SIGN_PEND_MAX entries.
      68             : 
      69             :    From the network: The FEC resolver doesn't use a cyclic order, but it
      70             :    does promise that once it returns an FEC set, it will return at least
      71             :    complete_depth FEC sets before returning it again.  This means we
      72             :    want at most complete_depth-1 FEC sets exposed, so
      73             :    complete_depth=e+1 FEC sets.  The FEC resolver has the
      74             :    ability to keep individual shreds for partial_depth calls, but
      75             :    because in this version of the shred tile, we send each shred to all
      76             :    its destinations as soon as we get it, we don't need that
      77             :    functionality, so we set partial_depth=1.
      78             : 
      79             :    Adding these up and plugging in the current value of
      80             :    SIGN_PEND_MAX, we get 2*e+10+fec_resolver_depth FEC sets.
      81             : 
      82             :    A note on parallelization.  From the network, shreds are distributed
      83             :    to tiles based on a validator-specific seeded hash of (slot, FEC set
      84             :    index) so all the shreds for a given FEC set (and any equivocating
      85             :    FEC set) are processed by the same tile.  From the leader pipeline,
      86             :    the original implementation used to parallelize by batch of
      87             :    microblocks (so within a block, batches were distributed to different
      88             :    tiles).  To support chained merkle shreds, the current implementation
      89             :    processes all the batches on tile 0 -- this should be a temporary
      90             :    state while Solana moves to a newer shred format that support better
      91             :    parallelization. */
      92             : 
      93           0 : #define IN_KIND_EPOCH   ( 1UL)
      94           0 : #define IN_KIND_POH     ( 3UL)
      95           0 : #define IN_KIND_NET     ( 4UL)
      96           0 : #define IN_KIND_SIGN    ( 5UL)
      97             : #define IN_KIND_REPAIR  ( 6UL)
      98           0 : #define IN_KIND_IPECHO  ( 7UL)
      99           0 : #define IN_KIND_GOSSIP  ( 8UL)
     100           0 : #define IN_KIND_ROOTEDR (11UL) /* Alpenglow */
     101             : 
     102           0 : #define NET_OUT_IDX     1
     103           0 : #define SIGN_OUT_IDX    2
     104             : #define IN_LINK_MAX     32UL
     105             : 
     106             : FD_STATIC_ASSERT( sizeof(fd_entry_batch_meta_t)==56UL, poh_shred_mtu );
     107             : 
     108           0 : #define FD_SHRED_ADD_SHRED_EXTRA_RETVAL_CNT 3
     109             : FD_STATIC_ASSERT( FD_SHRED_ADD_SHRED_EXTRA_RETVAL_CNT+FD_FEC_RESOLVER_ADD_SHRED_RETVAL_CNT==FD_METRICS_ENUM_SHRED_PROCESS_RESULT_CNT, metrics );
     110             : FD_STATIC_ASSERT( FD_FEC_RESOLVER_SHRED_OKAY+FD_FEC_RESOLVER_ADD_SHRED_RETVAL_OFF+FD_SHRED_ADD_SHRED_EXTRA_RETVAL_CNT==FD_METRICS_ENUM_SHRED_PROCESS_RESULT_V_ACCEPTED_IDX, metrics );
     111             : 
     112             : /* Number of entries in the block_ids table. Each entry is 32 byte.
     113             :    This table is used to keep track of block ids that we create
     114             :    when we're leader, so that we can access them whenever we need
     115             :    a *parent* block id for a new block. Larger table allows to
     116             :    retrieve older parent block ids. Currently it's set for worst
     117             :    case parent offset of USHORT_MAX (max allowed in a shred),
     118             :    making the total table 2MiB.
     119             :    See also comment on chained_merkle_root. */
     120           0 : #define BLOCK_IDS_TABLE_CNT USHORT_MAX
     121             : 
     122             : /* See note on parallelization above. Currently we process all batches in tile 0. */
     123             : #if 1
     124             : #define SHOULD_PROCESS_THESE_SHREDS ( ctx->round_robin_id==0 )
     125             : #else
     126             : #define SHOULD_PROCESS_THESE_SHREDS ( ctx->batch_cnt%ctx->round_robin_cnt==ctx->round_robin_id )
     127             : #endif
     128             : 
     129             : typedef union {
     130             :   struct {
     131             :     fd_wksp_t * mem;
     132             :     ulong       chunk0;
     133             :     ulong       wmark;
     134             :   };
     135             :   fd_net_rx_bounds_t net_rx;
     136             : } fd_shred_in_ctx_t;
     137             : 
     138             : /* A leader FEC set whose sign request went out on shred_sign and has
     139             :    not been answered. */
     140             : 
     141             : typedef struct {
     142             :   ulong            fec_set_idx;
     143             :   ulong            tsorig;
     144             :   fd_bmtree_node_t merkle_root;
     145             : } fd_shred_sign_pend_t;
     146             : 
     147             : typedef struct {
     148             :   fd_shredder_t      * shredder;
     149             :   fd_fec_resolver_t  * resolver;
     150             :   ulong                shred_limit;
     151             :   fd_pubkey_t          identity_key[1]; /* Just the public key */
     152             : 
     153             :   ulong                round_robin_id;
     154             :   ulong                round_robin_cnt;
     155             :   /* Number of batches shredded from PoH during the current slot.
     156             :      This should be the same for all the shred tiles. */
     157             :   ulong                batch_cnt;
     158             :   /* Slot of the most recent microblock we've seen from PoH,
     159             :      or 0 if we haven't seen one yet */
     160             :   ulong                slot;
     161             : 
     162             :   fd_rnonce_ss_t       repair_nonce_ss[1];
     163             : 
     164             :   fd_keyswitch_t *     keyswitch;
     165             : 
     166             :   fd_fec_set_t       * fec_sets;
     167             : 
     168             :   fd_stake_ci_t      * stake_ci;
     169             :   /* These are used in between during_frag and after_frag */
     170             :   ulong                      new_root;
     171             :   ulong                      slot_max;
     172             :   ulong                      future_slot;
     173             : 
     174             :   ulong poh_in_expect_seq;
     175             : 
     176             :   ushort net_id;
     177             : 
     178             :   int skip_frag;
     179             :   int parse_failed; /* during_frag's parse failed and this tile owns the frag, counted in after_frag once not overrun */
     180             : 
     181             :   ulong                    adtl_dests_leader_cnt;
     182             :   fd_shred_dest_weighted_t adtl_dests_leader    [ FD_TOPO_ADTL_DESTS_MAX ];
     183             :   ulong                    adtl_dests_retransmit_cnt;
     184             :   fd_shred_dest_weighted_t adtl_dests_retransmit[ FD_TOPO_ADTL_DESTS_MAX ];
     185             : 
     186             :   fd_ip4_udp_hdrs_t data_shred_net_hdr  [1];
     187             :   fd_ip4_udp_hdrs_t parity_shred_net_hdr[1];
     188             : 
     189             :   ulong shredder_fec_set_idx;     /* In [0, shredder_max_fec_set_idx) */
     190             :   ulong shredder_max_fec_set_idx; /* exclusive */
     191             : 
     192             :   uchar shredder_merkle_root[32];
     193             : 
     194             :   ulong send_fec_set_idx[ FD_SHRED_BATCH_FEC_SETS_MAX ];
     195             :   ulong send_fec_set_cnt;
     196             :   ulong tsorig;  /* timestamp of the last packet in compressed form */
     197             : 
     198             :   /* Leader FEC sets awaiting their signature, oldest first.  The sign
     199             :      tile answers in order on sign_shred, so each response frag belongs
     200             :      to the head, which it finishes. */
     201             :   fd_shred_sign_pend_t sign_pend[ FD_SHRED_SIGN_PEND_MAX ];
     202             : 
     203             :   ulong sign_pend_head;
     204             :   ulong sign_pend_cnt;
     205             :   ulong sign_seq;
     206             :   uchar signature[ 64 ] __attribute__((aligned(32UL)));
     207             : 
     208             :   fd_wksp_t * sign_out_mem;
     209             :   ulong       sign_out_chunk0;
     210             :   ulong       sign_out_wmark;
     211             :   ulong       sign_out_chunk;
     212             : 
     213             :   /* Includes Ethernet, IP, UDP headers */
     214             :   ulong shred_buffer_sz;
     215             :   uchar shred_buffer[ FD_NET_MTU ];
     216             : 
     217             :   /* These seeds get generated in privileged_init but used in
     218             :      unprivileged_init, so we store them here in between. */
     219             :   ulong resolver_seed;
     220             :   ulong shred_dest_seed;
     221             : 
     222             :   fd_shred_in_ctx_t in[ IN_LINK_MAX ];
     223             :   int               in_kind[ IN_LINK_MAX ];
     224             : 
     225             :   fd_wksp_t * net_out_mem;
     226             :   ulong       net_out_chunk0;
     227             :   ulong       net_out_wmark;
     228             :   ulong       net_out_chunk;
     229             : 
     230             :   /* This is the output link for shreds that is currently consumed by
     231             :      the repair and replay tile. */
     232             :   ulong       shred_out_idx;
     233             :   fd_wksp_t * shred_out_mem;
     234             :   ulong       shred_out_chunk0;
     235             :   ulong       shred_out_wmark;
     236             :   ulong       shred_out_chunk;
     237             : 
     238             :   /* Highest slot relayed on turbine, published for rpc
     239             :      (getMaxRetransmitSlot).  NULL if rpc is disabled. */
     240             :   ulong *     rtx_fseq;
     241             :   ulong       rtx_slot;
     242             : 
     243             :   fd_store_t    * store;
     244             :   fd_store_map_t  map_join[1];
     245             :   int             disk_fd;
     246             :   int             alpenglow;
     247             : 
     248             :   fd_gossip_update_message_t gossip_upd_buf[1];
     249             : 
     250             :   struct {
     251             :     fd_histf_t batch_sz[ 1 ];
     252             :     fd_histf_t batch_microblock_cnt[ 1 ];
     253             :     fd_histf_t shredding_timing[ 1 ];
     254             :     fd_histf_t add_shred_timing[ 1 ];
     255             :     fd_histf_t fec_fallback_write_timing[ 1 ];
     256             :     ulong shred_processing_result[ FD_FEC_RESOLVER_ADD_SHRED_RETVAL_CNT+FD_SHRED_ADD_SHRED_EXTRA_RETVAL_CNT ];
     257             :     ulong invalid_block_id_cnt;
     258             :     ulong shred_rejected_unchained_cnt;
     259             :     ulong repair_rcv_cnt;
     260             :     ulong repair_rcv_bytes;
     261             :     ulong turbine_rcv_cnt;
     262             :     ulong turbine_rcv_bytes;
     263             :     ulong bad_nonce;
     264             :     ulong fec_fallback_write_cnt;
     265             :     ulong fec_fallback_write_bytes;
     266             :   } metrics[ 1 ];
     267             : 
     268             :   struct {
     269             :     ulong pos; /* in payload, range [0, FD_SHRED_BATCH_RAW_BUF_SZ-8UL) */
     270             :     ulong slot; /* set to 0 when pos==0 */
     271             :     union {
     272             :       struct {
     273             :         ulong microblock_cnt;
     274             :         uchar payload[ FD_SHRED_BATCH_RAW_BUF_SZ - 8UL ];
     275             :       };
     276             :       uchar raw[ FD_SHRED_BATCH_RAW_BUF_SZ ];
     277             :     };
     278             :   } pending_batch;
     279             : 
     280             :   fd_epoch_schedule_t            epoch_schedule[1];
     281             :   fd_shred_features_activation_t features_activation[1];
     282             : 
     283             :   /* max_shred_idx is the exclusive upper bound for shred
     284             :      indices. We need to reject any shred with an
     285             :      index >= current_max_shred_idx, but we also want to reject anything
     286             :      that is part of an FEC set whose highest shred index would reach
     287             :      the bound.
     288             : 
     289             :      Because this bound can change with feature gates, for example the
     290             :      reduce_slot_time feature gates, we store the bound for the
     291             :      previous, current, and next regimes, along with the slots at which
     292             :      the current and next bounds take effect. This lets us apply, to
     293             :      each shred, the limit effective at that shreds slot.
     294             : 
     295             :      For a given shred slot, the max_shred_idx for that shred is:
     296             :       next_max_shred_idx_start_slot    <= slot                                    -> next_max_shred_idx
     297             :       current_max_shred_idx_start_slot <= slot < next_max_shred_idx_start_slot    -> current_max_shred_idx
     298             :                                           slot < current_max_shred_idx_start_slot -> prev_max_shred_idx
     299             :   */
     300             :   ulong                          prev_max_shred_idx;
     301             :   ulong                          current_max_shred_idx;
     302             :   ulong                          next_max_shred_idx;
     303             :   ulong                          current_max_shred_idx_start_slot;
     304             :   ulong                          next_max_shred_idx_start_slot;
     305             :   ulong                          bench_max_shred_idx; /* [development.bench.max_shreds_per_block], floors the chain's limits */
     306             :   /* too large to be left in the stack */
     307             :   fd_shred_dest_idx_t scratchpad_dests[ FD_SHRED_DEST_MAX_FANOUT*(FD_REEDSOL_DATA_SHREDS_MAX+FD_REEDSOL_PARITY_SHREDS_MAX) ];
     308             : 
     309             :   uchar * chained_merkle_root;
     310             :   fd_bmtree_node_t out_merkle_roots[ FD_SHRED_BATCH_FEC_SETS_MAX ];
     311             :   uchar block_ids[ BLOCK_IDS_TABLE_CNT ][ FD_SHRED_MERKLE_ROOT_SZ ];
     312             : 
     313             :   fd_sha512_t sha512[1];
     314             :   uchar       bmtree_mem[ FD_BMTREE_COMMIT_FOOTPRINT( FD_SHRED_MERKLE_LAYER_CNT ) ] __attribute__((aligned(FD_BMTREE_COMMIT_ALIGN)));
     315             : } fd_shred_ctx_t;
     316             : 
     317             : /* shred features are generally considered active at the epoch *following*
     318             :    the epoch in which the feature gate is activated.
     319             : 
     320             :    As an optimization, when the activation slot is received, it is converted
     321             :    into the first slot of the subsequent epoch.  This allows for a more
     322             :    efficient check (shred_slot >= feature_slot) and avoids the overhead of
     323             :    repeatedly converting slots into epochs for comparison.
     324             : 
     325             :    In Agave, this is done with check_feature_activation():
     326             :    https://github.com/anza-xyz/agave/blob/v3.1.4/turbine/src/cluster_nodes.rs#L771
     327             :    https://github.com/anza-xyz/agave/blob/v3.1.4/core/src/shred_fetch_stage.rs#L456 */
     328             : static inline ulong
     329           0 : fd_shred_get_feature_activation_slot0( ulong feature_slot, fd_shred_ctx_t * ctx ) {
     330             :   /* if the feature does not have an activation slot yet, return ULONG_MAX */
     331           0 :   if( FD_UNLIKELY( feature_slot==ULONG_MAX ) ) {
     332           0 :     return ULONG_MAX;
     333           0 :   }
     334             :   /* if we don't have an epoch schedule yet, return ULONG_MAX */
     335           0 :   if( FD_UNLIKELY( ctx->epoch_schedule->slots_per_epoch==0 ) ) {
     336           0 :     return ULONG_MAX;
     337           0 :   }
     338             :   /* compute the activation epoch, add one, return the first slot. */
     339           0 :   ulong feature_epoch = 1 + fd_slot_to_epoch( ctx->epoch_schedule, feature_slot, NULL );
     340           0 :   return fd_epoch_slot0( ctx->epoch_schedule, feature_epoch );
     341           0 : }
     342             : 
     343             : FD_FN_CONST static inline ulong
     344           0 : scratch_align( void ) {
     345           0 :   return 128UL;
     346           0 : }
     347             : 
     348             : FD_FN_PURE static inline ulong
     349           0 : scratch_footprint( fd_topo_tile_t const * tile ) {
     350             : 
     351           0 :   ulong fec_resolver_footprint = fd_fec_resolver_footprint( tile->shred.fec_resolver_depth, 1UL, tile->shred.fec_exposure+1UL,
     352           0 :                                                             128UL * tile->shred.fec_resolver_depth );
     353           0 :   ulong l = FD_LAYOUT_INIT;
     354           0 :   l = FD_LAYOUT_APPEND( l, alignof(fd_shred_ctx_t),          sizeof(fd_shred_ctx_t)                  );
     355           0 :   l = FD_LAYOUT_APPEND( l, fd_stake_ci_align(),              fd_stake_ci_footprint()                 );
     356           0 :   l = FD_LAYOUT_APPEND( l, fd_fec_resolver_align(),          fec_resolver_footprint                  );
     357           0 :   l = FD_LAYOUT_APPEND( l, fd_shredder_align(),              fd_shredder_footprint()                 );
     358           0 :   return FD_LAYOUT_FINI( l, scratch_align() );
     359           0 : }
     360             : 
     361             : static inline void
     362           0 : during_housekeeping( fd_shred_ctx_t * ctx ) {
     363           0 :   if( FD_UNLIKELY( fd_keyswitch_state_query( ctx->keyswitch )==FD_KEYSWITCH_STATE_SWITCH_PENDING ) ) {
     364           0 :     ulong seq_must_complete = ctx->keyswitch->param;
     365             : 
     366           0 :     if( FD_UNLIKELY( fd_seq_lt( ctx->poh_in_expect_seq, seq_must_complete ) || ctx->sign_pend_cnt ) ) {
     367             :       /* See fd_keyswitch.h, we need to flush any in-flight shreds from
     368             :          the leader pipeline before switching key.  Sets still awaiting
     369             :          their signature were requested under the old key. */
     370           0 :       FD_LOG_WARNING(( "Flushing in-flight unpublished shreds, must reach seq %lu, currently at %lu with %lu awaiting signature ...", seq_must_complete, ctx->poh_in_expect_seq, ctx->sign_pend_cnt ));
     371           0 :       return;
     372           0 :     }
     373             : 
     374           0 :     memcpy( ctx->identity_key->uc, ctx->keyswitch->bytes, 32UL );
     375           0 :     fd_stake_ci_set_identity( ctx->stake_ci, ctx->identity_key );
     376           0 :     fd_keyswitch_state( ctx->keyswitch, FD_KEYSWITCH_STATE_COMPLETED );
     377           0 :   }
     378           0 : }
     379             : 
     380             : static inline void
     381           0 : metrics_write( fd_shred_ctx_t * ctx ) {
     382           0 :   FD_MHIST_COPY( SHRED, REPAIR_LEAD_DELAY_NANOS,             fd_fec_resolver_completion_lag_hist( ctx->resolver ) );
     383           0 :   FD_MHIST_COPY( SHRED, BATCH_SIZE_BYTES,                    ctx->metrics->batch_sz                               );
     384           0 :   FD_MHIST_COPY( SHRED, MICROBLOCK_PER_BATCH,                ctx->metrics->batch_microblock_cnt                   );
     385           0 :   FD_MHIST_COPY( SHRED, BATCH_SHRED_DURATION_NANOS,          ctx->metrics->shredding_timing                       );
     386           0 :   FD_MHIST_COPY( SHRED, ADD_SHRED_DURATION_NANOS,            ctx->metrics->add_shred_timing                       );
     387           0 :   FD_MHIST_COPY( SHRED, STORE_FEC_SYNC_SPILL_DURATION_NANOS, ctx->metrics->fec_fallback_write_timing              );
     388           0 :   FD_MCNT_SET  ( SHRED, REPAIR_RX,                           ctx->metrics->repair_rcv_cnt                         );
     389           0 :   FD_MCNT_SET  ( SHRED, REPAIR_RX_BYTES,                     ctx->metrics->repair_rcv_bytes                       );
     390           0 :   FD_MCNT_SET  ( SHRED, TURBINE_RX,                          ctx->metrics->turbine_rcv_cnt                        );
     391           0 :   FD_MCNT_SET  ( SHRED, TURBINE_RX_BYTES,                    ctx->metrics->turbine_rcv_bytes                      );
     392           0 :   FD_MCNT_SET  ( SHRED, REPAIR_NONCE_FAILED,                 ctx->metrics->bad_nonce                              );
     393           0 :   FD_MCNT_SET  ( SHRED, STORE_FEC_SYNC_SPILLED,              ctx->metrics->fec_fallback_write_cnt                 );
     394           0 :   FD_MCNT_SET  ( SHRED, STORE_FEC_SYNC_SPILLED_BYTES,        ctx->metrics->fec_fallback_write_bytes               );
     395             : 
     396           0 :   FD_MCNT_SET  ( SHRED, PARENT_BLOCK_ID_ZEROED, ctx->metrics->invalid_block_id_cnt         );
     397           0 :   FD_MCNT_SET  ( SHRED, UNCHAINED_REJECTED,     ctx->metrics->shred_rejected_unchained_cnt );
     398             : 
     399           0 :   FD_MCNT_ENUM_COPY( SHRED, PROCESSED,      ctx->metrics->shred_processing_result      );
     400           0 : }
     401             : 
     402             : static inline int
     403             : before_frag( fd_shred_ctx_t * ctx,
     404             :              ulong            in_idx,
     405             :              ulong            seq,
     406           0 :              ulong            sig ) {
     407           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_IPECHO ) ) {
     408           0 :     FD_TEST( sig!=0UL && sig<=USHORT_MAX );
     409           0 :     fd_shredder_set_shred_version    ( ctx->shredder, (ushort)sig );
     410           0 :     fd_fec_resolver_set_shred_version( ctx->resolver, (ushort)sig );
     411           0 :     return 1;
     412           0 :   }
     413             : 
     414           0 :   if( FD_UNLIKELY( !ctx->shredder->shred_version ) ) return -1;
     415             : 
     416           0 :   if( FD_LIKELY( ctx->in_kind[ in_idx ]==IN_KIND_POH ) ) {
     417           0 :     if( FD_UNLIKELY( (fd_disco_poh_sig_pkt_type( sig )==POH_PKT_TYPE_MICROBLOCK) &
     418           0 :                      (ctx->sign_pend_cnt+FD_SHRED_BATCH_FEC_SETS_MAX>FD_SHRED_SIGN_PEND_MAX) ) ) return -1;
     419           0 :     ctx->poh_in_expect_seq = seq+1UL;
     420           0 :     return fd_disco_poh_sig_pkt_type( sig )!=POH_PKT_TYPE_MICROBLOCK;
     421           0 :   }
     422           0 :   if( FD_LIKELY( ctx->in_kind[ in_idx ]==IN_KIND_NET ) ) {
     423           0 :     return (int)(fd_disco_netmux_sig_proto( sig )!=DST_PROTO_SHRED) & (int)(fd_disco_netmux_sig_proto( sig )!=DST_PROTO_REPAIR);
     424           0 :   }
     425           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_GOSSIP ) ){
     426           0 :     return sig!=FD_GOSSIP_UPDATE_TAG_CONTACT_INFO &&
     427           0 :            sig!=FD_GOSSIP_UPDATE_TAG_CONTACT_INFO_REMOVE;
     428           0 :   }
     429           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_ROOTEDR ) ) {
     430           0 :     return sig!=REPLAY_SIG_ROOT_ADVANCED; /* only care about root_advanced messages */
     431           0 :   }
     432           0 :   return 0;
     433           0 : }
     434             : 
     435             : static void
     436             : during_frag( fd_shred_ctx_t * ctx,
     437             :              ulong            in_idx,
     438             :              ulong            seq,
     439             :              ulong            sig,
     440             :              ulong            chunk,
     441             :              ulong            sz,
     442           0 :              ulong            ctl ) {
     443             : 
     444           0 :   ctx->skip_frag    = 0;
     445           0 :   ctx->parse_failed = 0;
     446             : 
     447           0 :   ctx->tsorig = fd_frag_meta_ts_comp( fd_tickcount() );
     448             : 
     449           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_REPAIR ) ) {
     450           0 :     if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz>FD_NET_MTU ) )
     451           0 :     FD_LOG_ERR(( "chunk %lu %lu corrupt, not in range [%lu,%lu]", chunk, sz,
     452           0 :                 ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark ));
     453             : 
     454           0 :     uchar const * dcache_entry = fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk );
     455           0 :     fd_memcpy( ctx->shred_buffer, dcache_entry, sz );
     456           0 :     return;
     457           0 :   }
     458             : 
     459           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_GOSSIP ) ) {
     460           0 :     if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz>sizeof(fd_gossip_update_message_t) ) )
     461           0 :       FD_LOG_ERR(( "chunk %lu %lu corrupt, not in range [%lu,%lu]", chunk, sz,
     462           0 :                    ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark ));
     463           0 :     uchar const * gossip_upd_msg = fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk );
     464           0 :     fd_memcpy( ctx->gossip_upd_buf, gossip_upd_msg, sz );
     465           0 :     return;
     466           0 :   }
     467             : 
     468             :   /* Alpenglow */
     469           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_ROOTEDR ) ) {
     470           0 :     if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz<sizeof(fd_replay_root_advanced_t) ) )
     471           0 :       FD_LOG_ERR(( "chunk %lu %lu corrupt, not in range [%lu,%lu]", chunk, sz,
     472           0 :                    ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark ));
     473           0 :     fd_replay_root_advanced_t const * rooted_msg = fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk );
     474           0 :     ctx->new_root = rooted_msg->slot;
     475           0 :     return;
     476           0 :   }
     477             : 
     478           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_EPOCH ) ) {
     479           0 :     if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark ) )
     480           0 :       FD_LOG_ERR(( "chunk %lu %lu corrupt, not in range [%lu,%lu]", chunk, sz,
     481           0 :                    ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark ));
     482             : 
     483           0 :     uchar const *               dcache_entry = fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk );
     484           0 :     fd_epoch_info_msg_t const * epoch_msg    = fd_type_pun_const( dcache_entry );
     485             : 
     486           0 :     FD_TEST( epoch_msg->staked_vote_cnt<=MAX_STAKE_WEIGHTS );
     487           0 :     FD_TEST( epoch_msg->staked_id_cnt<=MAX_STAKE_WEIGHTS );
     488             : 
     489           0 :     fd_stake_ci_epoch_msg_init( ctx->stake_ci, epoch_msg );
     490             : 
     491           0 :     *ctx->epoch_schedule = epoch_msg->epoch_schedule;
     492             : 
     493           0 :     fd_slot_params_t slot_params = fd_slot_params_lookup( &FD_SLOT_PARAMS_400MS,
     494           0 :                                                           &epoch_msg->features,
     495           0 :                                                           &epoch_msg->epoch_schedule,
     496           0 :                                                           epoch_msg->start_slot );
     497             : 
     498           0 :     ctx->current_max_shred_idx            = fd_ulong_max( slot_params.max_shred_idx, ctx->bench_max_shred_idx );
     499           0 :     ctx->current_max_shred_idx_start_slot = fd_slot_params_effective_slot( &slot_params,
     500           0 :                                                                            &epoch_msg->features,
     501           0 :                                                                            &epoch_msg->epoch_schedule );
     502           0 :     ctx->next_max_shred_idx_start_slot    = fd_slot_params_next_effective_slot( &slot_params,
     503           0 :                                                                                 &epoch_msg->features,
     504           0 :                                                                                 &epoch_msg->epoch_schedule );
     505           0 :     ctx->prev_max_shred_idx               = fd_ulong_max( fd_slot_params_lookup( &FD_SLOT_PARAMS_400MS,
     506           0 :                                                                                  &epoch_msg->features,
     507           0 :                                                                                  &epoch_msg->epoch_schedule,
     508           0 :                                                                                  fd_ulong_sat_sub( ctx->current_max_shred_idx_start_slot, 1UL ) ).max_shred_idx, ctx->bench_max_shred_idx );
     509           0 :     ctx->next_max_shred_idx               = fd_ulong_max( fd_slot_params_lookup( &FD_SLOT_PARAMS_400MS,
     510           0 :                                                                                  &epoch_msg->features,
     511           0 :                                                                                  &epoch_msg->epoch_schedule,
     512           0 :                                                                                  ctx->next_max_shred_idx_start_slot ).max_shred_idx, ctx->bench_max_shred_idx );
     513           0 :     ctx->features_activation->enforce_fixed_fec_set = fd_shred_get_feature_activation_slot0(
     514           0 :       epoch_msg->features.enforce_fixed_fec_set, ctx );
     515             : 
     516           0 :     return;
     517           0 :   }
     518             : 
     519           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_SIGN ) ) {
     520           0 :     if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz!=64UL ) ) FD_LOG_ERR(( "chunk %lu %lu corrupt, not in range [%lu,%lu]", chunk, sz, ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark ));
     521             : 
     522           0 :     if( FD_UNLIKELY( seq!=ctx->sign_seq ) ) FD_LOG_CRIT(( "sign response seq %lu, expected %lu", seq, ctx->sign_seq ));
     523           0 :     fd_memcpy( ctx->signature, fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk ), 64UL );
     524           0 :     return;
     525           0 :   }
     526             : 
     527           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_POH ) ) {
     528           0 :     ctx->send_fec_set_cnt = 0UL;
     529             : 
     530             :     /* This is a frag from the PoH tile.  We'll copy it to our pending
     531             :        microblock batch and shred it if necessary (last in block or
     532             :        above watermark).  We just go ahead and shred it here, even
     533             :        though we may get overrun.  If we do end up getting overrun, we
     534             :        just won't send these shreds out and we'll reuse the FEC set for
     535             :        the next one.  From a higher level though, if we do get overrun,
     536             :        a bunch of shreds will never be transmitted, and we'll end up
     537             :        producing a block that never lands on chain. */
     538             : 
     539           0 :     uchar const * dcache_entry = fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk );
     540           0 :     if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz>FD_POH_SHRED_MTU ||
     541           0 :         sz<(sizeof(fd_entry_batch_meta_t)+sizeof(fd_entry_batch_header_t)) ) )
     542           0 :       FD_LOG_ERR(( "chunk %lu %lu corrupt, not in range [%lu,%lu]", chunk, sz,
     543           0 :             ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark ));
     544             : 
     545           0 :     fd_entry_batch_meta_t const * entry_meta = (fd_entry_batch_meta_t const *)dcache_entry;
     546           0 :     uchar const *                 entry      = dcache_entry + sizeof(fd_entry_batch_meta_t);
     547           0 :     ulong                         entry_sz   = sz           - sizeof(fd_entry_batch_meta_t);
     548             : 
     549             :     /* It should never be possible for this to fail, but we check it
     550             :       anyway. */
     551           0 :     FD_TEST( entry_sz + ctx->pending_batch.pos <= sizeof(ctx->pending_batch.payload) );
     552             : 
     553           0 :     ulong target_slot = fd_disco_poh_sig_slot( sig );
     554           0 :     if( FD_UNLIKELY( (ctx->pending_batch.microblock_cnt>0) & (ctx->pending_batch.slot!=target_slot) ) ) {
     555             :       /* TODO: The Agave client sends a dummy entry batch with only 1
     556             :         byte and the block-complete bit set.  This helps other
     557             :         validators know that the block is dead and they should not try
     558             :         to continue building a fork on it.  We probably want a similar
     559             :         approach eventually. */
     560           0 :       FD_LOG_WARNING(( "Abandoning %lu microblocks for slot %lu and switching to slot %lu",
     561           0 :             ctx->pending_batch.microblock_cnt, ctx->pending_batch.slot, target_slot ));
     562           0 :       ctx->pending_batch.slot           = 0UL;
     563           0 :       ctx->pending_batch.pos            = 0UL;
     564           0 :       ctx->pending_batch.microblock_cnt = 0UL;
     565           0 :       ctx->batch_cnt                    = 0UL;
     566             : 
     567           0 :       FD_MCNT_INC( SHRED, BATCH_ABANDONED, 1UL );
     568           0 :     }
     569             : 
     570           0 :     ctx->pending_batch.slot = target_slot;
     571             :     /* We want to send out some shreds immediately when we start a new
     572             :        slot to help with leader targeting. */
     573           0 :     int new_slot = 0;
     574           0 :     if( FD_UNLIKELY( target_slot!=ctx->slot )) {
     575             :       /* Reset batch count if we are in a new slot */
     576           0 :       ctx->batch_cnt = 0UL;
     577           0 :       ctx->slot      = target_slot;
     578           0 :       new_slot       = 1;
     579             : 
     580             :       /* At the beginning of a new slot, prepare chained_merkle_root.
     581             :          chained_merkle_root is initialized at the block_id of the parent
     582             :          block, there's two cases:
     583             : 
     584             :          1. block_id is passed in by the poh tile:
     585             :             - it's always passed when parent block had a different leader
     586             :             - it may be passed when we were leader for parent block (there
     587             :               are race conditions when it's not passed)
     588             : 
     589             :          2. block_id is taken from block_ids table if we were the leader
     590             :             for the parent block (when we were NOT the leader, because of
     591             :             equivocation, we can't store block_id in the table)
     592             : 
     593             :          chained_merkle_root is stored in block_ids table at target_slot
     594             :          and it's progressively updated as more microblocks are received.
     595             :          As a result, when we move to a new slot, the block_ids table at
     596             :          the old slot will contain the block_id.
     597             : 
     598             :          The block_ids table is designed to protect against the race condition
     599             :          case in 1., therefore the table may not be set in some cases, e.g. if
     600             :          a validator (re)starts, but in those cases we don't expect the race
     601             :          condition to apply. */
     602           0 :       ctx->chained_merkle_root = ctx->block_ids[ target_slot % BLOCK_IDS_TABLE_CNT ];
     603           0 :       if( FD_UNLIKELY( SHOULD_PROCESS_THESE_SHREDS ) ) {
     604           0 :         if( FD_LIKELY( entry_meta->parent_block_id_valid ) ) {
     605             :           /* 1. Initialize chained_merkle_root sent from poh tile */
     606           0 :           memcpy( ctx->chained_merkle_root, entry_meta->parent_block_id, FD_SHRED_MERKLE_ROOT_SZ );
     607           0 :         } else {
     608           0 :           ulong parent_slot = target_slot - entry_meta->parent_offset;
     609           0 :           fd_epoch_leaders_t const * lsched = fd_stake_ci_get_lsched_for_slot( ctx->stake_ci, parent_slot );
     610           0 :           fd_pubkey_t const * slot_leader = fd_epoch_leaders_get( lsched, parent_slot );
     611             : 
     612           0 :           if( lsched && slot_leader && fd_memeq( slot_leader, ctx->identity_key, sizeof(fd_pubkey_t) ) ) {
     613             :             /* 2. Initialize chained_merkle_root from block_ids table, if we were the leader */
     614           0 :             memcpy( ctx->chained_merkle_root, ctx->block_ids[ parent_slot % BLOCK_IDS_TABLE_CNT ], FD_SHRED_MERKLE_ROOT_SZ );
     615           0 :           } else {
     616             :             /* This should never happen, log a metric and set chained_merkle_root to 0 */
     617           0 :             ctx->metrics->invalid_block_id_cnt++;
     618           0 :             memset( ctx->chained_merkle_root, 0, FD_SHRED_MERKLE_ROOT_SZ );
     619           0 :           }
     620           0 :         }
     621           0 :       }
     622           0 :     }
     623             : 
     624           0 :     if( FD_LIKELY( !SHOULD_PROCESS_THESE_SHREDS ) ) {
     625             :       /* If we are not processing this batch, filter in after_frag. */
     626           0 :       ctx->skip_frag = 1;
     627           0 :     }
     628             : 
     629           0 :     ulong   pending_batch_wmark = FD_SHRED_BATCH_WMARK_CHAINED;
     630           0 :     uchar * chained_merkle_root = ctx->chained_merkle_root;
     631             :     /* All fec sets in the last batch of a block need to be resigned.
     632             :        This needs to match Agave's behavior - as a reference, see:
     633             :        https://github.com/anza-xyz/agave/blob/v2.3/ledger/src/shred/merkle.rs#L1040 */
     634           0 :     if( FD_UNLIKELY( entry_meta->block_complete==1 ) ) {
     635           0 :       pending_batch_wmark = FD_SHRED_BATCH_WMARK_RESIGNED;
     636           0 :     }
     637             : 
     638             :     /* If this microblock completes the block, the batch is then
     639             :        finalized here.  Otherwise, we check whether the new entry
     640             :        would exceed the pending_batch_wmark.  If true, then the
     641             :        batch is closed now, shredded, and a new batch is started
     642             :        with the incoming microblock.  If false, no shredding takes
     643             :        place, and the microblock is added to the current batch.
     644             :        Pack limits entry bytes so this batching cannot exceed
     645             :        max_shred_idx. */
     646           0 :     int is_marker                = entry_meta->block_complete==-1;
     647           0 :     int writing_marker           = 0;
     648           0 :     int forced_end_batch         = entry_meta->block_complete | new_slot;
     649           0 :     int batch_would_exceed_wmark = ( ctx->pending_batch.pos + entry_sz ) > pending_batch_wmark;
     650           0 :     int include_in_current_batch = !is_marker && ( forced_end_batch | ( !batch_would_exceed_wmark ) );
     651           0 :     int process_current_batch    = is_marker ? !!ctx->pending_batch.pos : ( forced_end_batch | batch_would_exceed_wmark );
     652           0 :     int init_new_batch           = !include_in_current_batch;
     653             : 
     654           0 :     if( FD_LIKELY( include_in_current_batch ) ) {
     655           0 :       if( FD_UNLIKELY( SHOULD_PROCESS_THESE_SHREDS ) ) {
     656             :         /* Ugh, yet another memcpy */
     657           0 :         fd_memcpy_tn( ctx->pending_batch.payload + ctx->pending_batch.pos, entry, entry_sz );
     658           0 :       }
     659           0 :       ctx->pending_batch.pos            += entry_sz;
     660           0 :       ctx->pending_batch.microblock_cnt += 1UL;
     661           0 :     }
     662             : 
     663           0 : alpenglow_marker:
     664           0 :     if( FD_LIKELY( process_current_batch )) {
     665           0 :       ulong batch_sz = sizeof(ulong) + ctx->pending_batch.pos;
     666             : 
     667           0 :       if( FD_UNLIKELY( SHOULD_PROCESS_THESE_SHREDS ) ) {
     668             :         /* If it's our turn, shred this batch. FD_UNLIKELY because shred
     669             :            tile cnt generally >= 2 */
     670             : 
     671           0 :         long shredding_timing = -fd_tickcount();
     672             : 
     673           0 :         if( FD_UNLIKELY( !writing_marker ) ) ctx->send_fec_set_cnt = 0UL; /* verbose */
     674             : 
     675           0 :         fd_shredder_init_batch( ctx->shredder, ctx->pending_batch.raw, batch_sz, target_slot, entry_meta );
     676             : 
     677           0 :         ulong fec_set_cnt = fd_shredder_count_fec_sets( batch_sz, entry_meta->block_complete==1 );
     678           0 :         ulong pend_idx    = ctx->send_fec_set_cnt;
     679           0 :         for( ulong j=0UL; j<fec_set_cnt; j++ ) {
     680             : 
     681           0 :           fd_fec_set_t * out = ctx->fec_sets + ctx->shredder_fec_set_idx;
     682             : 
     683           0 :           FD_TEST( fd_shredder_next_fec_set( ctx->shredder, out, chained_merkle_root ) );
     684           0 :           FD_TEST( pend_idx<FD_SHRED_BATCH_FEC_SETS_MAX );
     685           0 :           memcpy( ctx->out_merkle_roots[pend_idx].hash, chained_merkle_root, 32UL );
     686             : 
     687           0 :           out->data_shred_rcvd     = 0U;
     688           0 :           out->parity_shred_rcvd   = 0U;
     689           0 :           out->turbine_shred_rcvd  = 0UL;
     690           0 :           out->repair_shred_rcvd   = 0UL;
     691             : 
     692           0 :           FD_TEST( ctx->send_fec_set_cnt<FD_SHRED_BATCH_FEC_SETS_MAX );
     693           0 :           ctx->send_fec_set_idx[ ctx->send_fec_set_cnt ] = ctx->shredder_fec_set_idx;
     694           0 :           ctx->send_fec_set_cnt += 1UL;
     695           0 :           ctx->shredder_fec_set_idx = (ctx->shredder_fec_set_idx+1UL)%ctx->shredder_max_fec_set_idx;
     696             : 
     697           0 :           pend_idx++;
     698           0 :         }
     699             : 
     700           0 :         fd_shredder_fini_batch( ctx->shredder );
     701           0 :         shredding_timing += fd_tickcount();
     702             : 
     703             :         /* Update metrics */
     704           0 :         fd_histf_sample( ctx->metrics->batch_sz,             batch_sz                          );
     705           0 :         fd_histf_sample( ctx->metrics->batch_microblock_cnt, ctx->pending_batch.microblock_cnt );
     706           0 :         fd_histf_sample( ctx->metrics->shredding_timing,     (ulong)shredding_timing           );
     707           0 :       } else {
     708           0 :         if( FD_UNLIKELY( !writing_marker ) ) ctx->send_fec_set_cnt = 0UL; /* verbose */
     709             : 
     710           0 :         fd_shredder_skip_batch( ctx->shredder, batch_sz, target_slot, entry_meta->block_complete==1 );
     711           0 :       }
     712             : 
     713           0 :       ctx->pending_batch.slot           = 0UL;
     714           0 :       ctx->pending_batch.pos            = 0UL;
     715           0 :       ctx->pending_batch.microblock_cnt = 0UL;
     716           0 :       ctx->batch_cnt++;
     717           0 :     }
     718             : 
     719           0 :     if( FD_UNLIKELY( init_new_batch && !writing_marker ) ) {
     720             :       /* TODO: this assumes that SHOULD_PROCESS_THESE_SHREDS is
     721             :          constant across batches.  Otherwise, the condition may
     722             :          need to be removed (or adjusted). */
     723           0 :       if( FD_UNLIKELY( SHOULD_PROCESS_THESE_SHREDS ) ) {
     724             :         /* Ugh, yet another memcpy */
     725           0 :         fd_memcpy_tn( is_marker ? ctx->pending_batch.raw : ctx->pending_batch.payload + 0UL /* verbose */, entry, entry_sz );
     726           0 :       }
     727           0 :       ctx->pending_batch.slot           = target_slot;
     728           0 :       ctx->pending_batch.pos            = fd_ulong_if( is_marker, entry_sz-sizeof(ulong), entry_sz );
     729           0 :       ctx->pending_batch.microblock_cnt = fd_ulong_if( is_marker, 0UL, 1UL                 );
     730           0 :     }
     731             : 
     732             :     /* The entry opened a batch of its own, so close it now. */
     733           0 :     if( FD_UNLIKELY( is_marker && !writing_marker ) ) {
     734           0 :       process_current_batch = 1;
     735           0 :       writing_marker        = 1;
     736           0 :       goto alpenglow_marker;
     737           0 :     }
     738           0 :   } else if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_NET ) ) {
     739             :     /* The common case, from the net tile.  The FEC resolver API does
     740             :        not present a prepare/commit model. If we get overrun between
     741             :        when the FEC resolver verifies the signature and when it stores
     742             :        the local copy, we could end up storing and retransmitting
     743             :        garbage.  Instead we copy it locally, sadly, and only give it to
     744             :        the FEC resolver when we know it won't be overrun anymore. */
     745           0 :     uchar const * dcache_entry = fd_net_rx_translate_frag( &ctx->in[ in_idx ].net_rx, chunk, ctl, sz );
     746           0 :     ulong hdr_sz = fd_disco_netmux_sig_hdr_sz( sig );
     747           0 :     FD_TEST( hdr_sz <= sz ); /* Should be ensured by the net tile */
     748             :     /* ctx->shred_limit is the smallest per-slot max_shred_idx, so no
     749             :        later parse is stricter.  The result may be garbage if the frag
     750             :        is overrun meanwhile, which the stem detects before after_frag. */
     751           0 :     fd_shred_t const * shred = fd_shred_parse( dcache_entry+hdr_sz, sz-hdr_sz, ctx->shred_limit );
     752           0 :     if( FD_UNLIKELY( !shred ) ) {
     753           0 :       ulong owner = sz-hdr_sz>=sizeof(ulong) ? fd_ulong_load_8( dcache_entry+hdr_sz )%ctx->round_robin_cnt : 0UL; /* round-robin key, the signature */
     754           0 :       ctx->parse_failed = owner==ctx->round_robin_id;
     755           0 :       ctx->skip_frag    = 1;
     756           0 :       return;
     757           0 :     };
     758             : 
     759             :     /* all shreds in the same FEC set will have the same signature
     760             :        so we can round-robin shreds between the shred tiles based on
     761             :        just the signature without splitting individual FEC sets. */
     762           0 :     if( FD_LIKELY( fd_ulong_load_8( shred->signature )%ctx->round_robin_cnt!=ctx->round_robin_id ) ) {
     763           0 :       ctx->skip_frag = 1;
     764           0 :       return;
     765           0 :     }
     766             : 
     767           0 :     if( FD_UNLIKELY( fd_disco_netmux_sig_proto( sig )==DST_PROTO_REPAIR ) ) {
     768           0 :       ctx->metrics->repair_rcv_cnt++;
     769           0 :       ctx->metrics->repair_rcv_bytes += sz;
     770           0 :     } else {
     771           0 :       ctx->metrics->turbine_rcv_cnt++;
     772           0 :       ctx->metrics->turbine_rcv_bytes += sz;
     773           0 :     }
     774             : 
     775             :     /* Drop unchained merkle shreds */
     776           0 :     int is_unchained = !fd_shred_is_chained( fd_shred_type( shred->variant ) );
     777           0 :     if( FD_UNLIKELY( is_unchained ) ) {
     778           0 :       ctx->metrics->shred_rejected_unchained_cnt++;
     779           0 :       ctx->skip_frag = 1;
     780           0 :       return;
     781           0 :     };
     782             : 
     783           0 :     fd_memcpy( ctx->shred_buffer, dcache_entry+hdr_sz, sz-hdr_sz );
     784           0 :     ctx->shred_buffer_sz = sz-hdr_sz;
     785           0 :   }
     786           0 : }
     787             : 
     788             : static inline void
     789             : send_shred( fd_shred_ctx_t                 * ctx,
     790             :             fd_stem_context_t              * stem,
     791             :             fd_shred_t const               * shred,
     792             :             fd_shred_dest_weighted_t const * dest,
     793           0 :             ulong                            tsorig ) {
     794             : 
     795           0 :   if( FD_UNLIKELY( !dest->ip4 ) ) return;
     796             : 
     797           0 :   uchar * packet = fd_chunk_to_laddr( ctx->net_out_mem, ctx->net_out_chunk );
     798             : 
     799           0 :   int is_data = fd_shred_is_data( fd_shred_type( shred->variant ) );
     800           0 :   fd_ip4_udp_hdrs_t * hdr  = (fd_ip4_udp_hdrs_t *)packet;
     801           0 :   *hdr = *( is_data ? ctx->data_shred_net_hdr : ctx->parity_shred_net_hdr );
     802             : 
     803           0 :   fd_ip4_hdr_t * ip4 = hdr->ip4;
     804           0 :   ip4->daddr  = dest->ip4;
     805           0 :   ip4->net_id = fd_ushort_bswap( ctx->net_id++ );
     806           0 :   ip4->check  = 0U;
     807           0 :   ip4->check  = fd_ip4_hdr_check_fast( ip4 );
     808             : 
     809           0 :   hdr->udp->net_dport = fd_ushort_bswap( dest->port );
     810             : 
     811           0 :   ulong shred_sz = fd_ulong_if( is_data, FD_SHRED_MIN_SZ, FD_SHRED_MAX_SZ );
     812           0 : #if FD_HAS_AVX
     813             :   /* We're going to copy this shred potentially a bunch of times without
     814             :      reading it again, and we'd rather not thrash our cache, so we want
     815             :      to use non-temporal writes here.  We need to make sure we don't
     816             :      touch the cache line containing the network headers that we just
     817             :      wrote to though.  We know the destination is 64 byte aligned.  */
     818           0 :   fd_memcpy_nt( packet+sizeof(fd_ip4_udp_hdrs_t), shred, shred_sz );
     819             : #else
     820             :   fd_memcpy   ( packet+sizeof(fd_ip4_udp_hdrs_t), shred, shred_sz );
     821             : #endif
     822             : 
     823           0 :   ulong pkt_sz = shred_sz + sizeof(fd_ip4_udp_hdrs_t);
     824           0 :   ulong tspub  = fd_frag_meta_ts_comp( fd_tickcount() );
     825           0 :   ulong sig    = fd_disco_netmux_sig( dest->ip4, dest->port, dest->ip4, DST_PROTO_OUTGOING, sizeof(fd_ip4_udp_hdrs_t) );
     826           0 :   ulong const chunk = ctx->net_out_chunk;
     827           0 :   fd_stem_publish( stem, NET_OUT_IDX, sig, chunk, pkt_sz, 0UL, tsorig, tspub );
     828           0 :   ctx->net_out_chunk = fd_dcache_compact_next( chunk, pkt_sz, ctx->net_out_chunk0, ctx->net_out_wmark );
     829           0 : }
     830             : 
     831             : /* Send the set's received (or, if received is 0, its produced and
     832             :    recovered) shreds to their turbine destinations: the leader's first
     833             :    hop, or our children. */
     834             : 
     835             : static void
     836             : fan_out( fd_shred_ctx_t *     ctx,
     837             :          fd_stem_context_t *  stem,
     838             :          fd_fec_set_t const * set,
     839             :          int                  is_leader,
     840             :          int                  received,
     841           0 :          ulong                tsorig ) {
     842           0 :   ulong fanout = 200UL; /* Default Agave's DATA_PLANE_FANOUT = 200UL */
     843           0 :   fd_shred_t const * shreds[ FD_REEDSOL_DATA_SHREDS_MAX+FD_REEDSOL_PARITY_SHREDS_MAX ];
     844           0 :   ulong k=0UL;
     845           0 :   for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ )
     846           0 :     if( !!(set->data_shred_rcvd   & (1U<<i))==!!received ) shreds[ k++ ] = set->data_shreds  [ i ].s;
     847           0 :   for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ )
     848           0 :     if( !!(set->parity_shred_rcvd & (1U<<i))==!!received ) shreds[ k++ ] = set->parity_shreds[ i ].s;
     849             : 
     850           0 :   if( FD_UNLIKELY( !k ) ) return;
     851           0 :   fd_shred_dest_t * sdest = fd_stake_ci_get_sdest_for_slot( ctx->stake_ci, shreds[ 0 ]->slot );
     852           0 :   if( FD_UNLIKELY( !sdest ) ) return;
     853             : 
     854           0 :   fd_shred_dest_idx_t * _dests = ctx->scratchpad_dests;
     855             : 
     856           0 :   ulong out_stride;
     857           0 :   ulong max_dest_cnt[1];
     858           0 :   fd_shred_dest_idx_t * dests;
     859           0 :   if( FD_LIKELY( !is_leader ) ) {
     860           0 :     out_stride = k;
     861           0 :     dests = fd_shred_dest_compute_children( sdest, shreds, k, _dests, k, fanout, fanout, max_dest_cnt );
     862           0 :     if( FD_UNLIKELY( !dests ) ) return; /* our own slot, or unknown leader: nothing to retransmit */
     863             : 
     864           0 :     for( ulong i=0UL; i<k; i++ ) {
     865           0 :       for( ulong j=0UL; j<ctx->adtl_dests_retransmit_cnt; j++ ) send_shred( ctx, stem, shreds[ i ], ctx->adtl_dests_retransmit+j, tsorig );
     866           0 :     }
     867           0 :   } else {
     868           0 :     for( ulong i=0UL; i<k; i++ ) {
     869           0 :       for( ulong j=0UL; j<ctx->adtl_dests_leader_cnt; j++ ) send_shred( ctx, stem, shreds[ i ], ctx->adtl_dests_leader+j, tsorig );
     870           0 :     }
     871           0 :     out_stride = k;
     872           0 :     *max_dest_cnt = 2UL; /* Root of turbine tree and next leader */
     873           0 :     dests = fd_shred_dest_compute_first( sdest, shreds, k, _dests );
     874             : 
     875             :     /* Send leader shreds to the next leader.  At the epoch boundary,
     876             :        this will be a no-op so we don't need to get the other sdest. */
     877           0 :     fd_shred_dest_idx_t next_leader = fd_shred_dest_leader_for_slot( sdest, shreds[ 0 ]->slot + 4UL );
     878           0 :     for( ulong i=0UL; i<k; i++ ) _dests[ k+i ] = fd_uint_if( next_leader==_dests[ i ], FD_SHRED_DEST_NO_DEST, next_leader );
     879           0 :   }
     880           0 :   if( FD_UNLIKELY( !dests ) ) return;
     881             : 
     882           0 :   for( ulong i=0UL; i<k; i++ ) {
     883           0 :     for( ulong j=0UL; j<*max_dest_cnt; j++ ) send_shred( ctx, stem, shreds[ i ], fd_shred_dest_idx_to_dest( sdest, dests[ j*out_stride+i ]), tsorig );
     884           0 :   }
     885           0 : }
     886             : 
     887             : /* Finish a complete FEC set: copy it into the store, tell repair and
     888             :    replay, and fan it out to the network. */
     889             : 
     890             : static void
     891             : complete_fec_set( fd_shred_ctx_t *         ctx,
     892             :                   fd_stem_context_t *      stem,
     893             :                   ulong                    fec_set_idx,
     894             :                   fd_bmtree_node_t const * merkle_root,
     895             :                   int                      is_leader,
     896           0 :                   ulong                    tsorig ) {
     897           0 :   fd_fec_set_t * set = ctx->fec_sets + fec_set_idx;
     898             : 
     899           0 :   fd_shred_t const * last = set->data_shreds[ FD_FEC_SHRED_CNT - 1 ].s;
     900             : 
     901             :   /* Broadcast locally produced shreds before any disk work. */
     902           0 :   if( FD_UNLIKELY( is_leader ) ) fan_out( ctx, stem, set, is_leader, 0, tsorig );
     903             : 
     904             :   /* Compute merkle root and chained merkle root. */
     905             : 
     906           0 :   int replay_fwd = 1;
     907           0 :   int again      = 0;
     908           0 :   if( FD_LIKELY( ctx->store ) ) {
     909           0 :     fd_hash_t const * mr = fd_type_pun_const( merkle_root );
     910             : 
     911             :     /* The payload is filled before the FEC is linked */
     912             : 
     913           0 :     if( FD_UNLIKELY( fd_store_query( ctx->map_join, mr ) ) ) {
     914           0 :       again = 1;
     915           0 :     } else {
     916           0 :       fd_store_fec_spill_stats_t spill[1];
     917           0 :       uint    data_idx;
     918           0 :       uchar * fec_data = fd_store_fec_data_reserve( ctx->store, ctx->disk_fd, &data_idx, spill );
     919           0 :       if( FD_UNLIKELY( spill->write_cnt ) ) {
     920           0 :         fd_histf_sample( ctx->metrics->fec_fallback_write_timing, spill->write_ticks );
     921           0 :         ctx->metrics->fec_fallback_write_cnt   += spill->write_cnt;
     922           0 :         ctx->metrics->fec_fallback_write_bytes += spill->write_bytes;
     923           0 :       }
     924           0 :       if( FD_UNLIKELY( !fec_data ) ) FD_LOG_CRIT(( "Store could not allocate a FEC payload" ));
     925           0 :       uint   data_sz = 0U;
     926           0 :       ushort shred_sz[ FD_FEC_SHRED_CNT ];
     927           0 :       for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) {
     928           0 :         fd_shred_t * data_shred = set->data_shreds[i].s;
     929           0 :         ulong        payload_sz = fd_shred_payload_sz( data_shred );
     930           0 :         if( FD_UNLIKELY( data_sz + payload_sz > ctx->store->fec_data_max ) ) {
     931           0 :           FD_LOG_CRIT(( "Shred tile %lu: completed FEC set %lu %u data_sz: %lu exceeds data_max: %lu", ctx->round_robin_id, data_shred->slot, data_shred->fec_set_idx, data_sz + payload_sz, ctx->store->fec_data_max ));
     932           0 :         }
     933           0 :         fd_memcpy_nt_nofence( fec_data + data_sz, fd_shred_data_payload( data_shred ), payload_sz );
     934           0 :         data_sz += (uint)payload_sz;
     935           0 :         FD_TEST( payload_sz<=USHORT_MAX );
     936           0 :         shred_sz[ i ] = (ushort)payload_sz;
     937           0 :       }
     938           0 :       _mm_sfence();
     939           0 :       fd_store_fec_t * fec;
     940           0 :       again = fd_store_insert( ctx->store, ctx->map_join, mr, last->slot, ctx->round_robin_id, data_idx, data_sz, shred_sz, &fec )==FD_MAP_ERR_KEY;
     941           0 :     }
     942           0 :     replay_fwd = !again || ctx->alpenglow;
     943           0 :   }
     944             : 
     945           0 :   if( FD_LIKELY( ctx->shred_out_idx!=ULONG_MAX && replay_fwd ) ) {
     946             : 
     947             :     /* Send all of the data shreds we recovered (weren't received).
     948             :        The chunks are all written before any is published, so the
     949             :        link burst must cover them or a chunk could be reused while
     950             :        an unreliable consumer still sees its old seq. */
     951           0 :     FD_STATIC_ASSERT( FD_SHRED_STEM_BURST>=32UL, shred_out_burst );
     952           0 :     ulong missing_chunk[ 32 ];
     953           0 :     ulong missing_cnt = 0UL;
     954           0 :     for( int i=0; !again && i<32; i++ ) {
     955           0 :       if( fd_uint_extract_bit( set->data_shred_rcvd, i )==0 ) {
     956           0 :         fd_shred_t * const missing = &set->data_shreds[ i ].s[0];
     957             : 
     958           0 :         fd_shred_base_t * shred_msg = (fd_shred_base_t *)fd_chunk_to_laddr( ctx->shred_out_mem, ctx->shred_out_chunk );
     959           0 :         fd_memcpy_nt_nofence( shred_msg->shred_, missing, fd_shred_sz( missing ) );
     960           0 :         memcpy( &shred_msg->merkle_root, merkle_root->hash, sizeof(fd_hash_t) );
     961             : 
     962           0 :         missing_chunk[ missing_cnt++ ] = ctx->shred_out_chunk;
     963           0 :         ctx->shred_out_chunk = fd_dcache_compact_next( ctx->shred_out_chunk, sizeof(fd_shred_base_t), ctx->shred_out_chunk0, ctx->shred_out_wmark );
     964           0 :       }
     965           0 :     }
     966             : 
     967           0 :     if( FD_LIKELY( missing_cnt ) ) {
     968           0 :       _mm_sfence();
     969           0 :       ulong sig   = ((ulong)FD_FEC_RESOLVER_SHRED_COMPLETES << 32UL) | SHRED_SIG_SRC_RECONSTRUCTED;
     970           0 :       ulong tspub = fd_frag_meta_ts_comp( fd_tickcount() );
     971           0 :       for( ulong i=0UL; i<missing_cnt; i++ ) fd_stem_publish( stem, ctx->shred_out_idx, sig, missing_chunk[ i ], sizeof(fd_shred_base_t), 0UL, tsorig, tspub );
     972           0 :     }
     973             : 
     974             :     /* Replay requires the FEC payload before this notification.
     975             :        Wire-shred persistence on rserve is asynchronous.
     976             : 
     977             :        This message, the shred msg, and the FEC evict msg constitute
     978             :        the max 3 possible messages to repair/replay per after_frag.
     979             :        In reality, it is only possible to publish all 3 in the case
     980             :        where we receive a coding shred first for a FEC set where
     981             :        (N=1,K=18), which allows for the FEC set to be instantly
     982             :        completed by the singular coding shred, and that also happens
     983             :        to evict a FEC set from the curr_map.  When fix-32 arrives, the
     984             :        link burst value can be lowered to 2. */
     985           0 :     ulong sig = again ? SHRED_SIG_FEC_COMPLETE_AGAIN : ( is_leader ? SHRED_SIG_FEC_COMPLETE_LEADER : SHRED_SIG_FEC_COMPLETE );
     986             : 
     987           0 :     fd_fec_complete_t * complete_msg = fd_chunk_to_laddr( ctx->shred_out_mem, ctx->shred_out_chunk );
     988           0 :     complete_msg->last_shred_hdr = *last;
     989           0 :     memcpy( &complete_msg->merkle_root, merkle_root->hash, sizeof(fd_hash_t) );
     990           0 :     complete_msg->chained_merkle_root = *(fd_hash_t *)fd_type_pun((uchar *)last + fd_shred_chain_off( last->variant ));
     991           0 :     if( FD_LIKELY( sig==SHRED_SIG_FEC_COMPLETE ) ) {
     992           0 :       complete_msg->turbine_shred_cnt       = (ulong)fd_ulong_popcnt( set->turbine_shred_rcvd );
     993           0 :       complete_msg->repair_shred_cnt        = (ulong)fd_ulong_popcnt( set->repair_shred_rcvd );
     994           0 :       complete_msg->reconstructed_shred_cnt = 2U*(uint)FD_FEC_SHRED_CNT-(uint)(fd_uint_popcnt( set->data_shred_rcvd ) + fd_uint_popcnt( set->parity_shred_rcvd ));
     995           0 :       complete_msg->data_shred_rcvd         = set->data_shred_rcvd;
     996           0 :       complete_msg->parity_shred_rcvd       = set->parity_shred_rcvd;
     997           0 :       complete_msg->repair_data_rcvd        = (uint)set->repair_shred_rcvd; /* data shreds are the low FD_FEC_SHRED_CNT bits */
     998           0 :     } else {
     999           0 :       complete_msg->turbine_shred_cnt       = 0U;
    1000           0 :       complete_msg->repair_shred_cnt        = 0U;
    1001           0 :       complete_msg->reconstructed_shred_cnt = 0U;
    1002           0 :       complete_msg->data_shred_rcvd         = 0U;
    1003           0 :       complete_msg->parity_shred_rcvd       = 0U;
    1004           0 :       complete_msg->repair_data_rcvd        = 0U;
    1005           0 :     }
    1006             : 
    1007           0 :     fd_stem_publish( stem, ctx->shred_out_idx, sig, ctx->shred_out_chunk, sizeof(fd_fec_complete_t), 0UL, tsorig, fd_frag_meta_ts_comp( fd_tickcount() ) );
    1008           0 :     ctx->shred_out_chunk = fd_dcache_compact_next( ctx->shred_out_chunk, sizeof(fd_fec_complete_t), ctx->shred_out_chunk0, ctx->shred_out_wmark );
    1009             : 
    1010           0 :   }
    1011             : 
    1012             :   /* Relay recovered shreds only after replay is told, computing their
    1013             :      turbine children is costly on staked nodes.  A set rebuilt purely
    1014             :      from repair is not on the live turbine path (catch-up), so its
    1015             :      recovered shreds are not relayed. */
    1016           0 :   if( FD_LIKELY( !is_leader && set->turbine_shred_rcvd ) ) fan_out( ctx, stem, set, is_leader, 0, tsorig );
    1017           0 : }
    1018             : 
    1019             : static void
    1020             : after_frag( fd_shred_ctx_t *    ctx,
    1021             :             ulong               in_idx,
    1022             :             ulong               seq,
    1023             :             ulong               sig,
    1024             :             ulong               sz,
    1025             :             ulong               tsorig,
    1026             :             ulong               _tspub,
    1027           0 :             fd_stem_context_t * stem ) {
    1028           0 :   (void)seq;
    1029           0 :   (void)sz;
    1030           0 :   (void)tsorig;
    1031           0 :   (void)_tspub;
    1032             : 
    1033           0 :   if( FD_UNLIKELY( ctx->skip_frag ) ) {
    1034           0 :     ctx->metrics->shred_processing_result[ FD_METRICS_ENUM_SHRED_PROCESS_RESULT_V_PARSE_FAILED_IDX ] += (ulong)ctx->parse_failed;
    1035           0 :     return;
    1036           0 :   }
    1037             : 
    1038           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_EPOCH ) ) {
    1039           0 :     fd_stake_ci_epoch_msg_fini( ctx->stake_ci );
    1040           0 :     return;
    1041           0 :   }
    1042             : 
    1043           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_ROOTEDR ) ) {
    1044           0 :     if( FD_LIKELY( (ctx->new_root > 0UL) & (ctx->new_root<ULONG_MAX) ) ) fd_fec_resolver_advance_slot_old( ctx->resolver, ctx->new_root );
    1045           0 :     return;
    1046           0 :   }
    1047             : 
    1048           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_GOSSIP ) ) {
    1049           0 :     if( ctx->gossip_upd_buf->tag==FD_GOSSIP_UPDATE_TAG_CONTACT_INFO ) {
    1050           0 :       fd_gossip_contact_info_t const * ci = ctx->gossip_upd_buf->contact_info->value;
    1051           0 :       fd_ip4_port_t tvu_addr;
    1052           0 :       tvu_addr.addr = ci->sockets[ FD_GOSSIP_CONTACT_INFO_SOCKET_TVU ].is_ipv6 ? 0U : ci->sockets[ FD_GOSSIP_CONTACT_INFO_SOCKET_TVU ].ip4;
    1053           0 :       tvu_addr.port = ci->sockets[ FD_GOSSIP_CONTACT_INFO_SOCKET_TVU ].port;
    1054           0 :       if( !tvu_addr.l ){
    1055           0 :         fd_stake_ci_dest_remove( ctx->stake_ci, fd_type_pun_const( ctx->gossip_upd_buf->origin ) );
    1056           0 :       } else {
    1057           0 :         fd_stake_ci_dest_update( ctx->stake_ci, fd_type_pun_const( ctx->gossip_upd_buf->origin ), tvu_addr.addr, fd_ushort_bswap( tvu_addr.port ) );
    1058           0 :       }
    1059           0 :     } else if( ctx->gossip_upd_buf->tag==FD_GOSSIP_UPDATE_TAG_CONTACT_INFO_REMOVE ) {
    1060           0 :       if( FD_UNLIKELY( !memcmp( ctx->identity_key->uc, ctx->gossip_upd_buf->origin, 32UL ) ) ) {
    1061             :         /* If our own contact info was dropped, we update with dummy IP
    1062             :            instead of removing since stake_ci expects our contact info
    1063             :            in the sdests table all the time. fd_stake_ci_new initializes
    1064             :            both ei->sdests with our contact info so this should always
    1065             :            update (and not append). */
    1066           0 :         fd_stake_ci_dest_update( ctx->stake_ci, fd_type_pun_const( ctx->gossip_upd_buf->origin ), 1U, 0U );
    1067           0 :       } else {
    1068           0 :         fd_stake_ci_dest_remove( ctx->stake_ci, fd_type_pun_const( ctx->gossip_upd_buf->origin ) );
    1069           0 :       }
    1070           0 :     }
    1071           0 :     return;
    1072           0 :   }
    1073             : 
    1074           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_SIGN ) ) {
    1075           0 :     FD_TEST( ctx->sign_pend_cnt );
    1076             : 
    1077           0 :     ctx->sign_seq++;
    1078           0 :     fd_shred_sign_pend_t * pend = ctx->sign_pend + ctx->sign_pend_head;
    1079           0 :     ctx->sign_pend_head = (ctx->sign_pend_head+1UL)%FD_SHRED_SIGN_PEND_MAX;
    1080           0 :     ctx->sign_pend_cnt--;
    1081             : 
    1082           0 :     fd_fec_set_t * set = ctx->fec_sets + pend->fec_set_idx;
    1083           0 :     for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) fd_memcpy( set->data_shreds  [ i ].s->signature, ctx->signature, FD_ED25519_SIG_SZ );
    1084           0 :     for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) fd_memcpy( set->parity_shreds[ i ].s->signature, ctx->signature, FD_ED25519_SIG_SZ );
    1085           0 :     complete_fec_set( ctx, stem, pend->fec_set_idx, &pend->merkle_root, 1, pend->tsorig );
    1086           0 :     return;
    1087           0 :   }
    1088             : 
    1089           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_POH ) ) {
    1090           0 :     FD_TEST( ctx->sign_pend_cnt+ctx->send_fec_set_cnt<=FD_SHRED_SIGN_PEND_MAX );
    1091           0 :     for( ulong k=0UL; k<ctx->send_fec_set_cnt; k++ ) {
    1092           0 :       fd_shred_sign_pend_t * pend = ctx->sign_pend + (ctx->sign_pend_head+ctx->sign_pend_cnt++)%FD_SHRED_SIGN_PEND_MAX;
    1093           0 :       pend->fec_set_idx = ctx->send_fec_set_idx[ k ];
    1094           0 :       pend->tsorig      = ctx->tsorig;
    1095           0 :       pend->merkle_root = ctx->out_merkle_roots[ k ];
    1096             : 
    1097           0 :       memcpy( fd_chunk_to_laddr( ctx->sign_out_mem, ctx->sign_out_chunk ), ctx->out_merkle_roots[ k ].hash, 32UL );
    1098           0 :       fd_stem_publish( stem, SIGN_OUT_IDX, FD_KEYGUARD_SIGN_TYPE_ED25519, ctx->sign_out_chunk, 32UL, 0UL, ctx->tsorig, fd_frag_meta_ts_comp( fd_tickcount() ) );
    1099           0 :       ctx->sign_out_chunk = fd_dcache_compact_next( ctx->sign_out_chunk, 32UL, ctx->sign_out_chunk0, ctx->sign_out_wmark );
    1100           0 :     }
    1101           0 :     return;
    1102           0 :   }
    1103           0 :   if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_REPAIR ) ) {
    1104           0 :     return;
    1105           0 :   }
    1106             : 
    1107           0 :   ulong fanout = 200UL; /* Default Agave's DATA_PLANE_FANOUT = 200UL */
    1108             : 
    1109           0 :   if( FD_LIKELY( ctx->in_kind[ in_idx ]==IN_KIND_NET ) ) {
    1110           0 :     uchar * shred_buffer    = ctx->shred_buffer;
    1111           0 :     ulong   shred_buffer_sz = ctx->shred_buffer_sz;
    1112             : 
    1113             :     /* Parsed in during_frag */
    1114           0 :     fd_shred_t const * shred = (fd_shred_t const *)shred_buffer;
    1115           0 :     ulong max_shred_idx = ctx->current_max_shred_idx;
    1116           0 :     if( FD_UNLIKELY( shred->slot< ctx->current_max_shred_idx_start_slot ) ) max_shred_idx = ctx->prev_max_shred_idx;
    1117           0 :     if( FD_UNLIKELY( shred->slot>=ctx->next_max_shred_idx_start_slot    ) ) max_shred_idx = ctx->next_max_shred_idx;
    1118             : 
    1119           0 :     fd_epoch_leaders_t const * lsched = fd_stake_ci_get_lsched_for_slot( ctx->stake_ci, shred->slot );
    1120           0 :     if( FD_UNLIKELY( !lsched      ) ) { ctx->metrics->shred_processing_result[ FD_METRICS_ENUM_SHRED_PROCESS_RESULT_V_LEADER_UNKNOWN_IDX ]++; return; }
    1121             : 
    1122           0 :     fd_pubkey_t const * slot_leader = fd_epoch_leaders_get( lsched, shred->slot );
    1123           0 :     if( FD_UNLIKELY( !slot_leader ) ) { ctx->metrics->shred_processing_result[ FD_METRICS_ENUM_SHRED_PROCESS_RESULT_V_LEADER_UNKNOWN_IDX ]++; return; } /* Count this as bad slot too */
    1124             : 
    1125             :     /* Our own block echoed back by a relay: we already have it, so skip
    1126             :        the verify and recovery.  Repair responses for our own slots are
    1127             :        kept, so a restarted leader can repair its block. */
    1128           0 :     if( FD_UNLIKELY( fd_disco_netmux_sig_proto( sig )!=DST_PROTO_REPAIR && fd_memeq( slot_leader, ctx->identity_key, sizeof(fd_pubkey_t) ) ) ) {
    1129           0 :       ctx->metrics->shred_processing_result[ FD_METRICS_ENUM_SHRED_PROCESS_RESULT_V_OWN_LEADER_ECHOED_IDX ]++;
    1130           0 :       return;
    1131           0 :     }
    1132             : 
    1133           0 :     fd_fec_set_t const * out_fec_set[1];
    1134           0 :     fd_shred_t const   * out_shred[1];
    1135           0 :     fd_fec_resolver_spilled_t spilled_fec = { 0 };
    1136           0 :     int from_repair = 0;
    1137             : 
    1138           0 :     uint nonce = UINT_MAX;
    1139           0 :     ulong shred_sz = fd_shred_sz( shred );
    1140           0 :     if( FD_UNLIKELY( (fd_disco_netmux_sig_proto( sig )==DST_PROTO_REPAIR) & (shred_buffer_sz>=shred_sz+sizeof(uint)) ) ) {
    1141           0 :       nonce = FD_LOAD(uint, shred_buffer + shred_sz );
    1142           0 :       long est_now_ns = fd_log_wallclock(); /* TODO: switch to fd_clock for performance */
    1143           0 :       int  slot_complete = fd_shred_is_data( fd_shred_type( shred->variant ) ) && (shred->data.flags & FD_SHRED_DATA_FLAG_SLOT_COMPLETE);
    1144           0 :       int  nonce_okay = fd_rnonce_ss_verify( ctx->repair_nonce_ss, nonce, shred->slot, shred->idx, slot_complete, est_now_ns );
    1145           0 :       ctx->metrics->bad_nonce += (ulong)(!nonce_okay);
    1146           0 :       from_repair = nonce_okay;
    1147           0 :     }
    1148             : 
    1149           0 :     uint shred_source = fd_disco_netmux_sig_proto( sig )==DST_PROTO_REPAIR
    1150           0 :                       ? fd_uint_if( from_repair, FD_FEC_RESOLVER_SHRED_SRC_REPAIR, FD_FEC_RESOLVER_SHRED_SRC_BAD_REPAIR )
    1151           0 :                       : FD_FEC_RESOLVER_SHRED_SRC_TURBINE;
    1152             : 
    1153           0 :     long add_shred_timing  = -fd_tickcount();
    1154           0 :     int rv = fd_fec_resolver_add_shred( ctx->resolver, shred, shred_buffer_sz, max_shred_idx, shred_source, slot_leader->uc, out_fec_set, out_shred, &ctx->out_merkle_roots[0], &spilled_fec );
    1155           0 :     add_shred_timing      +=  fd_tickcount();
    1156             : 
    1157           0 :     fd_histf_sample( ctx->metrics->add_shred_timing, (ulong)add_shred_timing );
    1158           0 :     ctx->metrics->shred_processing_result[ rv + FD_FEC_RESOLVER_ADD_SHRED_RETVAL_OFF+FD_SHRED_ADD_SHRED_EXTRA_RETVAL_CNT ]++;
    1159             : 
    1160           0 :     if( FD_UNLIKELY( ctx->shred_out_idx!=ULONG_MAX &&
    1161           0 :                      spilled_fec.slot!=0 ) ) {
    1162             :       /* We've spilled an in-progress FEC set in the fec_resolver. We
    1163             :          need to let repair know to clear out it's cached info for that
    1164             :          fec set and re-repair those shreds. */
    1165           0 :       fd_fec_evicted_t * evicted_msg = (fd_fec_evicted_t *)fd_type_pun( fd_chunk_to_laddr( ctx->shred_out_mem, ctx->shred_out_chunk ) );
    1166           0 :       evicted_msg->slot        = spilled_fec.slot;
    1167           0 :       evicted_msg->fec_set_idx = spilled_fec.fec_set_idx;
    1168           0 :       fd_memcpy( evicted_msg->merkle_root.uc, spilled_fec.merkle_root->hash, sizeof(fd_hash_t) );
    1169             : 
    1170           0 :       fd_stem_publish( stem, ctx->shred_out_idx, SHRED_SIG_FEC_EVICTED, ctx->shred_out_chunk, sizeof(fd_fec_evicted_t), 0, ctx->tsorig, fd_frag_meta_ts_comp( fd_tickcount() ) );
    1171           0 :       ctx->shred_out_chunk = fd_dcache_compact_next( ctx->shred_out_chunk, sizeof(fd_fec_evicted_t), ctx->shred_out_chunk0, ctx->shred_out_wmark );
    1172           0 :     }
    1173             : 
    1174             :     /* Send rotor future slots past max_live_slots so that unstaked
    1175             :        nodes can catch up. */
    1176             : 
    1177           0 :     if( FD_UNLIKELY( ctx->alpenglow &&
    1178           0 :                      rv==FD_FEC_RESOLVER_SHRED_IGNORED &&
    1179           0 :                      shred_source==FD_FEC_RESOLVER_SHRED_SRC_TURBINE &&
    1180           0 :                      shred->version==ctx->shredder->shred_version &&
    1181           0 :                      shred->slot>ctx->future_slot &&
    1182           0 :                      ctx->new_root<ULONG_MAX &&
    1183           0 :                      shred->slot>=ctx->new_root+ctx->slot_max &&
    1184           0 :                      fd_shred_type( shred->variant )!=FD_SHRED_TYPE_LEGACY_DATA &&
    1185           0 :                      fd_shred_type( shred->variant )!=FD_SHRED_TYPE_LEGACY_CODE ) ) {
    1186           0 :       fd_bmtree_node_t root[1];
    1187           0 :       int signed_ = fd_shred_merkle_root( shred, ctx->bmtree_mem, root ) &&
    1188           0 :                     FD_ED25519_SUCCESS==fd_ed25519_verify( root->hash, FD_SHRED_MERKLE_ROOT_SZ, shred->signature, slot_leader->uc, ctx->sha512 );
    1189           0 :       if( FD_LIKELY( signed_ ) ) {
    1190           0 :         ctx->future_slot = shred->slot;
    1191           0 :         fd_stem_publish( stem, ctx->shred_out_idx, fd_shred_sig_future( shred->slot ), 0UL, 0UL, 0UL, ctx->tsorig, fd_frag_meta_ts_comp( fd_tickcount() ) );
    1192           0 :       }
    1193           0 :     }
    1194             : 
    1195           0 :     if( FD_LIKELY( ctx->shred_out_idx!=ULONG_MAX
    1196           0 :                    && ( ( rv==FD_FEC_RESOLVER_SHRED_OKAY )
    1197           0 :                       | ( rv==FD_FEC_RESOLVER_SHRED_COMPLETES )
    1198           0 :                       | ( rv==FD_FEC_RESOLVER_SHRED_DUPLICATE )
    1199           0 :                       | ( rv==FD_FEC_RESOLVER_SHRED_EQUIVOC   ) ) ) ) {
    1200             : 
    1201             :       /* Construct the sig from fec_resolver result and shred source. */
    1202             : 
    1203           0 :       ulong _sig = fd_disco_netmux_sig_proto( sig )==DST_PROTO_REPAIR
    1204           0 :                      ? ( from_repair /*nonce_okay*/ ? SHRED_SIG_SRC_REPAIR : SHRED_SIG_SRC_BAD_REPAIR )
    1205           0 :                      : ( SHRED_SIG_SRC_TURBINE );
    1206           0 :       _sig = ((ulong)rv << 32UL) | _sig;
    1207             : 
    1208             :       /* Copy the full shred into the frag and publish. */
    1209             : 
    1210           0 :       fd_shred_base_t * shred_msg = (fd_shred_base_t *)fd_chunk_to_laddr( ctx->shred_out_mem, ctx->shred_out_chunk );
    1211           0 :       memcpy(  shred_msg->shred_, shred, fd_shred_sz( shred ) );
    1212           0 :       memcpy( &shred_msg->merkle_root, ctx->out_merkle_roots[0].hash, sizeof(fd_hash_t) );
    1213           0 :       if( FD_UNLIKELY( fd_disco_netmux_sig_proto( sig )==DST_PROTO_REPAIR ) ) { shred_msg->rnonce = nonce; }
    1214             : 
    1215           0 :       ulong tspub = fd_frag_meta_ts_comp( fd_tickcount() );
    1216           0 :       fd_stem_publish( stem, ctx->shred_out_idx, _sig, ctx->shred_out_chunk, sizeof(fd_shred_base_t), 0UL, ctx->tsorig, tspub );
    1217           0 :       ctx->shred_out_chunk = fd_dcache_compact_next( ctx->shred_out_chunk, sizeof(fd_shred_base_t), ctx->shred_out_chunk0, ctx->shred_out_wmark );
    1218           0 :     }
    1219             : 
    1220           0 :     if( FD_LIKELY( fd_disco_netmux_sig_proto( sig ) != DST_PROTO_REPAIR &&
    1221           0 :                  ( (rv==FD_FEC_RESOLVER_SHRED_OKAY) | (rv==FD_FEC_RESOLVER_SHRED_COMPLETES) ) ) ) {
    1222             :       /* Relay this shred */
    1223           0 :       if( FD_UNLIKELY( ctx->rtx_fseq && shred->slot>ctx->rtx_slot ) ) {
    1224           0 :         ctx->rtx_slot = shred->slot;
    1225           0 :         fd_fseq_update( ctx->rtx_fseq, shred->slot );
    1226           0 :       }
    1227           0 :       ulong max_dest_cnt[1];
    1228           0 :       do {
    1229             :         /* If we've validated the shred and it COMPLETES but we can't
    1230             :           compute the destination for whatever reason, don't forward
    1231             :           the shred, but still send it to the blockstore. */
    1232           0 :         fd_shred_dest_t * sdest = fd_stake_ci_get_sdest_for_slot( ctx->stake_ci, shred->slot );
    1233           0 :         if( FD_UNLIKELY( !sdest ) ) break;
    1234           0 :         fd_shred_dest_idx_t * dests = fd_shred_dest_compute_children( sdest, &shred, 1UL, ctx->scratchpad_dests, 1UL, fanout, fanout, max_dest_cnt );
    1235           0 :         if( FD_UNLIKELY( !dests ) ) break;
    1236             : 
    1237           0 :         for( ulong i=0UL; i<ctx->adtl_dests_retransmit_cnt; i++ ) send_shred( ctx, stem, *out_shred, ctx->adtl_dests_retransmit+i, ctx->tsorig );
    1238           0 :         for( ulong j=0UL; j<*max_dest_cnt; j++ ) send_shred( ctx, stem, *out_shred, fd_shred_dest_idx_to_dest( sdest, dests[ j ] ), ctx->tsorig );
    1239           0 :       } while( 0 );
    1240           0 :     }
    1241             : 
    1242           0 :     if( FD_LIKELY( rv!=FD_FEC_RESOLVER_SHRED_COMPLETES ) ) return;
    1243             : 
    1244           0 :     FD_TEST( ctx->fec_sets <= *out_fec_set );
    1245           0 :     complete_fec_set( ctx, stem, (ulong)(*out_fec_set - ctx->fec_sets), &ctx->out_merkle_roots[0], 0, ctx->tsorig );
    1246           0 :   }
    1247           0 : }
    1248             : 
    1249             : static void
    1250             : privileged_init( fd_topo_t const *      topo,
    1251           0 :                  fd_topo_tile_t const * tile ) {
    1252           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1253           0 :   FD_TEST( scratch!=NULL );
    1254             : 
    1255           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1256           0 :   fd_shred_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_shred_ctx_t ), sizeof( fd_shred_ctx_t ) );
    1257             : 
    1258           0 :   if( FD_UNLIKELY( !strcmp( tile->shred.identity_key_path, "" ) ) )
    1259           0 :     FD_LOG_ERR(( "identity_key_path not set" ));
    1260             : 
    1261           0 :   ctx->identity_key[ 0 ] = *(fd_pubkey_t const *)fd_type_pun_const( fd_keyload_load( tile->shred.identity_key_path, /* pubkey only: */ 1 ) );
    1262             : 
    1263           0 :   ctx->adtl_dests_retransmit_cnt = tile->shred.adtl_dests_retransmit_cnt;
    1264           0 :   fd_shred_resolve_additional_destinations( tile->shred.adtl_dests_retransmit,
    1265           0 :                                             tile->shred.adtl_dests_retransmit_cnt,
    1266           0 :                                             "tiles.shred.additional_shred_destinations_retransmit",
    1267           0 :                                             ctx->adtl_dests_retransmit );
    1268           0 :   ctx->adtl_dests_leader_cnt = tile->shred.adtl_dests_leader_cnt;
    1269           0 :   fd_shred_resolve_additional_destinations( tile->shred.adtl_dests_leader,
    1270           0 :                                             tile->shred.adtl_dests_leader_cnt,
    1271           0 :                                             "tiles.shred.additional_shred_destinations_leader",
    1272           0 :                                             ctx->adtl_dests_leader );
    1273             : 
    1274           0 :   if( FD_UNLIKELY( !fd_rng_secure( &(ctx->resolver_seed), sizeof(ulong) ) ) ) {
    1275           0 :     FD_LOG_CRIT(( "fd_rng_secure failed" ));
    1276           0 :   }
    1277           0 :   if( FD_UNLIKELY( !fd_rng_secure( &(ctx->shred_dest_seed), sizeof(ulong) ) ) ) {
    1278           0 :     FD_LOG_CRIT(( "fd_rng_secure failed" ));
    1279           0 :   }
    1280             : 
    1281           0 :   ctx->disk_fd = -1;
    1282           0 :   ulong store_obj_id = fd_pod_queryf_ulong( topo->props, ULONG_MAX, "store" );
    1283           0 :   if( FD_LIKELY( store_obj_id!=ULONG_MAX ) ) {
    1284           0 :     fd_store_t * store = fd_store_join( fd_topo_obj_laddr( topo, store_obj_id ) );
    1285           0 :     FD_TEST( store );
    1286           0 :     ctx->disk_fd = FD_STORE_FD_RW;
    1287           0 :     if( FD_UNLIKELY( fcntl( ctx->disk_fd, F_GETFD )<0 ) )
    1288           0 :       FD_LOG_ERR(( "store file descriptor was not inherited (%i-%s)", errno, fd_io_strerror( errno ) ));
    1289           0 :   }
    1290             : 
    1291           0 : }
    1292             : 
    1293             : static void
    1294             : unprivileged_init( fd_topo_t const *      topo,
    1295           0 :                    fd_topo_tile_t const * tile ) {
    1296             : 
    1297           0 :   FD_TEST( 0==strcmp( topo->links[tile->out_link_id[ NET_OUT_IDX   ]].name, "shred_net"   ) );
    1298           0 :   FD_TEST( 0==strcmp( topo->links[tile->out_link_id[ SIGN_OUT_IDX  ]].name, "shred_sign"  ) );
    1299             : 
    1300           0 :   if( FD_UNLIKELY( !tile->out_cnt ) )
    1301           0 :     FD_LOG_ERR(( "shred tile has no primary output link" ));
    1302             : 
    1303           0 :   ulong fec_exposure = tile->shred.fec_exposure;
    1304           0 :   if( FD_UNLIKELY( !fec_exposure ) ) FD_LOG_ERR(( "fec_exposure not set" ));
    1305             : 
    1306           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1307           0 :   FD_TEST( scratch!=NULL );
    1308             : 
    1309           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1310           0 :   fd_shred_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_shred_ctx_t ), sizeof( fd_shred_ctx_t ) );
    1311             : 
    1312           0 :   FD_CHECK_ERR( tile->in_cnt<=IN_LINK_MAX, "too many input links" );
    1313             : 
    1314           0 :   ctx->round_robin_cnt = fd_topo_tile_name_cnt( topo, tile->name );
    1315           0 :   ctx->round_robin_id  = tile->kind_id;
    1316           0 :   ctx->batch_cnt       = 0UL;
    1317           0 :   ctx->slot            = ULONG_MAX;
    1318           0 :   ctx->store           = NULL;
    1319             : 
    1320           0 :   ulong store_obj_id = fd_pod_queryf_ulong( topo->props, ULONG_MAX, "store" );
    1321           0 :   if( FD_LIKELY( store_obj_id!=ULONG_MAX ) ) {
    1322           0 :     ctx->store = fd_store_join( fd_topo_obj_laddr( topo, store_obj_id ) );
    1323           0 :     FD_TEST( ctx->store->magic==FD_STORE_MAGIC );
    1324           0 :     FD_TEST( fd_store_map_ljoin( ctx->store, ctx->map_join ) );
    1325           0 :   }
    1326           0 :   ctx->alpenglow = tile->shred.alpenglow;
    1327             : 
    1328             :   /* If the default partial_depth is ever changed, correspondingly
    1329             :      change the size of the fd_fec_intra_pool in fd_fec_repair. */
    1330           0 :   ulong fec_resolver_footprint = fd_fec_resolver_footprint( tile->shred.fec_resolver_depth, 1UL, fec_exposure+1UL,
    1331           0 :                                                             128UL * tile->shred.fec_resolver_depth );
    1332           0 :   ulong fec_set_cnt            = fd_shred_tile_fec_set_cnt( fec_exposure, tile->shred.fec_resolver_depth );
    1333             : 
    1334           0 :   void * fec_sets_shmem = NULL;
    1335             : 
    1336           0 :   ctx->rtx_fseq = NULL;
    1337           0 :   ctx->rtx_slot = 0UL;
    1338           0 :   ulong rtx_obj_id = fd_pod_queryf_ulong( topo->props, ULONG_MAX, "shred_rtx.%lu", tile->kind_id );
    1339           0 :   if( FD_UNLIKELY( rtx_obj_id!=ULONG_MAX ) ) {
    1340           0 :     ctx->rtx_fseq = fd_fseq_join( fd_topo_obj_laddr( topo, rtx_obj_id ) );
    1341           0 :     FD_TEST( ctx->rtx_fseq );
    1342           0 :   }
    1343             : 
    1344           0 :   ctx->shred_out_idx = fd_topo_find_tile_out_link( topo, tile, "shred_out", ctx->round_robin_id );
    1345           0 :   if( FD_LIKELY( ctx->shred_out_idx!=ULONG_MAX ) ) {
    1346           0 :     FD_TEST( fec_exposure==FD_SHRED_FIREDANCER_FEC_EXPOSURE );
    1347           0 :     fd_topo_link_t const * shred_out = &topo->links[ tile->out_link_id[ ctx->shred_out_idx ] ];
    1348           0 :     ctx->shred_out_mem    = topo->workspaces[ topo->objs[ shred_out->dcache_obj_id ].wksp_id ].wksp;
    1349           0 :     ctx->shred_out_chunk0 = fd_dcache_compact_chunk0( ctx->shred_out_mem, shred_out->dcache );
    1350           0 :     ctx->shred_out_wmark  = fd_dcache_compact_wmark ( ctx->shred_out_mem, shred_out->dcache, shred_out->mtu );
    1351           0 :     ctx->shred_out_chunk  = ctx->shred_out_chunk0;
    1352           0 :     FD_TEST( fd_dcache_compact_is_safe( ctx->shred_out_mem, shred_out->dcache, shred_out->mtu, shred_out->depth ) );
    1353           0 :     ulong fec_sets_required_cnt = fec_set_cnt*ctx->round_robin_cnt;
    1354           0 :     if( FD_LIKELY( ctx->store ) ) {
    1355           0 :       FD_TEST( ctx->store->fec_set_cnt>=fec_sets_required_cnt );
    1356           0 :       fd_fec_set_t * store_fec_sets = fd_store_fec_sets( ctx->store );
    1357           0 :       FD_TEST( store_fec_sets );
    1358             : 
    1359           0 :       fec_sets_shmem = store_fec_sets + ctx->round_robin_id*fec_set_cnt;
    1360           0 :     } else {
    1361           0 :       ulong fec_sets_obj_id = fd_pod_query_ulong( topo->props, "fec_sets", ULONG_MAX );
    1362           0 :       FD_TEST( fec_sets_obj_id!=ULONG_MAX );
    1363             : 
    1364           0 :       ulong fec_sets_sz = fd_pod_queryf_ulong( topo->props, 0UL, "obj.%lu.sz", fec_sets_obj_id );
    1365           0 :       FD_TEST( fec_sets_sz>=fec_sets_required_cnt*sizeof(fd_fec_set_t) );
    1366             : 
    1367           0 :       fd_fec_set_t * fec_sets = fd_topo_obj_laddr( topo, fec_sets_obj_id );
    1368           0 :       FD_TEST( fec_sets );
    1369             : 
    1370           0 :       fec_sets_shmem = fec_sets + ctx->round_robin_id*fec_set_cnt;
    1371           0 :     }
    1372             : 
    1373           0 :     ulong rnonce_ss_id = fd_pod_queryf_ulong( topo->props, ULONG_MAX, "rnonce_ss" );
    1374           0 :     FD_TEST( rnonce_ss_id!=ULONG_MAX );
    1375           0 :     memcpy( ctx->repair_nonce_ss, fd_topo_obj_laddr( topo, rnonce_ss_id ), sizeof(fd_rnonce_ss_t) );
    1376           0 :   }
    1377           0 :   if( FD_UNLIKELY( !fec_sets_shmem ) ) FD_LOG_ERR(( "missing FEC-set backing memory" ));
    1378             : 
    1379           0 :   if( FD_UNLIKELY( !tile->shred.fec_resolver_depth ) ) FD_LOG_ERR(( "fec_resolver_depth not set" ));
    1380           0 :   if( FD_UNLIKELY( !tile->shred.shred_listen_port  ) ) FD_LOG_ERR(( "shred_listen_port not set" ));
    1381             : 
    1382           0 :   void * _stake_ci = FD_SCRATCH_ALLOC_APPEND( l, fd_stake_ci_align(),              fd_stake_ci_footprint()            );
    1383           0 :   void * _resolver = FD_SCRATCH_ALLOC_APPEND( l, fd_fec_resolver_align(),          fec_resolver_footprint             );
    1384           0 :   void * _shredder = FD_SCRATCH_ALLOC_APPEND( l, fd_shredder_align(),              fd_shredder_footprint()            );
    1385             : 
    1386           0 :   fd_fec_set_t * fec_sets  = (fd_fec_set_t *)fec_sets_shmem;
    1387             : 
    1388           0 : #define NONNULL( x ) (__extension__({                                        \
    1389           0 :       __typeof__((x)) __x = (x);                                             \
    1390           0 :       if( FD_UNLIKELY( !__x ) ) FD_LOG_ERR(( #x " was unexpectedly NULL" )); \
    1391           0 :       __x; }))
    1392             : 
    1393           0 :   ushort expected_shred_version = tile->shred.expected_shred_version;
    1394             : 
    1395           0 :   ctx->keyswitch = fd_keyswitch_join( fd_topo_obj_laddr( topo, tile->id_keyswitch_obj_id ) );
    1396           0 :   FD_TEST( ctx->keyswitch );
    1397             : 
    1398             :   /* populate ctx */
    1399           0 :   fd_topo_link_t const * sign_out = &topo->links[ tile->out_link_id[ SIGN_OUT_IDX ] ];
    1400           0 :   FD_TEST( sign_out->mtu==32UL );
    1401           0 :   ctx->sign_out_mem    = topo->workspaces[ topo->objs[ sign_out->dcache_obj_id ].wksp_id ].wksp;
    1402           0 :   ctx->sign_out_chunk0 = fd_dcache_compact_chunk0( ctx->sign_out_mem, sign_out->dcache );
    1403           0 :   ctx->sign_out_wmark  = fd_dcache_compact_wmark ( ctx->sign_out_mem, sign_out->dcache, sign_out->mtu );
    1404           0 :   ctx->sign_out_chunk  = ctx->sign_out_chunk0;
    1405             : 
    1406           0 :   ctx->bench_max_shred_idx           = tile->shred.bench_max_shreds_per_block;
    1407           0 :   ulong shred_limit                  = tile->shred.max_shreds_per_block;
    1408           0 :   ctx->shred_limit                   = shred_limit;
    1409           0 :   fd_fec_set_t * resolver_sets       = fec_sets + fec_exposure + FD_SHRED_SIGN_PEND_MAX;
    1410           0 :   ctx->shredder = NONNULL( fd_shredder_join     ( fd_shredder_new     ( _shredder ) ) );
    1411           0 :   ctx->resolver = NONNULL( fd_fec_resolver_join ( fd_fec_resolver_new ( _resolver,
    1412           0 :                                                                         tile->shred.fec_resolver_depth, 1UL,
    1413           0 :                                                                         fec_exposure+1UL,
    1414           0 :                                                                         128UL * tile->shred.fec_resolver_depth,
    1415           0 :                                                                         tile->shred.alpenglow ? tile->shred.slot_max : 0UL,
    1416           0 :                                                                         resolver_sets,
    1417           0 :                                                                         ctx->resolver_seed ) ) );
    1418           0 :   FD_TEST( fd_sha512_join( fd_sha512_new( ctx->sha512 ) ) );
    1419           0 :   ctx->new_root    = 0UL;
    1420           0 :   ctx->slot_max    = tile->shred.slot_max;
    1421           0 :   ctx->future_slot = 0UL;
    1422             : 
    1423           0 :   if( FD_LIKELY( !!expected_shred_version ) ) {
    1424           0 :     fd_shredder_set_shred_version    ( ctx->shredder, expected_shred_version );
    1425           0 :     fd_fec_resolver_set_shred_version( ctx->resolver, expected_shred_version );
    1426           0 :   }
    1427             : 
    1428           0 :   ctx->fec_sets = fec_sets;
    1429             : 
    1430           0 :   ctx->stake_ci = fd_stake_ci_join( fd_stake_ci_new( _stake_ci, ctx->identity_key, ctx->shred_dest_seed ) );
    1431             : 
    1432           0 :   ctx->net_id   = (ushort)0;
    1433             : 
    1434           0 :   fd_ip4_udp_hdr_init( ctx->data_shred_net_hdr,   FD_SHRED_MIN_SZ, 0, tile->shred.shred_listen_port );
    1435           0 :   fd_ip4_udp_hdr_init( ctx->parity_shred_net_hdr, FD_SHRED_MAX_SZ, 0, tile->shred.shred_listen_port );
    1436             : 
    1437           0 :   for( ulong i=0UL; i<tile->in_cnt; i++ ) {
    1438           0 :     fd_topo_link_t const * link = &topo->links[ tile->in_link_id[ i ] ];
    1439           0 :     fd_topo_wksp_t const * link_wksp = &topo->workspaces[ topo->objs[ link->dcache_obj_id ].wksp_id ];
    1440             : 
    1441           0 :     if( FD_LIKELY(      !strcmp( link->name, "net_shred"    ) ) ) {
    1442           0 :       ctx->in_kind[ i ] = IN_KIND_NET;
    1443           0 :       fd_net_rx_bounds_init( &ctx->in[ i ].net_rx, link->dcache );
    1444           0 :       continue; /* only net_rx needs to be set in this case. */
    1445           0 :     }
    1446           0 :     else if( FD_LIKELY( !strcmp( link->name, "poh_shred"     ) ) ) ctx->in_kind[ i ] = IN_KIND_POH;
    1447           0 :     else if( FD_LIKELY( !strcmp( link->name, "replay_epoch"  ) ) ) ctx->in_kind[ i ] = IN_KIND_EPOCH;
    1448           0 :     else if( FD_LIKELY( !strcmp( link->name, "sign_shred"    ) ) ) ctx->in_kind[ i ] = IN_KIND_SIGN;
    1449           0 :     else if( FD_LIKELY( !strcmp( link->name, "ipecho_out"    ) ) ) ctx->in_kind[ i ] = IN_KIND_IPECHO;
    1450           0 :     else if( FD_LIKELY( !strcmp( link->name, "replay_slot"   ) ) ) ctx->in_kind[ i ] = IN_KIND_ROOTEDR;
    1451           0 :     else if( FD_LIKELY( !strcmp( link->name, "gossip_ciaddr" ) ) ) ctx->in_kind[ i ] = IN_KIND_GOSSIP;
    1452             : 
    1453           0 :     else FD_LOG_ERR(( "shred tile has unexpected input link %lu %s", i, link->name ));
    1454             : 
    1455           0 :     if( FD_LIKELY( !!link->mtu ) ) {
    1456           0 :       ctx->in[ i ].mem    = link_wksp->wksp;
    1457           0 :       ctx->in[ i ].chunk0 = fd_dcache_compact_chunk0( ctx->in[ i ].mem, link->dcache );
    1458           0 :       ctx->in[ i ].wmark  = fd_dcache_compact_wmark ( ctx->in[ i ].mem, link->dcache, link->mtu );
    1459           0 :     }
    1460           0 :   }
    1461             : 
    1462           0 :   fd_topo_link_t const * net_out = &topo->links[ tile->out_link_id[ NET_OUT_IDX ] ];
    1463             : 
    1464           0 :   ctx->net_out_chunk0 = fd_dcache_compact_chunk0( fd_wksp_containing( net_out->dcache ), net_out->dcache );
    1465           0 :   ctx->net_out_mem    = topo->workspaces[ topo->objs[ net_out->dcache_obj_id ].wksp_id ].wksp;
    1466           0 :   ctx->net_out_wmark  = fd_dcache_compact_wmark ( ctx->net_out_mem, net_out->dcache, net_out->mtu );
    1467           0 :   ctx->net_out_chunk  = ctx->net_out_chunk0;
    1468             : 
    1469           0 :   if( FD_LIKELY( ctx->shred_out_idx!=ULONG_MAX ) ) {
    1470           0 :     fd_topo_link_t const * shred_out = &topo->links[ tile->out_link_id[ ctx->shred_out_idx ] ];
    1471           0 :     ctx->shred_out_mem         = topo->workspaces[ topo->objs[ shred_out->dcache_obj_id ].wksp_id ].wksp;
    1472           0 :     ctx->shred_out_chunk0      = fd_dcache_compact_chunk0( ctx->shred_out_mem, shred_out->dcache );
    1473           0 :     ctx->shred_out_wmark       = fd_dcache_compact_wmark ( ctx->shred_out_mem, shred_out->dcache, shred_out->mtu );
    1474           0 :     ctx->shred_out_chunk       = ctx->shred_out_chunk0;
    1475           0 :     FD_TEST( fd_dcache_compact_is_safe( ctx->shred_out_mem, shred_out->dcache, shred_out->mtu, shred_out->depth ) );
    1476             :     /* An unreliable consumer ignores credits, so the dcache must hold
    1477             :        a full STEM_BURST beyond the mcache depth. */
    1478           0 :     FD_TEST( shred_out->burst>=FD_SHRED_STEM_BURST );
    1479           0 :   }
    1480             : 
    1481           0 :   ctx->poh_in_expect_seq = 0UL;
    1482             : 
    1483           0 :   ctx->sign_pend_head = 0UL;
    1484           0 :   ctx->sign_pend_cnt  = 0UL;
    1485           0 :   ctx->sign_seq       = 0UL;
    1486             : 
    1487           0 :   ctx->shredder_fec_set_idx = 0UL;
    1488           0 :   ctx->shredder_max_fec_set_idx = fec_exposure + FD_SHRED_SIGN_PEND_MAX;
    1489             : 
    1490           0 :   ctx->chained_merkle_root = NULL;
    1491           0 :   memset( ctx->out_merkle_roots, 0, sizeof(ctx->out_merkle_roots) );
    1492             : 
    1493           0 :   for( ulong i=0UL; i<FD_SHRED_BATCH_FEC_SETS_MAX; i++ ) { ctx->send_fec_set_idx[ i ] = ULONG_MAX; }
    1494           0 :   ctx->send_fec_set_cnt = 0UL;
    1495             : 
    1496           0 :   ctx->shred_buffer_sz  = 0UL;
    1497           0 :   memset( ctx->shred_buffer, 0xFF, FD_NET_MTU );
    1498             : 
    1499           0 :   fd_histf_join( fd_histf_new( ctx->metrics->batch_sz,             FD_MHIST_MIN(         SHRED, BATCH_SIZE_BYTES           ),
    1500           0 :                                                                    FD_MHIST_MAX(         SHRED, BATCH_SIZE_BYTES           ) ) );
    1501           0 :   fd_histf_join( fd_histf_new( ctx->metrics->batch_microblock_cnt, FD_MHIST_MIN(         SHRED, MICROBLOCK_PER_BATCH       ),
    1502           0 :                                                                    FD_MHIST_MAX(         SHRED, MICROBLOCK_PER_BATCH       ) ) );
    1503           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->metrics->shredding_timing,     FD_MHIST_EDGES_NS( SHRED, BATCH_SHRED_DURATION_NANOS ) ) );
    1504           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->metrics->add_shred_timing,     FD_MHIST_EDGES_NS( SHRED, ADD_SHRED_DURATION_NANOS ) ) );
    1505           0 :   fd_histf_join( fd_metrics_histf_new_ns( ctx->metrics->fec_fallback_write_timing, FD_MHIST_EDGES_NS( SHRED, STORE_FEC_SYNC_SPILL_DURATION_NANOS ) ) );
    1506           0 :   memset( ctx->metrics->shred_processing_result, '\0', sizeof(ctx->metrics->shred_processing_result) );
    1507           0 :   ctx->metrics->invalid_block_id_cnt         = 0UL;
    1508           0 :   ctx->metrics->shred_rejected_unchained_cnt = 0UL;
    1509           0 :   ctx->metrics->repair_rcv_cnt               = 0UL;
    1510           0 :   ctx->metrics->repair_rcv_bytes             = 0UL;
    1511           0 :   ctx->metrics->turbine_rcv_cnt              = 0UL;
    1512           0 :   ctx->metrics->turbine_rcv_bytes            = 0UL;
    1513           0 :   ctx->metrics->bad_nonce                    = 0UL;
    1514           0 :   ctx->metrics->fec_fallback_write_cnt       = 0UL;
    1515           0 :   ctx->metrics->fec_fallback_write_bytes     = 0UL;
    1516             : 
    1517           0 :   ctx->pending_batch.microblock_cnt = 0UL;
    1518           0 :   ctx->pending_batch.pos            = 0UL;
    1519           0 :   ctx->pending_batch.slot           = 0UL;
    1520           0 :   memset( ctx->pending_batch.payload, 0, sizeof(ctx->pending_batch.payload) );
    1521             : 
    1522           0 :   memset( ctx->epoch_schedule, 0, sizeof(ctx->epoch_schedule) );
    1523           0 :   for( ulong i=0UL; i<FD_SHRED_FEATURES_ACTIVATION_SLOT_CNT; i++ ) {
    1524           0 :     ctx->features_activation->slots[i] = FD_SHRED_FEATURES_ACTIVATION_SLOT_DISABLED;
    1525           0 :   }
    1526           0 :   ctx->prev_max_shred_idx               = ctx->shred_limit;
    1527           0 :   ctx->current_max_shred_idx            = ctx->shred_limit;
    1528           0 :   ctx->next_max_shred_idx               = ctx->shred_limit;
    1529           0 :   ctx->current_max_shred_idx_start_slot = 0UL;
    1530           0 :   ctx->next_max_shred_idx_start_slot    = ULONG_MAX;
    1531             : 
    1532           0 :   ulong scratch_top = FD_SCRATCH_ALLOC_FINI( l, scratch_align() );
    1533           0 :   if( FD_UNLIKELY( scratch_top > (ulong)scratch + scratch_footprint( tile ) ) )
    1534           0 :     FD_LOG_ERR(( "scratch overflow %lu %lu %lu", scratch_top - (ulong)scratch - scratch_footprint( tile ), scratch_top, (ulong)scratch + scratch_footprint( tile ) ));
    1535             : 
    1536           0 :   memset( ctx->block_ids, 0, sizeof(ctx->block_ids) );
    1537           0 : }
    1538             : 
    1539             : static ulong
    1540             : populate_allowed_seccomp( fd_topo_t const *      topo,
    1541             :                           fd_topo_tile_t const * tile,
    1542             :                           ulong                  out_cnt,
    1543           0 :                           struct sock_filter *   out ) {
    1544           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1545           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1546           0 :   fd_shred_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_shred_ctx_t ), sizeof( fd_shred_ctx_t ) );
    1547             : 
    1548           0 :   populate_sock_filter_policy_fd_shred_tile( out_cnt, out, (uint)fd_log_private_logfile_fd(), (uint)ctx->disk_fd );
    1549           0 :   return sock_filter_policy_fd_shred_tile_instr_cnt;
    1550           0 : }
    1551             : 
    1552             : static ulong
    1553             : populate_allowed_fds( fd_topo_t const *      topo,
    1554             :                       fd_topo_tile_t const * tile,
    1555             :                       ulong                  out_fds_cnt,
    1556           0 :                       int *                  out_fds ) {
    1557           0 :   void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
    1558           0 :   FD_SCRATCH_ALLOC_INIT( l, scratch );
    1559           0 :   fd_shred_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_shred_ctx_t ), sizeof( fd_shred_ctx_t ) );
    1560             : 
    1561           0 :   if( FD_UNLIKELY( out_fds_cnt<3UL ) ) FD_LOG_ERR(( "out_fds_cnt %lu", out_fds_cnt ));
    1562             : 
    1563           0 :   ulong out_cnt = 0UL;
    1564           0 :   out_fds[ out_cnt++ ] = 2; /* stderr */
    1565           0 :   if( FD_LIKELY( -1!=fd_log_private_logfile_fd() ) )
    1566           0 :     out_fds[ out_cnt++ ] = fd_log_private_logfile_fd(); /* logfile */
    1567           0 :   if( FD_LIKELY( ctx->disk_fd>=0 ) )
    1568           0 :     out_fds[ out_cnt++ ] = ctx->disk_fd;
    1569           0 :   return out_cnt;
    1570           0 : }
    1571             : 
    1572             : /* One stem iteration finishes at most one FEC set on shred_out: 32
    1573             :    data shreds and a completion, after at most an eviction and a shred
    1574             :    on the network path.  PoH input only publishes sign requests, at
    1575             :    most one per FEC set of a batch. */
    1576           0 : #define STEM_BURST FD_SHRED_STEM_BURST
    1577             : 
    1578             : /* See explanation in fd_pack */
    1579           0 : #define STEM_LAZY  (128L*3000L)
    1580             : 
    1581             : /* When leader, poh_shred carries a stream of one microblock per frag
    1582             :    and the other links are near empty; keep draining it. */
    1583           0 : #define STEM_STICKY_POLL_MAX (16UL)
    1584             : 
    1585           0 : #define STEM_CALLBACK_CONTEXT_TYPE  fd_shred_ctx_t
    1586           0 : #define STEM_CALLBACK_CONTEXT_ALIGN alignof(fd_shred_ctx_t)
    1587             : 
    1588           0 : #define STEM_CALLBACK_DURING_HOUSEKEEPING during_housekeeping
    1589           0 : #define STEM_CALLBACK_METRICS_WRITE       metrics_write
    1590           0 : #define STEM_CALLBACK_BEFORE_FRAG         before_frag
    1591           0 : #define STEM_CALLBACK_DURING_FRAG         during_frag
    1592           0 : #define STEM_CALLBACK_AFTER_FRAG          after_frag
    1593             : 
    1594             : #include "../stem/fd_stem.c"
    1595             : 
    1596             : fd_topo_run_tile_t fd_tile_shred = {
    1597             :   .name                     = "shred",
    1598             :   .populate_allowed_seccomp = populate_allowed_seccomp,
    1599             :   .populate_allowed_fds     = populate_allowed_fds,
    1600             :   .scratch_align            = scratch_align,
    1601             :   .scratch_footprint        = scratch_footprint,
    1602             :   .privileged_init          = privileged_init,
    1603             :   .unprivileged_init        = unprivileged_init,
    1604             :   .run                      = stem_run,
    1605             : };

Generated by: LCOV version 1.14