LCOV - code coverage report
Current view: top level - disco/shred - fd_fec_resolver.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 557 641 86.9 %
Date: 2026-12-02 04:32:07 Functions: 10 13 76.9 %

          Line data    Source code
       1             : #include "../../ballet/shred/fd_shred.h"
       2             : #include "fd_fec_set.h"
       3             : #include "../../ballet/sha256/fd_sha256.h"
       4             : #include "../../ballet/ed25519/fd_ed25519_verifier.h"
       5             : #include "../../ballet/reedsol/fd_reedsol.h"
       6             : #include "../metrics/fd_metrics.h"
       7             : #include "fd_fec_resolver.h"
       8             : #include "fd_fec_samp.h"
       9             : #if FD_HAS_AVX512
      10             : #include "../../util/simd/fd_avx512.h"
      11             : #include <stddef.h>
      12             : #endif
      13             : 
      14             : 
      15             : typedef struct __attribute__((packed)) {
      16             :   ulong slot;
      17             :   uint fec_idx;
      18             : } slot_fec_pair_t;
      19             : 
      20             : struct __attribute__((aligned(32UL))) set_ctx {
      21             :   /* The Merkle root.  This is the only unique unforgeable identifier of
      22             :      the FEC set. */
      23             :   fd_bmtree_node_t      root;
      24             : 
      25             :   /* The leader's signature of the root of the Merkle tree of the shreds
      26             :      in this FEC set.  If the leader has sent multiple signatures, this
      27             :      is the first valid one we received. */
      28             :   fd_ed25519_sig_t         sig;
      29             : 
      30             :   union {
      31             :     /* When allocated, it's in a map_chain by the root and a treap
      32             :        by (shred, FEC set idx).  When it's not allocated, it is either
      33             :        in the free list or the completed list.  Both of those slists use
      34             :        free_next. */
      35             :     struct {
      36             :       uint              map_next;
      37             :       uint              map_prev;
      38             :       uint              treap_parent;
      39             :       uint              treap_left;
      40             :       uint              treap_right;
      41             :       uint              treap_prio;
      42             :     };
      43             :     struct {
      44             :       uint              free_next;
      45             :     };
      46             :   };
      47             : 
      48             :   ulong                 slot;
      49             :   uint                  fec_set_idx;
      50             : 
      51             :   uchar                 data_variant;
      52             :   uchar                 parity_variant;
      53             : 
      54             :   /* equivoc is set to 1 if at any moment there is a context in the
      55             :      map/treap with the same (slot, fec_set_idx) as this one */
      56             :   uchar                 equivoc;
      57             : 
      58             :   ulong                 total_rx_shred_cnt;
      59             : 
      60             :   fd_fec_set_t *        set;
      61             : 
      62             :   union {
      63             :     fd_bmtree_commit_t  tree[1];
      64             :     uchar               _footprint[ FD_BMTREE_COMMIT_FOOTPRINT( FD_SHRED_MERKLE_LAYER_CNT ) ] __attribute__((aligned(FD_BMTREE_COMMIT_ALIGN)));
      65             :   };
      66             : };
      67             : typedef struct set_ctx set_ctx_t;
      68             : 
      69             : #define MAP_NAME              ctx_map
      70         624 : #define MAP_KEY               root
      71             : #define MAP_KEY_T             fd_bmtree_node_t
      72         462 : #define MAP_IDX_T             uint
      73         753 : #define MAP_NEXT              map_next
      74         501 : #define MAP_PREV              map_prev
      75         321 : #define MAP_ELE_T             set_ctx_t
      76          63 : #define MAP_KEY_EQ(k0,k1)    (!memcmp( (k0)->hash, (k1)->hash, 32UL ))
      77         672 : #define MAP_KEY_HASH(key,s)  (fd_hash( s, key->hash, 32UL ))
      78             : #define MAP_OPTIMIZE_RANDOM_ACCESS_REMOVAL 1
      79             : #include "../../util/tmpl/fd_map_chain.c"
      80             : 
      81             : 
      82             : #define SLIST_NAME  ctx_list
      83             : #define SLIST_ELE_T set_ctx_t
      84         606 : #define SLIST_IDX_T uint
      85        1338 : #define SLIST_NEXT  free_next
      86             : #include "../../util/tmpl/fd_slist.c"
      87             : 
      88             : 
      89             : static inline int
      90             : slot_fec_pair_compare( slot_fec_pair_t const * q,
      91       10167 :                        set_ctx_t       const * e ) {
      92             :   /* It seems like
      93             :      return (int)( q->slot!=e->slot ?
      94             :                    q->slot    - e->slot :
      95             :                    q->fec_idx - e->fec_set_idx );
      96             :      should work, but I am concerned about overflow since this is all
      97             :      attacker controlled input. */
      98       10167 :   if( FD_LIKELY( q->slot   !=e->slot        ) ) return fd_int_if( q->slot   <e->slot,        -1, 1 );
      99       10122 :   if( FD_LIKELY( q->fec_idx!=e->fec_set_idx ) ) return fd_int_if( q->fec_idx<e->fec_set_idx, -1, 1 );
     100        9249 :   return 0;
     101       10122 : }
     102             : 
     103             : #define TREAP_NAME       ctx_treap
     104             : #define TREAP_T          set_ctx_t
     105        1392 : #define TREAP_IDX_T      uint
     106         753 : #define TREAP_PARENT     treap_parent
     107       10854 : #define TREAP_LEFT       treap_left
     108       10875 : #define TREAP_RIGHT      treap_right
     109         567 : #define TREAP_PRIO       treap_prio
     110          75 : #define TREAP_LT(e0,e1)  (((e0)->slot < (e1)->slot) | ( ((e0)->slot==(e1)->slot) & ((e0)->fec_set_idx < (e1)->fec_set_idx)))
     111             : #define TREAP_QUERY_T    slot_fec_pair_t const *
     112       10167 : #define TREAP_CMP(q,e)   slot_fec_pair_compare( (q), (e) )
     113             : #include "../../util/tmpl/fd_treap.c"
     114             : 
     115             : 
     116             : 
     117             : /* Once we're done with a FEC set, it goes into a map_chain and heap,
     118             :    both keyed by (slot, FEC set idx). */
     119             : 
     120             : struct done_ele {
     121             :   slot_fec_pair_t key;
     122             :   uint            heap_left; /* also used by pool when not allocated */
     123             :   uint            heap_right;
     124             :   uint            map_next;
     125             :   uint            map_prev;
     126             :   /* Ideally here we'd store the Merkle root of the one we completed,
     127             :      but there are two problems with that.  First of all, the shreds
     128             :      don't contain the Merkle root, which means we have to derive it
     129             :      with a bunch of mildly expensive hashing (about 1us per shred).
     130             :      Second of all, the Merkle root is relatively large (32 bytes).
     131             : 
     132             :      Thankfully, we have a key advantage that we can leverage.
     133             :      Equivocation detection can be probabilistic.  It's not that big of
     134             :      a deal to reject a shred with IGNORED instead of EQUIVOC as long as
     135             :      some firedancer node picks up that it is equivoc and produces the
     136             :      proof.  This suggests some kind of validator-specific sampling
     137             :      solution.  The code is factored nicely to be able to iterate on the
     138             :      sampling in the future. */
     139             :   fd_fec_samp_t   fec_sample[1];
     140             :   /* Low 56 bits of fd_tickcount() at which this FEC set completed.
     141             :      Elapsed ticks are computed modulo 2^56, retaining full tick
     142             :      precision for intervals shorter than 2^56 ticks (about 278 days at
     143             :      3 GHz). */
     144             :   ulong complete_ts : 56;
     145             :   uchar post_done_turbine_rem; /* decremented after done, but initally set to the number of repair shreds that
     146             :                                   contributed to the FEC set. We receive up to 32 unique repair shreds per FEC,
     147             :                                   so this number begins maximum at 32.  We decrement this as we receive turbine
     148             :                                   shreds post-completion, and by proxy measure how eagerly we repaired for
     149             :                                   this FEC set. */
     150             : };
     151             : typedef struct done_ele done_ele_t;
     152             : FD_STATIC_ASSERT( sizeof(done_ele_t)==40UL, done_ele_t );
     153             : #define SIG_HASH_EQUIVOC UINT_MAX
     154             : 
     155             : #define MAP_NAME              done_map
     156         360 : #define MAP_KEY               key
     157             : #define MAP_KEY_T             slot_fec_pair_t
     158       21105 : #define MAP_IDX_T             uint
     159       10077 : #define MAP_NEXT              map_next
     160         717 : #define MAP_PREV              map_prev
     161         141 : #define MAP_ELE_T             done_ele_t
     162        9936 : #define MAP_KEY_EQ(k0,k1)     ( ((k0)->slot==(k1)->slot) & ((k0)->fec_idx==(k1)->fec_idx) )
     163       10755 : #define MAP_KEY_HASH(key,s)  ((fd_ulong_hash( (key)->slot ^ (s) ) ^ fd_uint_hash( (key)->fec_idx ^ (uint)(s>>19) )))
     164             : #define MAP_OPTIMIZE_RANDOM_ACCESS_REMOVAL 1
     165             : #include "../../util/tmpl/fd_map_chain.c"
     166             : 
     167             : #define HEAP_NAME             done_heap
     168         420 : #define HEAP_IDX_T            uint
     169        1017 : #define HEAP_LEFT             heap_left
     170        1017 : #define HEAP_RIGHT            heap_right
     171             : #define HEAP_T                done_ele_t
     172         579 : #define HEAP_LT(e0,e1)       (((e0)->key.slot < (e1)->key.slot) | \
     173         579 :                             ( ((e0)->key.slot==(e1)->key.slot) & ((e0)->key.fec_idx < (e1)->key.fec_idx)))
     174             : #include "../../util/tmpl/fd_heap.c"
     175             : 
     176             : #define POOL_NAME             done_pool
     177          96 : #define POOL_T                done_ele_t
     178             : #define POOL_IDX_T            uint
     179         717 : #define POOL_NEXT             heap_left
     180             : #include "../../util/tmpl/fd_pool.c"
     181             : 
     182             : struct __attribute__((aligned(FD_FEC_RESOLVER_ALIGN))) fd_fec_resolver {
     183             :   /* depth stores the number of FEC sets this resolver can track
     184             :      simultaneously.  done_depth stores the depth of the done tcache,
     185             :      i.e. the number of done FEC set keys that this resolver remembers.
     186             :      partial_depth stores the minimum size of the free FEC set list.
     187             :      completed_depth stores the size of the completed FEC set list. */
     188             :   ulong depth;
     189             :   ulong partial_depth;
     190             :   ulong complete_depth;
     191             :   ulong done_depth;
     192             : 
     193             :   /* upper bound on the slot range above the root slot */
     194             :   ulong slot_max;
     195             : 
     196             :   /* expected_shred_version: discard all shreds with a shred version
     197             :      other than the specified value */
     198             :   ushort expected_shred_version;
     199             : 
     200             :   /* Test/fuzz mode: bypass Merkle+Ed25519 verification in add_shred. */
     201             :   uchar  bypass_verify;
     202             : 
     203             :   /* ctx_pool: A flat array (not an fd_pool) of the set_ctx_t
     204             :      structures used to back ctx_map, ctx_treap, and the ctx
     205             :      freelists. */
     206             :   set_ctx_t * ctx_pool;
     207             : 
     208             :   /* ctx_map: A map (using fd_map_chain) from Merkle roots to
     209             :      the context object with its relevant data for in progress FEC sets.
     210             :      This map contains at most `depth` elements at any time. */
     211             :   ctx_map_t * ctx_map;
     212             : 
     213             :   /* ctx_treap: A treap (using fd_treap) of the context objects for in
     214             :      progress FEC sets.  They are sorted by (slot, FEC index) from
     215             :      smallest to largest.  In the case of equivocation, multiple
     216             :      elements with the same key may be present, with no particular
     217             :      ordering between them. */
     218             :   ctx_treap_t ctx_treap[1];
     219             : 
     220             :   /* free_list and complete_list are slists (using fd_slist)
     221             :      of FEC set contexts that are not in ctx_map.  See the long comment
     222             :      in the header for why there are two.  In order to satisfy the
     223             :      invariants, technically we only need to store the FEC set memory,
     224             :      not the full context, but it's not that big of a difference
     225             :      (especially if partial_depth and complete_depth are small), and it
     226             :      simplifies memory management.
     227             : 
     228             :      Invariant: at every entry and exit to fd_fec_resolver_add_shred:
     229             :      - free_list has between partial_depth and partial_depth+depth
     230             :        elements.
     231             :      - complete_list has complete_depth elements
     232             :        (all these counts are inclusive). */
     233             :   ctx_list_t  free_list[1];
     234             :   ctx_list_t  complete_list[1];
     235             : 
     236             :   /* free_list_cnt: The number of items in free_list. */
     237             :   ulong free_list_cnt;
     238             : 
     239             :   /* completion_lag_hist: histogram of how much earlier repair made a
     240             :      FEC set complete.  Completion needs any FD_FEC_SHRED_CNT shreds, so
     241             :      a set that completed with R repair shreds would have needed R more
     242             :      turbine arrivals to get there on turbine alone.
     243             : 
     244             :      Best effort approximation.  It counts turbine *arrivals*, not
     245             :      distinct shred indices -- the per-set bitmaps are released at
     246             :      completion. */
     247             :   fd_histf_t completion_lag_hist[1];
     248             : 
     249             :   /* done_pool: A pool (this time using fd_pool) of the done_ele_t
     250             :      elements that back done_map and done_heap.  Invariant: each element
     251             :      is either (i) released and in the pool, or (ii) in both the
     252             :      done_map and done_heap. */
     253             :   done_ele_t * done_pool;
     254             : 
     255             :   /* done_map: A map (using fd_map_chain) mapping (slot, fec_idx) to an
     256             :      element of done_pool.  Even in the presence of equivocation, a
     257             :      specific (slot, fec_idx) tuple occurs at most once in the map,
     258             :      and the FEC sample is likely set to force_match.  In the presence
     259             :      of equivocation, the right shreds are probably being delivered
     260             :      using repair, which will bypass reading the done_map, so it doesn't
     261             :      really matter. */
     262             :   done_map_t * done_map;
     263             : 
     264             :   /* done_heap: A min heap (using fd_heap) based on (slot, fec_idx) used
     265             :      to stop tracking done elements older than slot_old, and for
     266             :      eviction in the unlikely case that we run out of elements in the
     267             :      done_map. */
     268             :   done_heap_t done_heap[1];
     269             : 
     270             :   /* slot_old: slot_old is the lowest slot for which shreds will be
     271             :      accepted.  That is any shred with slot<slot_old is rejected by
     272             :      add_shred with IGNORED.  slot_old can only increase. */
     273             :   ulong slot_old;
     274             : 
     275             :   /* seed: done_map uses seed to compute a hash of the FEC set */
     276             :   ulong seed;
     277             : 
     278             :   /* reedsol is used for calculations while adding a shred.  Its state
     279             :      outside a call to add_shred is indeterminate. */
     280             :   fd_reedsol_t  reedsol[1];
     281             : 
     282             :   /* verifier: verifies the FEC set signatures, with a small per leader
     283             :      pubkey cache.  A leader signs every set of its slots, so the few
     284             :      keys active at once repeat for hundreds of sets. */
     285             :   fd_ed25519_verifier_t * verifier;
     286             : 
     287             :   /* The footprint for the objects follows the struct and is in the same
     288             :      order as the pointers, namely:
     289             :        ctx_pool
     290             :        ctx_map
     291             :        done_pool
     292             :        done_map
     293             :        verifier */
     294             : };
     295             : 
     296             : #define ED25519_CACHE_ENT_CNT (16UL)
     297             : 
     298             : typedef struct fd_fec_resolver fd_fec_resolver_t;
     299             : 
     300             : FD_FN_PURE ulong
     301             : fd_fec_resolver_footprint( ulong depth,
     302             :                            ulong partial_depth,
     303             :                            ulong complete_depth,
     304           3 :                            ulong done_depth ) {
     305           3 :   if( FD_UNLIKELY( (depth==0UL) | (partial_depth==0UL) | (complete_depth==0UL) | (done_depth==0UL) ) ) return 0UL;
     306           3 :   if( FD_UNLIKELY( (depth>UINT_MAX) | (partial_depth>UINT_MAX) | (complete_depth>UINT_MAX)         ) ) return 0UL;
     307             : 
     308           3 :   ulong depth_sum = depth + partial_depth + complete_depth;
     309           3 :   if( FD_UNLIKELY( depth_sum>=UINT_MAX ) ) return 0UL;
     310             : 
     311           3 :   ulong ctx_chain_cnt  = ctx_map_chain_cnt_est ( depth      );
     312           3 :   ulong done_chain_cnt = done_map_chain_cnt_est( done_depth );
     313             : 
     314           3 :   ulong layout = FD_LAYOUT_INIT;
     315           3 :   layout = FD_LAYOUT_APPEND( layout, FD_FEC_RESOLVER_ALIGN,    sizeof(fd_fec_resolver_t)                           );
     316           3 :   layout = FD_LAYOUT_APPEND( layout, alignof(set_ctx_t),       sizeof(set_ctx_t)*depth_sum                         );
     317           3 :   layout = FD_LAYOUT_APPEND( layout, ctx_map_align(),          ctx_map_footprint  ( ctx_chain_cnt  )               );
     318           3 :   layout = FD_LAYOUT_APPEND( layout, done_pool_align(),        done_pool_footprint( done_depth     )               );
     319           3 :   layout = FD_LAYOUT_APPEND( layout, done_map_align(),         done_map_footprint ( done_chain_cnt )               );
     320           3 :   layout = FD_LAYOUT_APPEND( layout, fd_ed25519_verifier_align(), fd_ed25519_verifier_footprint( ED25519_CACHE_ENT_CNT ) );
     321             : 
     322           3 :   return FD_LAYOUT_FINI( layout, FD_FEC_RESOLVER_ALIGN );
     323           3 : }
     324             : 
     325           0 : FD_FN_CONST ulong fd_fec_resolver_align( void ) { return FD_FEC_RESOLVER_ALIGN; }
     326             : 
     327             : fd_histf_t const *
     328           0 : fd_fec_resolver_completion_lag_hist( fd_fec_resolver_t const * resolver ) {
     329           0 :   return resolver->completion_lag_hist;
     330           0 : }
     331             : 
     332             : 
     333             : void *
     334             : fd_fec_resolver_new( void                    * shmem,
     335             :                      ulong                     depth,
     336             :                      ulong                     partial_depth,
     337             :                      ulong                     complete_depth,
     338             :                      ulong                     done_depth,
     339             :                      ulong                     slot_max,
     340             :                      fd_fec_set_t            * sets,
     341          36 :                      ulong                     seed ) {
     342          36 :   if( FD_UNLIKELY( (depth==0UL) | (partial_depth==0UL) | (complete_depth==0UL) | (done_depth==0UL) ) ) return NULL;
     343          36 :   if( FD_UNLIKELY( (depth>UINT_MAX) | (partial_depth>UINT_MAX) | (complete_depth>UINT_MAX)         ) ) return NULL;
     344             : 
     345          36 :   ulong depth_sum = depth + partial_depth + complete_depth;
     346          36 :   if( FD_UNLIKELY( depth_sum>=UINT_MAX ) ) return NULL;
     347             : 
     348          36 :   ulong ctx_chain_cnt  = ctx_map_chain_cnt_est ( depth      );
     349          36 :   ulong done_chain_cnt = done_map_chain_cnt_est( done_depth );
     350             : 
     351             :                                                               /* round( 2^64 * ... */
     352          36 :   ulong seed0 = fd_ulong_hash( seed +  7640891576956012809UL );  /* sqrt(2)-1 */
     353          36 :   ulong seed1 = fd_ulong_hash( seed + 13503953896175478587UL );  /* sqrt(3)-1 */
     354          36 :   ulong seed2 = fd_ulong_hash( seed +  4354685564936845356UL );  /* sqrt(5)-2 */
     355          36 :   ulong seed3 = fd_ulong_hash( seed + 11912009170470909682UL );  /* sqrt(7)-2 */
     356          36 :   ulong seed4 = fd_ulong_hash( seed +  5883258537300569243UL );  /* sqrt(11)-3 */
     357             : 
     358          36 :   FD_SCRATCH_ALLOC_INIT( l, shmem );
     359          36 :   void * self        = FD_SCRATCH_ALLOC_APPEND( l, FD_FEC_RESOLVER_ALIGN,    sizeof(fd_fec_resolver_t)                           );
     360          36 :   void * _ctx_pool   = FD_SCRATCH_ALLOC_APPEND( l, alignof(set_ctx_t),       sizeof(set_ctx_t)*depth_sum                         );
     361          36 :   void * _ctx_map    = FD_SCRATCH_ALLOC_APPEND( l, ctx_map_align(),          ctx_map_footprint  ( ctx_chain_cnt  )               );
     362          36 :   void * _done_pool  = FD_SCRATCH_ALLOC_APPEND( l, done_pool_align(),        done_pool_footprint( done_depth     )               );
     363          36 :   void * _done_map   = FD_SCRATCH_ALLOC_APPEND( l, done_map_align(),         done_map_footprint ( done_chain_cnt )               );
     364          36 :   void * _verifier   = FD_SCRATCH_ALLOC_APPEND( l, fd_ed25519_verifier_align(), fd_ed25519_verifier_footprint( ED25519_CACHE_ENT_CNT ) );
     365          36 :   FD_SCRATCH_ALLOC_FINI( l, FD_FEC_RESOLVER_ALIGN );
     366             : 
     367          36 :   fd_fec_resolver_t * resolver = (fd_fec_resolver_t *)self;
     368          36 :   void * _ctx_treap     = resolver->ctx_treap;
     369          36 :   void * _free_list     = resolver->free_list;
     370          36 :   void * _complete_list = resolver->complete_list;
     371          36 :   void * _done_heap     = resolver->done_heap;
     372             : 
     373          36 :   if( FD_UNLIKELY( !ctx_map_new         ( _ctx_map, ctx_chain_cnt, seed0          ) ) ) { FD_LOG_WARNING(( "ctx_map_new fail"       )); return NULL; }
     374          36 :   if( FD_UNLIKELY( !ctx_treap_new       ( _ctx_treap, depth_sum                   ) ) ) { FD_LOG_WARNING(( "ctx_treap_new fail"     )); return NULL; }
     375          36 :   if( FD_UNLIKELY( !ctx_list_new        ( _free_list                              ) ) ) { FD_LOG_WARNING(( "ctx_list_new fail"      )); return NULL; }
     376          36 :   if( FD_UNLIKELY( !ctx_list_new        ( _complete_list                          ) ) ) { FD_LOG_WARNING(( "ctx_list_new fail"      )); return NULL; }
     377          36 :   if( FD_UNLIKELY( !done_pool_new       ( _done_pool, done_depth                  ) ) ) { FD_LOG_WARNING(( "done_pool_new fail"     )); return NULL; }
     378          36 :   if( FD_UNLIKELY( !done_map_new        ( _done_map, done_chain_cnt, seed1        ) ) ) { FD_LOG_WARNING(( "done_map_new fail"      )); return NULL; }
     379          36 :   if( FD_UNLIKELY( !done_heap_new       ( _done_heap, done_depth                  ) ) ) { FD_LOG_WARNING(( "done_heap_new fail"     )); return NULL; }
     380          36 :   if( FD_UNLIKELY( !fd_ed25519_verifier_new( _verifier, ED25519_CACHE_ENT_CNT, seed4 ) ) ) { FD_LOG_WARNING(( "ed25519_verifier_new fail" )); return NULL; }
     381             : 
     382          36 :   fd_histf_join( fd_metrics_histf_new_ns( resolver->completion_lag_hist, FD_MHIST_EDGES_NS( SHRED, REPAIR_LEAD_DELAY_NANOS ) ) );
     383             : 
     384          36 :   set_ctx_t * ctx_pool = (set_ctx_t *)_ctx_pool;
     385          36 :   fd_memset( ctx_pool, '\0', sizeof(set_ctx_t)*depth_sum );
     386         201 :   for( ulong i=0UL; i<depth_sum; i++ ) ctx_pool[i].set = sets + i;
     387          36 :   ctx_treap_seed( ctx_pool, depth_sum, seed2 );
     388             : 
     389             :   /* Initialize all the lists */
     390          36 :   ctx_list_t * free_list     = ctx_list_join( _free_list     );    FD_TEST( free_list    ==resolver->free_list     );
     391          36 :   ctx_list_t * complete_list = ctx_list_join( _complete_list );    FD_TEST( complete_list==resolver->complete_list );
     392             : 
     393         153 :   for( ulong i=0UL;                 i<depth+partial_depth; i++ ) { ctx_list_idx_push_tail( free_list,     i, ctx_pool ); }
     394          84 :   for( ulong i=depth+partial_depth; i<depth_sum;           i++ ) { ctx_list_idx_push_tail( complete_list, i, ctx_pool ); }
     395          36 :   ctx_list_leave( complete_list );
     396          36 :   ctx_list_leave( free_list     );
     397             : 
     398          36 :   resolver->depth                  = depth;
     399          36 :   resolver->partial_depth          = partial_depth;
     400          36 :   resolver->complete_depth         = complete_depth;
     401          36 :   resolver->done_depth             = done_depth;
     402          36 :   resolver->slot_max               = slot_max;
     403          36 :   resolver->expected_shred_version = 0;
     404          36 :   resolver->bypass_verify          = 0;
     405          36 :   resolver->free_list_cnt          = depth+partial_depth;
     406          36 :   resolver->slot_old               = 0UL;
     407          36 :   resolver->seed                   = seed3;
     408          36 :   return shmem;
     409          36 : }
     410             : 
     411             : fd_fec_resolver_t *
     412          36 : fd_fec_resolver_join( void * shmem ) {
     413          36 :   fd_fec_resolver_t * resolver = (fd_fec_resolver_t *)shmem;
     414          36 :   ulong depth          = resolver->depth;
     415          36 :   ulong partial_depth  = resolver->partial_depth;
     416          36 :   ulong complete_depth = resolver->complete_depth;
     417          36 :   ulong done_depth     = resolver->done_depth;
     418             : 
     419          36 :   ulong depth_sum = depth + partial_depth + complete_depth;
     420          36 :   if( FD_UNLIKELY( depth_sum>=UINT_MAX ) ) return NULL;
     421             : 
     422          36 :   ulong ctx_chain_cnt  = ctx_map_chain_cnt_est ( depth      );
     423          36 :   ulong done_chain_cnt = done_map_chain_cnt_est( done_depth );
     424             : 
     425          36 :   FD_SCRATCH_ALLOC_INIT( l, shmem );
     426          36 :   /*     self     */   FD_SCRATCH_ALLOC_APPEND( l, FD_FEC_RESOLVER_ALIGN,    sizeof(fd_fec_resolver_t)                           );
     427          36 :   void * _ctx_pool   = FD_SCRATCH_ALLOC_APPEND( l, alignof(set_ctx_t),       sizeof(set_ctx_t)*depth_sum                         );
     428          36 :   void * _ctx_map    = FD_SCRATCH_ALLOC_APPEND( l, ctx_map_align(),          ctx_map_footprint  ( ctx_chain_cnt  )               );
     429          36 :   void * _done_pool  = FD_SCRATCH_ALLOC_APPEND( l, done_pool_align(),        done_pool_footprint( done_depth     )               );
     430          36 :   void * _done_map   = FD_SCRATCH_ALLOC_APPEND( l, done_map_align(),         done_map_footprint ( done_chain_cnt )               );
     431          36 :   void * _verifier   = FD_SCRATCH_ALLOC_APPEND( l, fd_ed25519_verifier_align(), fd_ed25519_verifier_footprint( ED25519_CACHE_ENT_CNT ) );
     432          36 :   FD_SCRATCH_ALLOC_FINI( l, FD_FEC_RESOLVER_ALIGN );
     433             : 
     434          36 :   resolver->ctx_pool      = (set_ctx_t *)_ctx_pool;
     435          36 :   resolver->ctx_map       = ctx_map_join         ( _ctx_map   );  if( FD_UNLIKELY( !resolver->ctx_map       ) ) return NULL;
     436          36 :   resolver->done_pool     = done_pool_join       ( _done_pool );  if( FD_UNLIKELY( !resolver->done_pool     ) ) return NULL;
     437          36 :   resolver->done_map      = done_map_join        ( _done_map  );  if( FD_UNLIKELY( !resolver->done_map      ) ) return NULL;
     438          36 :   resolver->verifier      = fd_ed25519_verifier_join( _verifier );  if( FD_UNLIKELY( !resolver->verifier   ) ) return NULL;
     439          36 :   if( FD_UNLIKELY(      ctx_treap_join( resolver->ctx_treap     )!=      resolver->ctx_treap     ) ) return NULL;
     440          36 :   if( FD_UNLIKELY(      ctx_list_join ( resolver->free_list     )!=      resolver->free_list     ) ) return NULL;
     441          36 :   if( FD_UNLIKELY(      ctx_list_join ( resolver->complete_list )!=      resolver->complete_list ) ) return NULL;
     442          36 :   if( FD_UNLIKELY(      done_heap_join( resolver->done_heap     )!=      resolver->done_heap     ) ) return NULL;
     443             : 
     444          36 :   return resolver;
     445          36 : }
     446             : 
     447             : void
     448             : fd_fec_resolver_set_shred_version( fd_fec_resolver_t * resolver,
     449          36 :                                    ushort              expected_shred_version ) {
     450          36 :   resolver->expected_shred_version = expected_shred_version;
     451          36 : }
     452             : 
     453             : void
     454             : fd_fec_resolver_set_bypass_verify( fd_fec_resolver_t * resolver,
     455           0 :                                    int                 bypass_verify ) {
     456           0 :   resolver->bypass_verify = (uchar)!!bypass_verify;
     457           0 : }
     458             : 
     459             : void
     460             : fd_fec_resolver_advance_slot_old( fd_fec_resolver_t * resolver,
     461           6 :                                   ulong               slot_old ) {
     462           6 :   if( FD_UNLIKELY( slot_old <= resolver->slot_old ) ) return;
     463           6 :   resolver->slot_old = slot_old;
     464             : 
     465             :   /* Remove from done map */
     466           6 :   done_heap_t * done_heap = resolver->done_heap;
     467           6 :   done_map_t  * done_map  = resolver->done_map;
     468           6 :   done_ele_t  * done_pool = resolver->done_pool;
     469             : 
     470           9 :   while( done_heap_ele_cnt( done_heap ) ) {
     471           3 :     done_ele_t * min_ele = done_heap_ele_peek_min( done_heap, done_pool );
     472           3 :     if( FD_UNLIKELY( min_ele->key.slot>=slot_old ) ) break;
     473           3 :     done_map_ele_remove_fast( done_map,  min_ele, done_pool );
     474           3 :     done_heap_idx_remove_min( done_heap,          done_pool );
     475           3 :     done_pool_ele_release   ( done_pool, min_ele            );
     476           3 :   }
     477             : 
     478             :   /* Remove from in progress map */
     479           6 :   ctx_map_t   * ctx_map       = resolver->ctx_map;
     480           6 :   ctx_treap_t * ctx_treap     = resolver->ctx_treap;
     481           6 :   set_ctx_t   * ctx_pool      = resolver->ctx_pool;
     482           6 :   ctx_list_t  * free_list     = resolver->free_list;
     483             : 
     484           6 :   ctx_treap_fwd_iter_t next;
     485           9 :   for( ctx_treap_fwd_iter_t iter=ctx_treap_fwd_iter_init( ctx_treap, ctx_pool ); !ctx_treap_fwd_iter_done( iter ); iter=next ) {
     486           3 :     next = ctx_treap_fwd_iter_next( iter, ctx_pool );
     487           3 :     set_ctx_t * min_ele = ctx_treap_fwd_iter_ele( iter, ctx_pool );
     488           3 :     if( FD_UNLIKELY( min_ele->slot>=slot_old ) ) break;
     489             : 
     490           3 :     ctx_treap_ele_remove   ( ctx_treap, min_ele, ctx_pool );
     491           3 :     ctx_map_ele_remove_fast( ctx_map,   min_ele, ctx_pool );
     492           3 :     ctx_list_ele_push_head ( free_list, min_ele, ctx_pool );
     493           3 :     resolver->free_list_cnt++;
     494           3 :   }
     495           6 : }
     496             : 
     497             : static inline void
     498             : ensure_done_pool_free( done_ele_t  * done_pool,
     499             :                        done_heap_t * done_heap,
     500         279 :                        done_map_t  * done_map ) {
     501         279 :   if( FD_UNLIKELY( !done_pool_free( done_pool ) ) ) {
     502             :     /* Done map is full, so we'll forget about the oldest slot */
     503         138 :     ulong worst_idx = done_heap_idx_peek_min( done_heap );
     504         138 :     FD_TEST( worst_idx!=done_heap_idx_null() ); /* Done pool can't be empty and full at the same time */
     505         138 :     done_heap_idx_remove_min( done_heap,            done_pool );
     506         138 :     done_map_idx_remove_fast( done_map,  worst_idx, done_pool );
     507         138 :     done_pool_idx_release( done_pool, worst_idx );
     508             :     /* Now it's not empty */
     509         138 :   }
     510         279 : }
     511             : 
     512             : 
     513             : int
     514             : fd_fec_resolver_add_shred( fd_fec_resolver_t         * resolver,
     515             :                            fd_shred_t const          * shred,
     516             :                            ulong                       shred_sz,
     517             :                            ulong                       max_shred_idx,
     518             :                            uint                        source,
     519             :                            uchar const               * leader_pubkey,
     520             :                            fd_fec_set_t const      * * out_fec_set,
     521             :                            fd_shred_t const        * * out_shred,
     522             :                            fd_bmtree_node_t          * out_merkle_root,
     523       10581 :                            fd_fec_resolver_spilled_t * out_spilled      ) {
     524       10581 :   FD_TEST( source<=FD_FEC_RESOLVER_SHRED_SRC_BAD_REPAIR );
     525             : 
     526             :   /* Unpack variables */
     527       10581 :   ulong partial_depth = resolver->partial_depth;
     528             : 
     529       10581 :   ctx_list_t  * free_list     = resolver->free_list;
     530       10581 :   ctx_list_t  * complete_list = resolver->complete_list;
     531       10581 :   ctx_map_t   * ctx_map       = resolver->ctx_map;
     532       10581 :   ctx_treap_t * ctx_treap     = resolver->ctx_treap;
     533       10581 :   set_ctx_t   * ctx_pool      = resolver->ctx_pool;
     534       10581 :   done_map_t  * done_map      = resolver->done_map;
     535       10581 :   done_ele_t  * done_pool     = resolver->done_pool;
     536       10581 :   done_heap_t * done_heap     = resolver->done_heap;
     537             : 
     538       10581 :   fd_reedsol_t * reedsol       = resolver->reedsol;
     539             : 
     540             :   /* Invariants:
     541             :       * each set_ctx_t is in exactly one of ctx_map, freelist, or
     542             :         complete_list */
     543             : 
     544             :   /* Is this shred for a slot we've already rooted or otherwise don't
     545             :      care about? */
     546       10581 :   if( FD_UNLIKELY( shred->slot<resolver->slot_old ) ) return FD_FEC_RESOLVER_SHRED_IGNORED;
     547       10479 :   if( FD_UNLIKELY( resolver->slot_max && shred->slot>=resolver->slot_old+resolver->slot_max ) ) return FD_FEC_RESOLVER_SHRED_IGNORED;
     548             : 
     549             :   /* Do a bunch of quick validity checks */
     550       10479 :   if( FD_UNLIKELY( shred->version!=resolver->expected_shred_version  ) ) return FD_FEC_RESOLVER_SHRED_REJECTED;
     551       10452 :   if( FD_UNLIKELY( shred_sz<fd_shred_sz( shred )                     ) ) return FD_FEC_RESOLVER_SHRED_REJECTED;
     552       10452 :   if( FD_UNLIKELY( shred->idx>=max_shred_idx                         ) ) return FD_FEC_RESOLVER_SHRED_REJECTED;
     553       10452 :   if( FD_UNLIKELY( shred->fec_set_idx>max_shred_idx-FD_FEC_SHRED_CNT ) ) return FD_FEC_RESOLVER_SHRED_REJECTED;
     554       10452 :   if( FD_UNLIKELY( shred->idx-shred->fec_set_idx>=FD_FEC_SHRED_CNT   ) ) return FD_FEC_RESOLVER_SHRED_REJECTED;
     555       10452 :   if( FD_UNLIKELY( shred->fec_set_idx%FD_FEC_SHRED_CNT!=0UL          ) ) return FD_FEC_RESOLVER_SHRED_REJECTED;
     556             : 
     557       10359 :   uchar variant    = shred->variant;
     558       10359 :   uchar shred_type = fd_shred_type( variant );
     559             : 
     560       10359 :   int is_data_shred = fd_shred_is_data( shred_type );
     561             : 
     562       10359 :   if( !is_data_shred ) { /* Roughly 50/50 branch */
     563        5409 :     if( FD_UNLIKELY( (shred->code.data_cnt!=FD_FEC_SHRED_CNT) | (shred->code.code_cnt!=FD_FEC_SHRED_CNT) ) )
     564           3 :       return FD_FEC_RESOLVER_SHRED_REJECTED;
     565        5406 :     if( FD_UNLIKELY( shred->code.idx>=FD_FEC_SHRED_CNT            ) ) return FD_FEC_RESOLVER_SHRED_REJECTED;
     566        5406 :     if( FD_UNLIKELY( shred->code.idx!=shred->idx%FD_FEC_SHRED_CNT ) ) return FD_FEC_RESOLVER_SHRED_REJECTED;
     567             :     /* We want to ignore parity shreds corresponding to data shreds for
     568             :        which the parent slot is something we've already pruned (see
     569             :        below), but the parent offset is only a field in data shreds.  We
     570             :        could do it at reconstruction time, but then there's not a good
     571             :        return code.  It would be like a FEC_FATAL_REJECT, but returning
     572             :        IGNORED.  So instead we just snoop into the parity data and pick
     573             :        out the parent_off.  If all data shreds have the same value for
     574             :        parent_off, then all parity shreds will have that same value at
     575             :        the corresponding bytes.  If the data shreds have different
     576             :        values, this comparison is non-sensical, but we'll reject the FEC
     577             :        set later. */
     578        5406 :     ushort parent_off = FD_LOAD( ushort, fd_shred_code_payload( shred )+0x53UL-0x40UL );
     579        5406 :     if( FD_UNLIKELY( shred->slot-parent_off<resolver->slot_old ) ) return FD_FEC_RESOLVER_SHRED_IGNORED;
     580        5406 :   } else {
     581             :     /* if the shred's parent is for a slot we've already pruned, ignore it. */
     582        4950 :     if( FD_UNLIKELY( shred->slot-shred->data.parent_off<resolver->slot_old ) ) return FD_FEC_RESOLVER_SHRED_IGNORED;
     583             : 
     584             :     /* if it has slot complete, it must be the last one in the FEC. */
     585        4854 :     if( FD_UNLIKELY( (shred->data.flags & FD_SHRED_DATA_FLAG_SLOT_COMPLETE) && ((1UL+shred->idx) % FD_FEC_SHRED_CNT) ) ) {
     586           0 :       return FD_FEC_RESOLVER_SHRED_REJECTED;
     587           0 :     }
     588             : 
     589             :     /* if it has data complete, it must be the last data shred in the FEC set
     590             :        https://github.com/anza-xyz/agave/blob/v4.3.0-beta.0/ledger/src/shred/filter.rs#L346-L354 */
     591        4854 :     if( FD_UNLIKELY( ( shred->data.flags & FD_SHRED_DATA_FLAG_DATA_COMPLETE ) &&
     592        4854 :                      ( shred->idx != ( shred->fec_set_idx + ( FD_FEC_SHRED_CNT - 1UL ) ) ) ) ) {
     593           0 :       return FD_FEC_RESOLVER_SHRED_REJECTED;
     594           0 :     }
     595        4854 :   }
     596             : 
     597       10164 :   if( FD_UNLIKELY( !fd_shred_is_chained( shred_type ) ) ) {
     598             :     /* Reject any legacy and unchained shreds */
     599           0 :     return FD_FEC_RESOLVER_SHRED_REJECTED;
     600           0 :   }
     601             : 
     602             :   /* For the purposes of the shred header, tree_depth means the number
     603             :      of nodes, counting the leaf but excluding the root.  For bmtree,
     604             :      depth means the number of layers, which counts both. */
     605       10164 :   ulong tree_depth           = fd_shred_merkle_cnt( variant ); /* In [0, 15] */
     606             : 
     607             :   /* in_type_idx is between [0, code.data_cnt) or [0, code.code_cnt),
     608             :      where data_cnt <= FD_FEC_SHRED_CNT and code_cnt <= FD_FEC_SHRED_CNT
     609             :      On the other hand, shred_idx, goes from [0, code.data_cnt +
     610             :      code.code_cnt), with all the data shreds having
     611             :      shred_idx < code.data_cnt and all the parity shreds having
     612             :      shred_idx >= code.data_cnt. */
     613       10164 :   ulong in_type_idx = fd_ulong_if( is_data_shred, shred->idx - shred->fec_set_idx, shred->code.idx );
     614       10164 :   ulong shred_idx   = fd_ulong_if( is_data_shred, in_type_idx, in_type_idx + shred->code.data_cnt  );
     615             : 
     616       10164 :   if( FD_UNLIKELY( ( shred->fec_set_idx % FD_FEC_SHRED_CNT ) != 0UL ) ) return FD_FEC_RESOLVER_SHRED_REJECTED;
     617       10164 :   if( FD_UNLIKELY( in_type_idx >= FD_FEC_SHRED_CNT ) )                  return FD_FEC_RESOLVER_SHRED_REJECTED;
     618             : 
     619             :   /* This, combined with the check on shred->code.data_cnt implies that
     620             :      shred_idx is in [0, 2*FD_FEC_SHRED_CNT). */
     621             : 
     622       10164 :   if( FD_UNLIKELY( tree_depth!=FD_SHRED_MERKLE_LAYER_CNT-1UL ) ) return FD_FEC_RESOLVER_SHRED_REJECTED;
     623             : 
     624             :   /* Now we're done with all the simple, quick checks */
     625       10164 :   int is_repair = source==FD_FEC_RESOLVER_SHRED_SRC_REPAIR && is_data_shred;
     626             : 
     627       10164 :   set_ctx_t * ctx = NULL;
     628             : 
     629             :   /* If we detect a different Merkle root for the same (slot, FEC set
     630             :      idx), it means either the shred is invalid, or the leader is
     631             :      equivocating.  We can't tell which without verifying the shred
     632             :      though. */
     633       10164 :   int equivoc_or_invalid = 0;
     634             : 
     635       10164 :   slot_fec_pair_t const slot_fec_pair[1] = {{ .slot = shred->slot, .fec_idx = shred->fec_set_idx }};
     636             : 
     637             :   /* If it's from Turbine, we'll first check if we've already completed
     638             :      the FEC set (likely case) or another FEC set for the same (slot,
     639             :      FEC set idx) pair (unlikely case).  Either case will lead to
     640             :      rejecting the shred, but possibly later via the equivoc_or_invalid
     641             :      if we need to validate it. */
     642       10164 :   if( FD_LIKELY( !is_repair ) ) {
     643             :     /* Most likely, it's just done. */
     644       10116 :     done_ele_t * done_ele = done_map_ele_query( done_map, slot_fec_pair, NULL, done_pool );
     645       10116 :     if( FD_LIKELY( done_ele ) ) {
     646         552 :       if( FD_LIKELY( fd_fec_samp_matches( done_ele->fec_sample, resolver->seed, shred ) ) ) {
     647         552 :         if( FD_UNLIKELY( (source==FD_FEC_RESOLVER_SHRED_SRC_TURBINE) & (done_ele->post_done_turbine_rem>0L) ) ) {
     648             :           /* Turbine has now supplied as many shreds for this set as
     649             :              repair contributed, so this is approx. when the set would
     650             :              have completed on turbine alone. */
     651           0 :           done_ele->post_done_turbine_rem--;
     652           0 :           if( FD_UNLIKELY( done_ele->post_done_turbine_rem==0 ) ) {
     653           0 :             ulong lag = ((ulong)fd_tickcount() - (ulong)done_ele->complete_ts) & ((1UL<<56)-1UL);
     654           0 :             fd_histf_sample( resolver->completion_lag_hist, lag );
     655           0 :           }
     656           0 :         }
     657         552 :         return FD_FEC_RESOLVER_SHRED_IGNORED;
     658         552 :       }
     659             : 
     660           0 :       equivoc_or_invalid = 1;
     661           0 :     }
     662             :     /* There could be 0, 1, or >1 contexts in the treap with this (slot,
     663             :        FEC set index).  If there are >1, this sets ctx to an arbitrary
     664             :        one, which may or may not have the Merkle root that matches this
     665             :        shred.  Regardless, we'll reject it with equivoc_or_invalid. */
     666        9564 :     ctx = ctx_treap_ele_query( ctx_treap, slot_fec_pair, ctx_pool );
     667        9564 :     if( FD_LIKELY( ctx ) ) equivoc_or_invalid |= ctx->equivoc;
     668        9564 :   }
     669             : 
     670             : 
     671        9612 :   ulong reedsol_protected_sz = 1115UL + FD_SHRED_DATA_HEADER_SZ - FD_SHRED_SIGNATURE_SZ - FD_SHRED_MERKLE_NODE_SZ*tree_depth
     672        9612 :                                       - FD_SHRED_MERKLE_ROOT_SZ*fd_shred_is_chained ( shred_type )
     673        9612 :                                       - FD_SHRED_SIGNATURE_SZ  *fd_shred_is_resigned( shred_type); /* In [743, 1139] conservatively*/
     674        9612 :   ulong data_merkle_protected_sz   = reedsol_protected_sz + FD_SHRED_MERKLE_ROOT_SZ*fd_shred_is_chained( shred_type );
     675        9612 :   ulong parity_merkle_protected_sz = reedsol_protected_sz + FD_SHRED_MERKLE_ROOT_SZ*fd_shred_is_chained( shred_type )
     676        9612 :                                                           + FD_SHRED_CODE_HEADER_SZ - FD_ED25519_SIG_SZ;
     677        9612 :   ulong merkle_protected_sz  = fd_ulong_if( is_data_shred, data_merkle_protected_sz, parity_merkle_protected_sz );
     678             : 
     679        9612 :   fd_bmtree_node_t leaf[1];
     680             : 
     681        9612 :   fd_bmtree_hash_leaf( leaf, (uchar const *)shred + sizeof(fd_ed25519_sig_t), merkle_protected_sz, FD_BMTREE_LONG_PREFIX_SZ );
     682             : 
     683             : 
     684        9612 :   if( FD_UNLIKELY( is_repair ) ) {
     685             :     /* If it's coming from repair, we're willing to do the work to
     686             :        compute the Merkle root and lookup the ctx by Merkle root. */
     687          48 :     fd_bmtree_node_t _root[1];
     688          48 :     fd_bmtree_node_t * root = fd_bmtree_from_proof( leaf, shred_idx, _root, (uchar const *)fd_shred_merkle_nodes( shred ),
     689          48 :                                                     tree_depth, FD_SHRED_MERKLE_NODE_SZ, FD_BMTREE_LONG_PREFIX_SZ );
     690             : 
     691          48 :     ctx = ctx_map_ele_query( ctx_map, root, NULL, ctx_pool );
     692          48 :   }
     693             : 
     694        9612 :   if( FD_UNLIKELY( !ctx ) ) { /* This is the first shred in the FEC set */
     695             : 
     696         342 :     if( FD_UNLIKELY( resolver->free_list_cnt<=partial_depth ) ) {
     697             :       /* Packet loss is really high and we have a lot of in-progress FEC
     698             :          sets that we haven't been able to finish.  Evict the context
     699             :          with the highest (slot, FEC idx).  This is the one that is the
     700             :          farthest away from what we're currently replaying, which means
     701             :          we have the longest time to request it via repair if we
     702             :          actually need it.  This also handles the case where a leader
     703             :          sends some shreds from their slots that are far in the future
     704             :          in this epoch. */
     705          39 :       set_ctx_t * victim_ctx = ctx_treap_rev_iter_ele( ctx_treap_rev_iter_init( ctx_treap, ctx_pool ), ctx_pool );
     706             : 
     707          39 :       if( FD_LIKELY( out_spilled ) ) {
     708           6 :         out_spilled->slot         = victim_ctx->slot;
     709           6 :         out_spilled->fec_set_idx  = victim_ctx->fec_set_idx;
     710           6 :         *out_spilled->merkle_root = victim_ctx->root;
     711           6 :       }
     712             : 
     713             :       /* Remove from treap and map, then add to free_list */
     714          39 :       ctx_treap_ele_remove   ( ctx_treap, victim_ctx, ctx_pool );
     715          39 :       ctx_map_ele_remove_fast( ctx_map,   victim_ctx, ctx_pool );
     716             : 
     717          39 :       ctx_list_ele_push_tail ( free_list, victim_ctx, ctx_pool );
     718          39 :       resolver->free_list_cnt++;
     719             : 
     720          39 :       FD_MCNT_INC( SHRED, FEC_INCOMPLETE_EVICTED, 1UL );
     721          39 :     }
     722             :     /* Now we know |free_list|>partial_depth */
     723             : 
     724         342 :     ctx = ctx_list_ele_pop_head( free_list, ctx_pool );
     725         342 :     resolver->free_list_cnt--;
     726             : 
     727             :     /* Now we need to derive the root of the Merkle tree and verify the
     728             :        signature to prevent a DOS attack just by sending lots of invalid
     729             :        shreds.  If this shred came from repair, we're redoing
     730             :        computation, but the code is gross otherwise. */
     731         342 :     fd_bmtree_commit_t * tree;
     732         342 :     tree = fd_bmtree_commit_init( ctx->_footprint, FD_SHRED_MERKLE_NODE_SZ, FD_BMTREE_LONG_PREFIX_SZ, FD_SHRED_MERKLE_LAYER_CNT );
     733         342 :     FD_TEST( tree==ctx->tree );
     734             : 
     735         342 :     fd_bmtree_node_t _root[1] = {0};
     736             : 
     737         342 :     fd_shred_merkle_t const * proof = fd_shred_merkle_nodes( shred );
     738         342 :     int rv = fd_bmtree_commitp_insert_with_proof( tree, shred_idx, leaf, (uchar const *)proof, tree_depth, _root );
     739         342 :     if( FD_UNLIKELY( !rv ) ) {
     740           0 :       ctx_list_ele_push_head( free_list, ctx, ctx_pool );
     741           0 :       resolver->free_list_cnt++;
     742           0 :       FD_MCNT_INC( SHRED, INITIAL_REJECTED, 1UL );
     743           0 :       return FD_FEC_RESOLVER_SHRED_REJECTED;
     744           0 :     }
     745             : 
     746         342 :     if( FD_LIKELY( !resolver->bypass_verify ) ) {
     747         342 :       if( FD_UNLIKELY( FD_ED25519_SUCCESS != fd_ed25519_verifier_verify( resolver->verifier, _root->hash, 32UL, shred->signature, leader_pubkey ) ) ) {
     748          12 :         ctx_list_ele_push_head( free_list, ctx, ctx_pool );
     749          12 :         resolver->free_list_cnt++;
     750          12 :         FD_MCNT_INC( SHRED, INITIAL_REJECTED, 1UL );
     751          12 :         return FD_FEC_RESOLVER_SHRED_REJECTED;
     752          12 :       }
     753         342 :     }
     754             : 
     755             :     /* Copy the merkle root into the output arg. */
     756         330 :     if( FD_LIKELY( out_merkle_root ) ) memcpy( out_merkle_root, _root, sizeof(fd_bmtree_node_t) );
     757             : 
     758         330 :     if( FD_UNLIKELY( equivoc_or_invalid ) ) {
     759             :       /* It wasn't invalid, so it must be equivoc.  As a reminder, this
     760             :          is the case where is_repair==0, we had the (slot, FEC set idx)
     761             :          in the done_map, and this shred didn't match the FEC sample. */
     762           0 :       ctx_list_ele_push_head( free_list, ctx, ctx_pool );
     763           0 :       resolver->free_list_cnt++;
     764             :       /* We want to record that we've sigverified the shred somewhere so
     765             :          that if an attacker sends it to us again, we don't have to
     766             :          verify it again.  We do that by inserting it into the done_map
     767             :          with force_match. */
     768           0 :       done_ele_t * done = done_map_ele_query( done_map, slot_fec_pair, NULL, done_pool );
     769           0 :       if( FD_LIKELY( done ) ) fd_fec_samp_set_force_match( done->fec_sample );
     770           0 :       else {
     771             :         /* This case can't happen right now, but keep it in case some
     772             :            code gets added that could evict from the done_map between
     773             :            the !is_repair query and here. */
     774           0 :         ensure_done_pool_free( done_pool, done_heap, done_map );
     775             : 
     776           0 :         done = done_pool_ele_acquire( done_pool );
     777             : 
     778           0 :         done->key.slot              = shred->slot;
     779           0 :         done->key.fec_idx           = shred->fec_set_idx;
     780           0 :         done->complete_ts           = 0UL;
     781           0 :         done->post_done_turbine_rem = 0U;
     782           0 :         fd_fec_samp_set_force_match( done->fec_sample );
     783             : 
     784           0 :         done_heap_ele_insert( done_heap, done, done_pool );
     785           0 :         done_map_ele_insert ( done_map,  done, done_pool );
     786           0 :       }
     787             : 
     788           0 :       return FD_FEC_RESOLVER_SHRED_EQUIVOC;
     789           0 :     }
     790             :     /* Do we already have something in the treap for the same (slot, FEC
     791             :        idx) of this shred?  If so, mark this one and the old one as
     792             :        equivocating.  If we have multiple, marking the old one will be a
     793             :        no-op, which means we don't care which one query returns. */
     794         330 :     uchar equivoc = 0;
     795         330 :     set_ctx_t * equivoc_ctx = ctx_treap_ele_query( ctx_treap, slot_fec_pair, ctx_pool );
     796         330 :     if( FD_UNLIKELY( equivoc_ctx ) ) {
     797           6 :       equivoc_ctx->equivoc = 1;
     798           6 :       equivoc              = 1;
     799           6 :     }
     800             : 
     801             :     /* This seems like a legitimate FEC set, so we populate the rest of
     802             :        the fields, then add it to the map and treap. */
     803         330 :     memcpy( ctx->sig, shred->signature, 64UL );
     804         330 :     ctx->slot               = shred->slot;
     805         330 :     ctx->fec_set_idx        = shred->fec_set_idx;
     806         330 :     ctx->data_variant       = fd_uchar_if(  is_data_shred, variant, fd_shred_variant( fd_shred_swap_type( shred_type ), (uchar)tree_depth ) );
     807         330 :     ctx->parity_variant     = fd_uchar_if( !is_data_shred, variant, fd_shred_variant( fd_shred_swap_type( shred_type ), (uchar)tree_depth ) );
     808         330 :     ctx->equivoc            = equivoc;
     809         330 :     ctx->total_rx_shred_cnt = 0UL;
     810         330 :     ctx->root               = *_root;
     811             : 
     812             :     /* Reset the FEC set */
     813         330 :     ctx->set->data_shred_rcvd    = 0U;
     814         330 :     ctx->set->parity_shred_rcvd  = 0U;
     815         330 :     ctx->set->turbine_shred_rcvd = 0UL;
     816         330 :     ctx->set->repair_shred_rcvd  = 0UL;
     817             : 
     818         330 :     ctx_map_ele_insert  ( ctx_map,   ctx, ctx_pool );
     819         330 :     ctx_treap_ele_insert( ctx_treap, ctx, ctx_pool );
     820             : 
     821        9270 :   } else {
     822             :     /* This is not the first shred in the set */
     823             : 
     824             :     /* Verify that the shred's slot and fec_set_idx match the context
     825             :        established by the first shred. */
     826        9270 :     if( FD_UNLIKELY( shred->slot!=ctx->slot || shred->fec_set_idx!=ctx->fec_set_idx ) ) {
     827           0 :       return FD_FEC_RESOLVER_SHRED_REJECTED;
     828           0 :     }
     829             : 
     830             :     /* First ensure that all the shreds in the FEC set have consistent
     831             :        variants.  They all must have the same tree_depth and the same
     832             :        chained/not chained, resigned/not resigned bits. */
     833        9270 :     if( FD_UNLIKELY( variant!=fd_uchar_if( is_data_shred, ctx->data_variant, ctx->parity_variant ) ) ) {
     834           0 :       return FD_FEC_RESOLVER_SHRED_REJECTED;
     835           0 :     }
     836             : 
     837        9270 :     int matching_root = 1;
     838        9270 :     fd_bmtree_node_t _root[1];
     839        9270 :     int matching_sig  = fd_memeq( ctx->sig, shred->signature, 64UL );
     840        9270 :     if( FD_UNLIKELY( resolver->bypass_verify ) ) {
     841           0 :       *_root = ctx->root;
     842           0 :       matching_sig = 1;
     843        9270 :     } else {
     844        9270 :       fd_shred_merkle_t const * proof = fd_shred_merkle_nodes( shred );
     845        9270 :       int rv = fd_bmtree_commitp_insert_with_proof( ctx->tree, shred_idx, leaf, (uchar const *)proof, tree_depth, _root );
     846        9270 :       if( FD_UNLIKELY( !rv ) ) {
     847             :         /* This means we've gotten a shred with a different Merkle root
     848             :            than ctx.  This can only happen in the Turbine case, because
     849             :            otherwise ctx comes from the Merkle-root keyed map.  We need
     850             :            to check the signature before we know if it's EQUIVOC or
     851             :            REJECTED. */
     852           9 :         fd_bmtree_node_t * root = fd_bmtree_from_proof( leaf, shred_idx, _root, (uchar const *)fd_shred_merkle_nodes( shred ),
     853           9 :                                                         tree_depth, FD_SHRED_MERKLE_NODE_SZ, FD_BMTREE_LONG_PREFIX_SZ );
     854           9 :         (void)root; /* it has to be ==_root.  If it were going to fail,
     855             :                        it would have happened earlier. */
     856           9 :         matching_root = 0;
     857           9 :       }
     858        9270 :     }
     859             : 
     860        9270 :     if( FD_UNLIKELY( !(matching_root & matching_sig ) ) ) {
     861             :       /* There are a few things that could be going on here.
     862             :          1. A malicious validator could be producing an alternative
     863             :             signature for the same Merkle root
     864             :          2. A malicious validator could be equivocating (valid
     865             :             signature, different Merkle root)
     866             :          3. Someone could be sending us a shred from a FEC set the
     867             :             leader previously signed, but with a clobbered signature
     868             :          4. Someone could be sending us total junk.
     869             :          Note: if bypass_verify is true, this branch can't be taken. */
     870           9 :       if( FD_UNLIKELY( FD_ED25519_SUCCESS != fd_ed25519_verifier_verify( resolver->verifier, _root->hash, 32UL, shred->signature, leader_pubkey ) ) ) {
     871             :         /* Case 3 or 4, reject it */
     872           9 :         return FD_FEC_RESOLVER_SHRED_REJECTED;
     873           9 :       }
     874           9 :     }
     875             : 
     876        9261 :     if( FD_LIKELY( out_merkle_root ) ) *out_merkle_root = *_root;
     877             : 
     878        9261 :     if( FD_UNLIKELY( (!matching_root) | equivoc_or_invalid ) ) {
     879             :       /* Case 2, or other equivocation. Store it as equivocating and then reject it. */
     880           0 :       done_ele_t * done = done_map_ele_query( done_map, slot_fec_pair, NULL, done_pool );
     881           0 :       if( FD_LIKELY( done ) ) fd_fec_samp_set_force_match( done->fec_sample );
     882           0 :       else {
     883           0 :         ensure_done_pool_free( done_pool, done_heap, done_map );
     884             : 
     885           0 :         done = done_pool_ele_acquire( done_pool );
     886             : 
     887           0 :         done->key.slot              = shred->slot;
     888           0 :         done->key.fec_idx           = shred->fec_set_idx;
     889           0 :         done->complete_ts           = 0UL;
     890           0 :         done->post_done_turbine_rem = 0U;
     891           0 :         fd_fec_samp_set_force_match( done->fec_sample );
     892             : 
     893           0 :         done_heap_ele_insert( done_heap, done, done_pool );
     894           0 :         done_map_ele_insert ( done_map,  done, done_pool );
     895           0 :       }
     896           0 :       return FD_FEC_RESOLVER_SHRED_EQUIVOC;
     897           0 :     }
     898             :     /* Otherwise, this must be case 1, which is fine */
     899             : 
     900             :     /* Check to make sure this is not a duplicate */
     901             :     /* We need to make sure that if repair evicted this set and is
     902             :        re-repairing it, we aren't ignoring its shreds, which would keep
     903             :        the set from ever completing.  In the old days, we would return
     904             :        IGNORED earlier for non-repair shreds, but in order to determine
     905             :        if we already have the shred (and so should IGNORE it), we need
     906             :        to make sure we have the right ctx, and we don't have a way to
     907             :        map shred ctx precisely without deriving the Merkle root, so that
     908             :        doesn't make sense anymore. */
     909        9261 :     int shred_dup = !!(fd_uint_if( is_data_shred, ctx->set->data_shred_rcvd, ctx->set->parity_shred_rcvd ) & (1U << in_type_idx));
     910             : 
     911        9261 :     if( FD_UNLIKELY( shred_dup ) ) {
     912         252 :       *out_shred = is_data_shred ? ctx->set->data_shreds[ in_type_idx ].s : ctx->set->parity_shreds[ in_type_idx ].s;
     913         252 :       return fd_int_if( is_repair, FD_FEC_RESOLVER_SHRED_DUPLICATE, FD_FEC_RESOLVER_SHRED_IGNORED );
     914         252 :     }
     915        9261 :   }
     916             : 
     917             :   /* At this point, the shred has passed Merkle validation and is new.
     918             :      We also know that ctx is a pointer to the set_ctx_t where this
     919             :      shred belongs. */
     920             : 
     921             :   /* Copy the shred to memory the FEC resolver owns */
     922        9339 :   uchar * dst = is_data_shred ? ctx->set->data_shreds[ in_type_idx ].b : ctx->set->parity_shreds[ in_type_idx ].b;
     923        9339 :   fd_memcpy( dst, shred, fd_shred_sz( shred ) );
     924             : 
     925             :   /* Resigned shreds are relayed with a zero retransmitter signature:
     926             :      nothing verifies it (verify_retransmitter_signature never activated
     927             :      and is superseded by Alpenglow) */
     928        9339 :   if( FD_UNLIKELY( fd_shred_is_resigned( shred_type ) ) ) {
     929          96 :     memset( dst + fd_shred_retransmitter_sig_off( (fd_shred_t *)dst ), 0, 64UL );
     930          96 :   }
     931             : 
     932        9339 :   ctx->set->data_shred_rcvd   |= (uint)(!!is_data_shred)<<in_type_idx;
     933        9339 :   ctx->set->parity_shred_rcvd |= (uint)( !is_data_shred)<<in_type_idx;
     934        9339 :   ulong shred_bit = 1UL<<shred_idx;
     935        9339 :   if( source==FD_FEC_RESOLVER_SHRED_SRC_TURBINE ) ctx->set->turbine_shred_rcvd |= shred_bit;
     936         558 :   else                                            ctx->set->repair_shred_rcvd  |= shred_bit;
     937        9339 :   ctx->total_rx_shred_cnt++;
     938             : 
     939             :   /* Do we have enough to begin reconstruction? */
     940        9339 :   if( FD_LIKELY( ctx->total_rx_shred_cnt < FD_FEC_SHRED_CNT ) ) {
     941        9060 :     *out_shred = (fd_shred_t const *)dst;
     942        9060 :     return FD_FEC_RESOLVER_SHRED_OKAY;
     943        9060 :   }
     944             : 
     945             :   /* At this point, the FEC set is either valid or permanently invalid,
     946             :      so we can consider it done either way. */
     947             : 
     948         279 :   done_ele_t * done = NULL;
     949             : 
     950             :   /* If it's already in the done map, we don't need to re-insert it.
     951             :      It's not very clear what we should do if it's for a different FEC
     952             :      set, but this can only happen the second insert was a repair shred,
     953             :      and in that case, it gets bypassed anyway, so it doesn't really
     954             :      matter.  We'll just keep the existing value in that case. */
     955         279 :   slot_fec_pair_t done_key[1] = {{ .slot = ctx->slot, .fec_idx = ctx->fec_set_idx }};
     956         279 :   if( FD_LIKELY( !done_map_ele_query( done_map, done_key, NULL, done_pool ) ) ) {
     957         279 :     ensure_done_pool_free( done_pool, done_heap, done_map );
     958             : 
     959         279 :     done = done_pool_ele_acquire( done_pool );
     960             : 
     961         279 :     done->key.slot              = ctx->slot;
     962         279 :     done->key.fec_idx           = ctx->fec_set_idx;
     963         279 :     done->complete_ts           = (ulong)fd_tickcount() & ((1UL<<56)-1UL);
     964         279 :     done->post_done_turbine_rem = (uchar)fd_ulong_popcnt( ctx->set->repair_shred_rcvd );
     965             : 
     966         279 :     if( FD_LIKELY( !!ctx->set->repair_shred_rcvd ) ) {
     967          24 :       FD_MCNT_INC( SHRED, REPAIR_COMPLETION_ASSISTED, 1UL );
     968          24 :     }
     969             :     /* We need to finish the reedsol_recover and inserting all the
     970             :        missing shreds into the tree before we can properly
     971             :        derive this, so for now, we'll set it as force match.  If we hit
     972             :        one of the FEC_FATAL_REJECTED cases below, which is extremely
     973             :        rare, we'll end up rejecting all Turbine shreds for this (slot,
     974             :        FEC set idx).  That's not ideal, but the block is going to get
     975             :        skipped unless the leader equivocates. */
     976         279 :     fd_fec_samp_set_force_match( done->fec_sample );
     977             : 
     978         279 :     done_heap_ele_insert( done_heap, done, done_pool );
     979         279 :     done_map_ele_insert ( done_map,  done, done_pool );
     980         279 :   }
     981             : 
     982             : 
     983         279 :   ctx_map_ele_remove_fast( ctx_map,   ctx, ctx_pool );
     984         279 :   ctx_treap_ele_remove   ( ctx_treap, ctx, ctx_pool );
     985             :   /* At this point, ctx is not in any of the data structures, so we need
     986             :      to be sure to add it to one of the lists before exiting. */
     987             : 
     988         279 :   fd_fec_set_t       * set  = ctx->set;
     989         279 :   fd_bmtree_commit_t * tree = ctx->tree;
     990             : 
     991         279 :   reedsol = fd_reedsol_recover_init( (void*)reedsol, reedsol_protected_sz );
     992        9207 :   for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) {
     993        8928 :     uchar * rs_payload = set->data_shreds[ i ].b + sizeof(fd_ed25519_sig_t);
     994        8928 :     if( set->data_shred_rcvd&(1U<<i) ) fd_reedsol_recover_add_rcvd_shred  ( reedsol, 1, rs_payload );
     995        4575 :     else                               fd_reedsol_recover_add_erased_shred( reedsol, 1, rs_payload );
     996        8928 :   }
     997        9207 :   for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) {
     998        8928 :     uchar * rs_payload = set->parity_shreds[ i ].b + FD_SHRED_CODE_HEADER_SZ;
     999        8928 :     if( set->parity_shred_rcvd&(1U<<i) ) fd_reedsol_recover_add_rcvd_shred  ( reedsol, 0, rs_payload );
    1000        4353 :     else                                 fd_reedsol_recover_add_erased_shred( reedsol, 0, rs_payload );
    1001        8928 :   }
    1002             : 
    1003         279 :   if( FD_UNLIKELY( FD_REEDSOL_SUCCESS != fd_reedsol_recover_fini( reedsol ) ) ) {
    1004             :     /* Exactly FD_FEC_SHRED_CNT shreds are present.  Any such subset
    1005             :        defines a codeword, so recovery cannot detect an inconsistent
    1006             :        FEC set here.  A malicious leader's inconsistent shreds are caught
    1007             :        by checking the recovered shreds against the signed Merkle root
    1008             :        below. */
    1009           0 :     ctx_list_ele_push_tail( free_list, ctx, ctx_pool );
    1010           0 :     resolver->free_list_cnt++;
    1011           0 :     FD_MCNT_INC( SHRED, FEC_FATAL_REJECTED, 1UL );
    1012           0 :     return FD_FEC_RESOLVER_SHRED_REJECTED;
    1013           0 :   }
    1014             : 
    1015         279 :   uchar const * chained_root = fd_ptr_if( fd_shred_is_chained( shred_type ), (uchar *)shred+fd_shred_chain_off( variant ), NULL );
    1016             : 
    1017             :   /* Populate the recovered shreds' headers and hash their leaves in
    1018             :      sha256 batches.  As in the shredder, the leaf prefix sits in the
    1019             :      unwritten signature tail; the signature is copied in afterwards. */
    1020         279 :   ulong const prefix_off = sizeof(fd_ed25519_sig_t)-FD_BMTREE_LONG_PREFIX_SZ;
    1021         279 :   fd_bmtree_node_t leaves[ 2UL*FD_FEC_SHRED_CNT ];
    1022         279 :   uchar batch_mem[ FD_SHA256_BATCH_FOOTPRINT ] __attribute__((aligned(FD_SHA256_BATCH_ALIGN)));
    1023         279 :   fd_sha256_batch_t * batch = fd_sha256_batch_init( batch_mem );
    1024             : 
    1025        9207 :   for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) {
    1026        8928 :     if( !(set->data_shred_rcvd&(1U<<i)) ) {
    1027        4575 :       if( FD_LIKELY( fd_shred_is_chained( shred_type ) ) ) {
    1028        4575 :         fd_memcpy( set->data_shreds[i].b+fd_shred_chain_off( ctx->data_variant ), chained_root, FD_SHRED_MERKLE_ROOT_SZ );
    1029        4575 :       }
    1030        4575 :       if( FD_LIKELY( !resolver->bypass_verify ) ) {
    1031        4575 :         fd_memcpy( set->data_shreds[i].b+prefix_off, fd_bmtree_leaf_prefix, FD_BMTREE_LONG_PREFIX_SZ );
    1032        4575 :         fd_sha256_batch_add( batch, set->data_shreds[i].b+prefix_off, data_merkle_protected_sz+FD_BMTREE_LONG_PREFIX_SZ, leaves[ i ].hash );
    1033        4575 :       }
    1034        4575 :     }
    1035        8928 :   }
    1036             : 
    1037        9207 :   for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) {
    1038        8928 :     if( !(set->parity_shred_rcvd&(1U<<i)) ) {
    1039        4353 :       fd_shred_t * p_shred = set->parity_shreds[i].s; /* We can't parse because we haven't populated the header */
    1040        4353 :       p_shred->variant       = ctx->parity_variant;
    1041        4353 :       p_shred->slot          = shred->slot;
    1042        4353 :       p_shred->idx           = (uint)(i + ctx->fec_set_idx);
    1043        4353 :       p_shred->version       = shred->version;
    1044        4353 :       p_shred->fec_set_idx   = (uint)ctx->fec_set_idx;
    1045        4353 :       p_shred->code.data_cnt = (ushort)FD_FEC_SHRED_CNT;
    1046        4353 :       p_shred->code.code_cnt = (ushort)FD_FEC_SHRED_CNT;
    1047        4353 :       p_shred->code.idx      = (ushort)i;
    1048             : 
    1049        4353 :       if( FD_LIKELY( fd_shred_is_chained( shred_type ) ) ) {
    1050        4353 :         fd_memcpy( set->parity_shreds[i].b+fd_shred_chain_off( ctx->parity_variant ), chained_root, FD_SHRED_MERKLE_ROOT_SZ );
    1051        4353 :       }
    1052        4353 :       if( FD_LIKELY( !resolver->bypass_verify ) ) {
    1053        4353 :         fd_memcpy( set->parity_shreds[i].b+prefix_off, fd_bmtree_leaf_prefix, FD_BMTREE_LONG_PREFIX_SZ );
    1054        4353 :         fd_sha256_batch_add( batch, set->parity_shreds[i].b+prefix_off, parity_merkle_protected_sz+FD_BMTREE_LONG_PREFIX_SZ, leaves[ FD_FEC_SHRED_CNT+i ].hash );
    1055        4353 :       }
    1056        4353 :     }
    1057        8928 :   }
    1058         279 :   fd_sha256_batch_fini( batch );
    1059             : 
    1060             :   /* Copy the signatures in, then insert the leaves in the same order */
    1061        9207 :   for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) {
    1062        8928 :     if( !(set->data_shred_rcvd&(1U<<i)) ) {
    1063        4575 :       fd_memcpy( set->data_shreds[i].b, shred, sizeof(fd_ed25519_sig_t) );
    1064        4575 :       if( FD_LIKELY( !resolver->bypass_verify ) ) {
    1065        4575 :         if( FD_UNLIKELY( !fd_bmtree_commitp_insert_with_proof( tree, i, leaves+i, NULL, 0, NULL ) ) ) {
    1066           0 :           ctx_list_ele_push_tail( free_list, ctx, ctx_pool );
    1067           0 :           resolver->free_list_cnt++;
    1068           0 :           FD_MCNT_INC( SHRED, FEC_FATAL_REJECTED, 1UL );
    1069           0 :           return FD_FEC_RESOLVER_SHRED_REJECTED;
    1070           0 :         }
    1071        4575 :       }
    1072        4575 :     }
    1073        8928 :   }
    1074             : 
    1075        9207 :   for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) {
    1076        8928 :     if( !(set->parity_shred_rcvd&(1U<<i)) ) {
    1077        4353 :       fd_memcpy( set->parity_shreds[i].s->signature, shred->signature, sizeof(fd_ed25519_sig_t) );
    1078        4353 :       if( FD_LIKELY( !resolver->bypass_verify ) ) {
    1079        4353 :         if( FD_UNLIKELY( !fd_bmtree_commitp_insert_with_proof( tree, FD_FEC_SHRED_CNT + i, leaves+FD_FEC_SHRED_CNT+i, NULL, 0, NULL ) ) ) {
    1080           0 :           ctx_list_ele_push_tail( free_list, ctx, ctx_pool );
    1081           0 :           resolver->free_list_cnt++;
    1082           0 :           FD_MCNT_INC( SHRED, FEC_FATAL_REJECTED, 1UL );
    1083           0 :           return FD_FEC_RESOLVER_SHRED_REJECTED;
    1084           0 :         }
    1085        4353 :       }
    1086        4353 :     }
    1087        8928 :   }
    1088             : 
    1089             :   /* Check that the whole Merkle tree is consistent. */
    1090         279 :   if( FD_UNLIKELY( !resolver->bypass_verify && !fd_bmtree_commitp_fini( tree, FD_FEC_SHRED_CNT + FD_FEC_SHRED_CNT ) ) ) {
    1091           0 :     ctx_list_ele_push_tail( free_list, ctx, ctx_pool );
    1092           0 :     resolver->free_list_cnt++;
    1093           0 :     FD_MCNT_INC( SHRED, FEC_FATAL_REJECTED, 1UL );
    1094           0 :     return FD_FEC_RESOLVER_SHRED_REJECTED;
    1095           0 :   }
    1096             : 
    1097             :   /* We now have fully populated the bmtree, so we can derive the
    1098             :      fec_sample. */
    1099         279 :   if( FD_LIKELY( done && !resolver->bypass_verify ) ) fd_fec_samp_derive( done->fec_sample, resolver->seed, ctx->slot, ctx->fec_set_idx, ctx->sig, &ctx->root, tree );
    1100             : 
    1101             :   /* Check that all the fields that are supposed to be consistent across
    1102             :      an FEC set actually are. */
    1103         279 :   fd_shred_t const * base_data_shred   = fd_shred_parse( set->data_shreds  [ 0 ].b, FD_SHRED_MIN_SZ, max_shred_idx );
    1104         279 :   fd_shred_t const * base_parity_shred = fd_shred_parse( set->parity_shreds[ 0 ].b, FD_SHRED_MAX_SZ, max_shred_idx );
    1105         279 :   int reject = (!base_data_shred) | (!base_parity_shred);
    1106             : 
    1107             :   /* Check idx of base shreds */
    1108         279 :   reject = reject || ((base_data_shred->idx!=ctx->fec_set_idx) | (base_parity_shred->idx!=ctx->fec_set_idx) |
    1109         279 :                       (base_data_shred->data.flags & FD_SHRED_DATA_FLAG_DATA_COMPLETE));
    1110             : 
    1111        8928 :   for( ulong i=1UL; (!reject) & (i<FD_FEC_SHRED_CNT); i++ ) {
    1112             :     /* Technically, we only need to re-parse the ones we recovered with
    1113             :        Reedsol, but parsing is pretty cheap and the rest of the
    1114             :        validation we need to do on all of them. */
    1115        8649 :     fd_shred_t const * parsed = fd_shred_parse( set->data_shreds[ i ].b, FD_SHRED_MIN_SZ, max_shred_idx );
    1116        8649 :     if( FD_UNLIKELY( !parsed ) ) { reject = 1; break; }
    1117        8649 :     reject |= parsed->variant         != base_data_shred->variant;
    1118        8649 :     reject |= parsed->slot            != base_data_shred->slot;
    1119        8649 :     reject |= parsed->version         != base_data_shred->version;
    1120        8649 :     reject |= parsed->fec_set_idx     != base_data_shred->fec_set_idx;
    1121        8649 :     reject |= parsed->data.parent_off != base_data_shred->data.parent_off;
    1122        8649 :     reject |= parsed->idx             != (uint)(ctx->fec_set_idx+i);
    1123        8649 :     reject |= (i!=FD_FEC_SHRED_CNT-1UL) && (parsed->data.flags & FD_SHRED_DATA_FLAG_DATA_COMPLETE);
    1124             : 
    1125        8649 :     reject |= fd_shred_is_chained( fd_shred_type( parsed->variant ) ) &&
    1126        8649 :                 !fd_memeq( (uchar *)parsed         +fd_shred_chain_off( parsed->variant          ),
    1127        8649 :                            (uchar *)base_data_shred+fd_shred_chain_off( base_data_shred->variant ), FD_SHRED_MERKLE_ROOT_SZ );
    1128        8649 :   }
    1129             : 
    1130        9207 :   for( ulong i=0UL; (!reject) & (i<FD_FEC_SHRED_CNT); i++ ) {
    1131        8928 :     fd_shred_t const * parsed = fd_shred_parse( set->parity_shreds[ i ].b, FD_SHRED_MAX_SZ, max_shred_idx );
    1132        8928 :     if( FD_UNLIKELY( !parsed ) ) { reject = 1; break; }
    1133        8928 :     reject |= fd_shred_type( parsed->variant )       != fd_shred_swap_type( fd_shred_type( base_data_shred->variant ) );
    1134        8928 :     reject |= fd_shred_merkle_cnt( parsed->variant ) != fd_shred_merkle_cnt( base_data_shred->variant );
    1135        8928 :     reject |= parsed->slot                           != base_data_shred->slot;
    1136        8928 :     reject |= parsed->version                        != base_data_shred->version;
    1137        8928 :     reject |= parsed->fec_set_idx                    != base_data_shred->fec_set_idx;
    1138        8928 :     reject |= parsed->idx                            != (uint)(ctx->fec_set_idx+i);
    1139        8928 :     reject |= parsed->code.data_cnt                  != base_parity_shred->code.data_cnt;
    1140        8928 :     reject |= parsed->code.code_cnt                  != base_parity_shred->code.code_cnt;
    1141        8928 :     reject |= parsed->code.idx                       != (ushort)i;
    1142             : 
    1143        8928 :     reject |= fd_shred_is_chained( fd_shred_type( parsed->variant ) ) &&
    1144        8928 :                 !fd_memeq( (uchar *)parsed         +fd_shred_chain_off( parsed->variant          ),
    1145        8928 :                            (uchar *)base_data_shred+fd_shred_chain_off( base_data_shred->variant ), FD_SHRED_MERKLE_ROOT_SZ );
    1146        8928 :   }
    1147             : 
    1148             :   /* SIMD-0504: once a data shred is not filled to capacity, all
    1149             :      following data shreds must be empty and the last data shred must
    1150             :      have the batch complete flag.  A data shred's capacity ends where
    1151             :      its chained Merkle root begins.
    1152             :      https://github.com/anza-xyz/agave/blob/v4.5.0-rc.0/ledger/src/shred/merkle.rs#L720-L738 */
    1153         279 :   if( FD_LIKELY( !reject ) ) {
    1154         279 :     ulong full_sz = fd_shred_chain_off( ctx->data_variant );
    1155         279 :     int   partial;
    1156          93 : #if FD_HAS_AVX512
    1157             :     /* Gather the 32 size fields (one 32-bit load per shred, low 16 bits
    1158             :        are the size) into a bit mask of full shreds and a bit mask of
    1159             :        empty shreds. */
    1160          93 :     FD_STATIC_ASSERT( FD_FEC_SHRED_CNT==32UL, simd );
    1161          93 :     ulong const   stride = sizeof(set->data_shreds[ 0 ]);
    1162          93 :     uchar const * sz0    = set->data_shreds[ 0 ].b + offsetof( fd_shred_t, data.size );
    1163          93 :     wwu_t const   idx    = wwu_mul( wwu( 0U,1U,2U,3U,4U,5U,6U,7U,8U,9U,10U,11U,12U,13U,14U,15U ), wwu_bcast( stride ) );
    1164          93 :     wwu_t const   lo16   = wwu_bcast( 0xFFFFU );
    1165          93 :     wwu_t const   sz_a   = wwu_and( _mm512_i32gather_epi32( idx, sz0,             1 ), lo16 );
    1166          93 :     wwu_t const   sz_b   = wwu_and( _mm512_i32gather_epi32( idx, sz0+16UL*stride, 1 ), lo16 );
    1167          93 :     wwu_t const   full   = wwu_bcast( full_sz                 );
    1168          93 :     wwu_t const   empty  = wwu_bcast( FD_SHRED_DATA_HEADER_SZ );
    1169          93 :     uint full_m  = (uint)wwu_eq( sz_a, full  ) | ((uint)wwu_eq( sz_b, full  )<<16);
    1170          93 :     uint empty_m = (uint)wwu_eq( sz_a, empty ) | ((uint)wwu_eq( sz_b, empty )<<16);
    1171             :     /* after: shreds strictly after the first non-full one (0 if all are
    1172             :        full) */
    1173          93 :     uint not_full = ~full_m;
    1174          93 :     uint after    = ~(not_full ^ (not_full-1U));
    1175          93 :     partial  = not_full!=0U;
    1176          93 :     reject  |= (after & ~empty_m)!=0U;
    1177             : #else
    1178         186 :     partial = 0;
    1179        6138 :     for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) {
    1180        5952 :       ulong data_sz = set->data_shreds[ i ].s->data.size;
    1181        5952 :       reject  |= partial & (data_sz!=FD_SHRED_DATA_HEADER_SZ);
    1182        5952 :       partial |= data_sz!=full_sz;
    1183        5952 :     }
    1184         186 : #endif
    1185         279 :     reject |= partial & !(set->data_shreds[ FD_FEC_SHRED_CNT-1UL ].s->data.flags & FD_SHRED_DATA_FLAG_DATA_COMPLETE);
    1186         279 :   }
    1187             : 
    1188         279 :   if( FD_UNLIKELY( reject ) ) {
    1189          30 :     ctx_list_ele_push_tail( free_list, ctx, ctx_pool );
    1190          30 :     resolver->free_list_cnt++;
    1191          30 :     FD_MCNT_INC( SHRED, FEC_FATAL_REJECTED, 1UL );
    1192          30 :     return FD_FEC_RESOLVER_SHRED_REJECTED;
    1193          30 :   }
    1194             : 
    1195             : 
    1196             :   /* Populate missing Merkle proofs */
    1197        8217 :   for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++   ) if( !( set->data_shred_rcvd&(1U<<i) ) )
    1198        4095 :     fd_bmtree_get_proof( tree, set->data_shreds[i].b   + fd_shred_merkle_off( set->data_shreds[i].s   ), i );
    1199             : 
    1200        8217 :   for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) if( !( set->parity_shred_rcvd&(1U<<i) ) )
    1201        3873 :     fd_bmtree_get_proof( tree, set->parity_shreds[i].b + fd_shred_merkle_off( set->parity_shreds[i].s ), FD_FEC_SHRED_CNT+i );
    1202             : 
    1203             :   /* Zero retransmitter signature on the recovered shreds too */
    1204         249 :   if( FD_UNLIKELY( fd_shred_is_resigned( shred_type ) ) ) {
    1205          99 :     for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++   ) if( !( set->data_shred_rcvd&(1U<<i) ) )
    1206          42 :       memset( set->data_shreds[i].b   + fd_shred_retransmitter_sig_off( set->data_shreds[i].s   ), 0, 64UL );
    1207             : 
    1208          99 :     for( ulong i=0UL; i<FD_FEC_SHRED_CNT; i++ ) if( !( set->parity_shred_rcvd&(1U<<i) ) )
    1209          54 :       memset( set->parity_shreds[i].b + fd_shred_retransmitter_sig_off( set->parity_shreds[i].s ), 0, 64UL );
    1210           3 :   }
    1211             : 
    1212             :   /* Finally... A valid FEC set.  Forward it along. */
    1213         249 :   ctx_list_ele_push_tail( complete_list, ctx, ctx_pool );
    1214         249 :   ctx_list_idx_push_tail( free_list, ctx_list_idx_pop_head( complete_list, ctx_pool ), ctx_pool );
    1215         249 :   resolver->free_list_cnt++;
    1216             : 
    1217         249 :   *out_fec_set = set;
    1218         249 :   *out_shred   = (fd_shred_t const *)dst;
    1219             : 
    1220         249 :   return FD_FEC_RESOLVER_SHRED_COMPLETES;
    1221         279 : }
    1222             : 
    1223             : 
    1224          24 : void * fd_fec_resolver_leave( fd_fec_resolver_t * resolver ) {
    1225          24 :   fd_ed25519_verifier_leave( resolver->verifier );
    1226          24 :   done_heap_leave       ( resolver->done_heap     );
    1227          24 :   ctx_list_leave        ( resolver->complete_list );
    1228          24 :   ctx_list_leave        ( resolver->free_list     );
    1229          24 :   ctx_treap_leave       ( resolver->ctx_treap     );
    1230          24 :   done_map_leave        ( resolver->done_map      );
    1231          24 :   done_pool_leave       ( resolver->done_pool     );
    1232          24 :   ctx_map_leave         ( resolver->ctx_map       );
    1233             : 
    1234          24 :   return (void *)resolver;
    1235          24 : }
    1236             : 
    1237          24 : void * fd_fec_resolver_delete( void * shmem ) {
    1238          24 :   fd_fec_resolver_t * resolver = (fd_fec_resolver_t *)shmem;
    1239          24 :   ulong depth          = resolver->depth;
    1240          24 :   ulong partial_depth  = resolver->partial_depth;
    1241          24 :   ulong complete_depth = resolver->complete_depth;
    1242          24 :   ulong done_depth     = resolver->done_depth;
    1243             : 
    1244          24 :   ulong depth_sum      = depth + partial_depth + complete_depth;
    1245          24 :   ulong ctx_chain_cnt  = ctx_map_chain_cnt_est ( depth      );
    1246          24 :   ulong done_chain_cnt = done_map_chain_cnt_est( done_depth );
    1247             : 
    1248          24 :   FD_SCRATCH_ALLOC_INIT( l, shmem );
    1249          24 :   /*     self      */  FD_SCRATCH_ALLOC_APPEND( l, FD_FEC_RESOLVER_ALIGN,    sizeof(fd_fec_resolver_t)                           );
    1250          24 :   /*     _ctx_pool */  FD_SCRATCH_ALLOC_APPEND( l, alignof(set_ctx_t),       sizeof(set_ctx_t)*depth_sum                         );
    1251          24 :   void * _ctx_map    = FD_SCRATCH_ALLOC_APPEND( l, ctx_map_align(),          ctx_map_footprint  ( ctx_chain_cnt  )               );
    1252          24 :   void * _done_pool  = FD_SCRATCH_ALLOC_APPEND( l, done_pool_align(),        done_pool_footprint( done_depth     )               );
    1253          24 :   void * _done_map   = FD_SCRATCH_ALLOC_APPEND( l, done_map_align(),         done_map_footprint ( done_chain_cnt )               );
    1254          24 :   void * _verifier   = FD_SCRATCH_ALLOC_APPEND( l, fd_ed25519_verifier_align(), fd_ed25519_verifier_footprint( ED25519_CACHE_ENT_CNT ) );
    1255          24 :   FD_SCRATCH_ALLOC_FINI( l, FD_FEC_RESOLVER_ALIGN );
    1256             : 
    1257          24 :   fd_ed25519_verifier_delete( _verifier );
    1258          24 :   done_heap_delete       ( resolver->done_heap     );
    1259          24 :   done_map_delete        ( _done_map               );
    1260          24 :   done_pool_delete       ( _done_pool              );
    1261          24 :   ctx_list_delete        ( resolver->complete_list );
    1262          24 :   ctx_list_delete        ( resolver->free_list     );
    1263          24 :   ctx_treap_delete       ( resolver->ctx_treap     );
    1264          24 :   ctx_map_delete         ( _ctx_map                );
    1265             : 
    1266          24 :   return shmem;
    1267          24 : }

Generated by: LCOV version 1.14