LCOV - code coverage report
Current view: top level - disco/pack - fd_pack.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 1742 1902 91.6 %
Date: 2026-11-03 04:25:32 Functions: 44 51 86.3 %

          Line data    Source code
       1             : #define FD_UNALIGNED_ACCESS_STYLE 0
       2             : #include "fd_pack.h"
       3             : 
       4             : #define SORT_NAME        fd_pack_writer_cost_sort
       5         711 : #define SORT_KEY_T       fd_pack_addr_use_t
       6         447 : #define SORT_BEFORE(a,b) (FD_PACK_TOP_WRITERS_SORT_BEFORE(a,b))
       7             : #define SORT_FN_ATTR     __attribute__((no_sanitize("address", "undefined"))) /* excessive ASan slowdown */
       8             : #include "../../util/tmpl/fd_sort.c"
       9             : 
      10             : #include "fd_pack_cost.h"
      11             : #include "fd_pack_bitset.h"
      12             : #include "fd_pack_unwritable.h"
      13             : #include "fd_chkdup.h"
      14             : #include "fd_pack_tip_prog_blacklist.h"
      15             : #include <math.h> /* for sqrt */
      16             : #include <stddef.h> /* for offsetof */
      17             : #include "../metrics/fd_metrics.h"
      18             : #include "../../util/fd_hash32.h"
      19             : 
      20             : #define FD_PACK_USE_NON_TEMPORAL_MEMCPY 1
      21             : 
      22             : #if FD_HAS_AVX512 && FD_PACK_USE_NON_TEMPORAL_MEMCPY
      23             : #include "../../util/simd/fd_nt_memcpy.h"
      24        4504 : #define pack_memcpy_out  fd_memcpy_nt_nofence
      25        5068 : #define pack_memcpy_fini() _mm_sfence()
      26             : #else
      27        9008 : #define pack_memcpy_out  fd_memcpy
      28             : #define pack_memcpy_fini()
      29             : #endif
      30             : 
      31             : /* Declare a bunch of helper structs used for pack-internal data
      32             :    structures. */
      33             : typedef struct {
      34             :   fd_acct_addr_t key;
      35             : } wrapped_acct_t;
      36             : 
      37             : /* fd_pack_ord_txn_t: An fd_txn_p_t with information required to order
      38             :    it by priority. */
      39             : struct fd_pack_private_ord_txn {
      40             :   /* It's important that there be no padding here (asserted below)
      41             :      because the code casts back and forth from pointers to this element
      42             :      to pointers to the whole struct. */
      43             :   union {
      44             :     fd_txn_p_t   txn[1];  /* txn is an alias for txn_e->txnp */
      45             :     fd_txn_e_t   txn_e[1];
      46             :     fd_txn_e_t   _txn_e;  /* Non-array type needed for map_chain */
      47             :   };
      48             : 
      49             :   /* Since this struct can be in one of several trees, it's helpful to
      50             :      store which tree.  This should be one of the FD_ORD_TXN_ROOT_*
      51             :      values. */
      52             :   int root;
      53             : 
      54             :   /* The sig2txn map_chain fields */
      55             :   ushort sigmap_next;
      56             :   ushort sigmap_prev;
      57             : 
      58             :   /* Each transaction is inserted with an expiration "time."  This code
      59             :      doesn't care about the units (blocks, rdtsc tick, ns, etc.), and
      60             :      doesn't require transactions to be inserted in expiration date
      61             :      order. */
      62             :   ulong expires_at;
      63             :   /* expq_idx: When this object is part of one of the treaps, it's
      64             :      also in the expiration priority queue.  This field (which is
      65             :      manipulated behind the scenes by the fd_prq code) stores where so
      66             :      that if we delete this transaction, we can also delete it from the
      67             :      expiration priority queue. */
      68             :   ulong expq_idx;
      69             : 
      70             :   /* The noncemap map_chain fields */
      71             :   ushort noncemap_next;
      72             :   ushort noncemap_prev;
      73             :   /* For nonce transactions, we store the provided expires_at value here
      74             :      for use by the noncemap comparison functionality.  The actual
      75             :      expires_at value for nonce transactions is rewritten */
      76             :   ulong  nonce_expires_at;
      77             : 
      78             :   /* We want rewards*compute_est to fit in a ulong so that r1/c1 < r2/c2 can be
      79             :      computed as r1*c2 < r2*c1, with the product fitting in a ulong.
      80             :      compute_est has a small natural limit of mid-20 bits. rewards doesn't have
      81             :      a natural limit, so there is some argument to be made for raising the
      82             :      limit for rewards to 40ish bits. The struct has better packing with
      83             :      uint/uint though. */
      84             :   uint                __attribute__((aligned(64))) /* We want the treap fields and the bitsets
      85             :                                                        to be on the same double cache line pair */
      86             :                rewards;     /* in Lamports */
      87             :   uint         compute_est; /* in compute units */
      88             : 
      89             :   /* The treap fields */
      90             :   ushort left;
      91             :   ushort right;
      92             :   ushort parent;
      93             :   ushort prio;
      94             :   ushort prev;
      95             :   ushort next;
      96             : 
      97             :   /* skip: if we skip this transaction more than FD_PACK_SKIP_CNT times
      98             :      for reasons that won't go away until the end of the block, then we
      99             :      want to skip it very quickly.  If skip is in [1, FD_PACK_SKIP_CNT],
     100             :      then that means we have to skip it `skip` more times before taking
     101             :      any action.  If skip>FD_PACK_SKIP_CNT, then it is a compressed slot
     102             :      number during which it should be skipped, and we'll skip it until
     103             :      the compressed slot reaches a new value.  skip is never 0. */
     104             :   ushort skip;
     105             : 
     106             :   FD_PACK_BITSET_DECLARE( rw_bitset ); /* all accts this txn references */
     107             :   FD_PACK_BITSET_DECLARE(  w_bitset ); /* accts this txn write-locks    */
     108             : 
     109             : };
     110             : typedef struct fd_pack_private_ord_txn fd_pack_ord_txn_t;
     111             : 
     112             : /* We require that the payload starts at byte 0 of fd_pack_ord_txn_t,
     113             :    because we cast back and forth between fd_txn_p_t* and
     114             :    fd_pack_ord_txn_t*.
     115             :    GCC and Clang seem to disagree on the rules of offsetof. */
     116             : FD_STATIC_ASSERT( offsetof( fd_pack_ord_txn_t, txn          )==0UL, fd_pack_ord_txn_t );
     117             : #if FD_USING_CLANG
     118             : FD_STATIC_ASSERT( offsetof( fd_txn_p_t,             payload )==0UL, fd_pack_ord_txn_t );
     119             : #else
     120             : FD_STATIC_ASSERT( offsetof( fd_pack_ord_txn_t, txn->payload )==0UL, fd_pack_ord_txn_t );
     121             : FD_STATIC_ASSERT( offsetof( fd_pack_ord_txn_t, txn_e->txnp  )==0UL, fd_pack_ord_txn_t );
     122             : #endif
     123             : 
     124             : /* FD_ORD_TXN_ROOT is essentially a small union packed into an int.  The low
     125             :    byte is the "tag".  The higher 3 bytes depend on the low byte. */
     126       29379 : #define FD_ORD_TXN_ROOT_TAG_MASK                    0xFF
     127     1175568 : #define FD_ORD_TXN_ROOT_FREE                        0
     128       34642 : #define FD_ORD_TXN_ROOT_PENDING                     1
     129        1467 : #define FD_ORD_TXN_ROOT_PENDING_BUNDLE              2
     130       30067 : #define FD_ORD_TXN_ROOT_PENALTY( idx )             (3 | (idx)<<8)
     131        1249 : #define FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE( idx ) (4 | (idx)<<8)
     132             : 
     133             : /* if root & TAG_MASK == PENALTY, then PENALTY_ACCT_IDX(root) gives the index
     134             :    in the transaction's list of account addresses of which penalty treap the
     135             :    transaction is in. */
     136             : #define FD_ORD_TXN_ROOT_PENALTY_ACCT_IDX( root )      (((root) & 0xFF00)>>8)
     137             : /* if root & TAG_MASK == PRE_ROTATION_BUNDLE, then
     138             :    PRE_ROTATION_BUNDLE_IDX(root) gives the index in
     139             :    pre_rotation_bundles of the bundle the transaction is in. */
     140         379 : #define FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE_IDX( root ) (((root) & 0xFF00)>>8)
     141             : 
     142      162912 : #define FD_PACK_IN_USE_WRITABLE    (0x8000000000000000UL)
     143      137674 : #define FD_PACK_IN_USE_BIT_CLEARED (0x4000000000000000UL)
     144             : 
     145             : /* Each non-empty microblock we schedule also has an overhead of 48
     146             :    bytes that counts towards shed limits.  That comes from the 32 byte
     147             :    hash, the hash count (8 bytes) and the transaction count (8 bytes).
     148             :    We don't have to pay this overhead if the microblock is empty, since
     149             :    those microblocks get dropped. */
     150       31155 : #define MICROBLOCK_DATA_OVERHEAD 48UL
     151             : 
     152             : FD_STATIC_ASSERT( sizeof(fd_acct_addr_t)==sizeof(fd_pubkey_t), "" );
     153             : 
     154             : /* fd_pack_expq_t: An element of an fd_prq to sort the transactions by
     155             :    timeout.  This structure has several invariants for entries
     156             :    corresponding to pending transactions:
     157             :      expires_at == txn->expires_at
     158             :      txn->exp_prq_idx is the index of this structure
     159             :    Notice that prq is an array-based heap, which means the indexes of
     160             :    elements change.  The PRQ_TMP_ST macro is hijacked to keep that
     161             :    invariant up to date.
     162             : 
     163             :    Note: this could be easier if fd_heap supported deleting from the
     164             :    middle, but that's not possible with the current design of fd_heap,
     165             :    which omits a parent pointer for improved performance. */
     166             : struct fd_pack_expq {
     167             :   ulong               expires_at;
     168             :   fd_pack_ord_txn_t * txn;
     169             : };
     170             : typedef struct fd_pack_expq fd_pack_expq_t;
     171             : 
     172             : 
     173             : /* fd_pack_bitset_acct_mapping_t: An element of an fd_map_dynamic that
     174             :    maps an account address to the number of transactions that are
     175             :    referencing it and the bit that is reserved to indicate it in the
     176             :    bitset, if any. */
     177             : struct fd_pack_bitset_acct_mapping {
     178             :   fd_acct_addr_t key; /* account address */
     179             :   ulong          ref_cnt;
     180             : 
     181             :   /* first_instance and first_instance_was_write are only valid when
     182             :      bit==FD_PACK_BITSET_FIRST_INSTANCE, which is set when ref_cnt
     183             :      transitions from 0 to 1.  These just exist to implement the
     184             :      optimization that accounts referenced a single time aren't
     185             :      allocated a bit, but this seems to be an important optimization. */
     186             :   fd_pack_ord_txn_t * first_instance;
     187             :   int                 first_instance_was_write;
     188             : 
     189             :   /* bit is in [0, FD_PACK_BITSET_MAX) U
     190             :      { FD_PACK_BITSET_FIRST_INSTANCE, FD_PACK_BITSET_SLOWPATH }. */
     191             :   ushort              bit;
     192             : };
     193             : typedef struct fd_pack_bitset_acct_mapping fd_pack_bitset_acct_mapping_t;
     194             : 
     195             : 
     196             : struct fd_pack_wcost_ele {
     197             :   fd_acct_addr_t key; /* account address */
     198             :   ulong          total_cost;
     199             :   union {
     200             :     uint         map_next;
     201             :     uint         pool_next;
     202             :   };
     203             :   uint           map_prev;
     204             :   uint           dlist_next;
     205             :   uint           dlist_prev;
     206             : };
     207             : typedef struct fd_pack_wcost_ele fd_pack_wcost_ele_t;
     208             : 
     209             : 
     210             : /* pack maintains a small state machine related to initializer bundles.
     211             :    See the header file for more details about it, but it's
     212             :    also summarized here:
     213             :    * NOT_INITIALIZED: The starting state for each block
     214             :    * PENDING: an initializer bundle has been scheduled, but pack has
     215             :      not observed its result yet, so we don't know if it was successful
     216             :      or not.
     217             :    * FAILED: the most recently scheduled initializer bundle failed
     218             :      for reasons other than already being executed.  Most commonly, this
     219             :      could be because of a bug in the code that generated the
     220             :      initializer bundle, a lack of fee payer balance, or an expired
     221             :      blockhash.
     222             :    * READY: the most recently scheduled initialization bundle succeeded
     223             :      and normal bundles can be scheduled in this slot. */
     224         588 : #define FD_PACK_IB_STATE_NOT_INITIALIZED 0
     225           3 : #define FD_PACK_IB_STATE_PENDING         1
     226           0 : #define FD_PACK_IB_STATE_FAILED          2
     227         162 : #define FD_PACK_IB_STATE_READY           3
     228             : 
     229             : 
     230             : /* Returns 1 if x.rewards/x.compute < y.rewards/y.compute. Not robust. */
     231      108667 : #define COMPARE_WORSE(x,y) ( ((ulong)((x)->rewards)*(ulong)((y)->compute_est)) < ((ulong)((y)->rewards)*(ulong)((x)->compute_est)) )
     232             : 
     233             : /* Declare all the data structures */
     234             : 
     235             : 
     236             : /* Define the big max-"heap" that we pull transactions off to schedule.
     237             :    The priority is given by reward/compute.  We may want to add in some
     238             :    additional terms at a later point.  In order to cheaply remove nodes,
     239             :    we actually use a treap.  */
     240             : #define POOL_NAME       trp_pool
     241        1710 : #define POOL_T          fd_pack_ord_txn_t
     242             : #define POOL_IDX_T      ushort
     243      686529 : #define POOL_NEXT       parent
     244             : #include "../../util/tmpl/fd_pool.c"
     245             : 
     246             : #define TREAP_T         fd_pack_ord_txn_t
     247             : #define TREAP_NAME      treap
     248             : #define TREAP_QUERY_T   void *                                         /* We don't use query ... */
     249             : #define TREAP_CMP(a,b)  (__extension__({ (void)(a); (void)(b); -1; })) /* which means we don't need to give a real
     250             :                                                                           implementation to cmp either */
     251      431274 : #define TREAP_IDX_T     ushort
     252             : #define TREAP_OPTIMIZE_ITERATION 1
     253      108667 : #define TREAP_LT        COMPARE_WORSE
     254             : #include "../../util/tmpl/fd_treap.c"
     255             : 
     256             : 
     257             : #define MAP_NAME              sig2txn
     258             : #define MAP_OPTIMIZE_RANDOM_ACCESS_REMOVAL 1
     259             : #define MAP_MULTI              1
     260       30846 : #define MAP_ELE_T              fd_pack_ord_txn_t
     261       48268 : #define MAP_PREV               sigmap_prev
     262       80825 : #define MAP_NEXT               sigmap_next
     263       42175 : #define MAP_IDX_T              ushort
     264             : 
     265             : #define MAP_KEY_T              fd_txn_e_t
     266       63477 : #define MAP_KEY                _txn_e
     267       85017 : #define TXNE_TO_SIG(ptr)       (__extension__({ fd_txn_p_t const * __p = (ptr)->txnp; __p->payload + TXN(__p)->signature_off;  }))
     268        8292 : #define MAP_KEY_EQ(k0,k1)      (!memcmp( TXNE_TO_SIG(k0), TXNE_TO_SIG(k1), FD_TXN_SIGNATURE_SZ) )
     269       68433 : #define MAP_KEY_HASH(key,seed) fd_hash( (seed), TXNE_TO_SIG(key), 64UL )
     270             : #include "../../util/tmpl/fd_map_chain.c"
     271             : 
     272             : 
     273             : /* noncemap: A map from (nonce account, nonce authority) to a durable
     274             :    nonce transaction containing it.  We only want to allow one
     275             :    transaction in the pool at a time with a given (nonce account, nonce
     276             :    authority) tuple value, keeping the one with the blockhash value
     277             :    derived from the newest blockhash, breaking ties by value.  The
     278             :    question is: can adding this limitation cause us to throw out
     279             :    potentially valuable transaction?  The answer is yes, but only very
     280             :    rarely, and the savings are worth it.  Suppose we have durable nonce
     281             :    transactions t1 and t2 that advance the same nonce account.
     282             : 
     283             :    If t1 and t2 have the same recent blockhash value:
     284             :    - If t1 lands on chain, then it will advance the nonce account, and
     285             :    t2 certainly cannot land on chain.
     286             :    - If t1 fails with AlreadyExecuted, that means the nonce account was
     287             :    advanced when t1 landed in a previous block, so t2 will certainly not
     288             :    land on chain either.
     289             :    - If t1 fails with BlockhashNotFound, then the nonce account was
     290             :    advanced in some previous transaction, so again, t2 will certainly
     291             :    not land on chain.
     292             :    - If t1 does not land on chain because of an issue with the fee
     293             :    payer, it's possible that t2 could land on chain if it used a
     294             :    different fee payer, but historical data shows this is unlikely.
     295             :    - If t1 does not land on chain because it is part of a bundle that
     296             :    fails for an unrelated reason, it's possible that t2 could land on
     297             :    chain, but again, historical data says this is rare.
     298             : 
     299             :    Otherwise, suppose t1's recent blockhash value is the value based on
     300             :    slot s1's blockhash (which is written to nonce accounts when
     301             :    executing in slot s1+1) and similarly for s2, and that s1<s2.
     302             :    Then we'll throw out t1 and only try to pack t2.
     303             : 
     304             :    The sender will only send t2 if they think the nonce account contains
     305             :    (or will contain) the value based on slot s2's blockhash, which means
     306             :    they think a transaction landed or will land in slot s2+1.
     307             :    If a transaction updating the nonce account did land in slot s2+1,
     308             :    then t1 can never land, so throwing it out is safe.
     309             :    It's possible, but seems unlikely, that the sender could be
     310             :    speculating and has only seen slot s2 but not s2+1 yet.  In that
     311             :    case, if we are leader for both s2+1, we could pack t1 in s2+1 and t2
     312             :    in a later slot.  Again, this is a case where we'll take the small
     313             :    hit in exchange for the simplification.
     314             : 
     315             :    We need to include the nonce authority in the hash to prevent one
     316             :    user from being able to DoS another user. */
     317             : 
     318             : typedef struct {
     319             :   fd_acct_addr_t const * nonce_acct;
     320             :   fd_acct_addr_t const * nonce_auth;
     321             : } noncemap_extract_t;
     322             : 
     323             : /* k must be a valid, durable nonce transaction.  No error checking is
     324             :    done. */
     325             : static inline void
     326             : noncemap_extract( fd_txn_e_t const   * k,
     327        3496 :                   noncemap_extract_t * out ) {
     328        3496 :   fd_txn_t const * txn = TXN(k->txnp);
     329             : 
     330        3496 :   ulong nonce_idx = k->txnp->payload[ txn->instr[ 0 ].acct_off+0 ];
     331        3496 :   ulong autho_idx = k->txnp->payload[ txn->instr[ 0 ].acct_off+2 ];
     332             : 
     333        3496 :   ulong imm_cnt = fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
     334        3496 :   fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, k->txnp->payload );
     335        3496 :   fd_acct_addr_t const * alt_adj = k->alt_accts - imm_cnt;
     336        3496 :   out->nonce_acct = fd_ptr_if( nonce_idx<imm_cnt, accts, alt_adj )+nonce_idx;
     337             :   /* The nonce authority must be a signer, so it must be an immediate
     338             :      account. */
     339        3496 :   out->nonce_auth = accts+autho_idx;
     340        3496 : }
     341             : 
     342             : static inline int
     343             : noncemap_key_eq_internal( fd_txn_e_t const * k0,
     344         189 :                           fd_txn_e_t const * k1 ) {
     345         189 :   noncemap_extract_t e0[1], e1[1];
     346         189 :   noncemap_extract( k0, e0 );
     347         189 :   noncemap_extract( k1, e1 );
     348             : 
     349         189 :   if( FD_UNLIKELY( memcmp( e0->nonce_acct,       e1->nonce_acct,       32UL ) ) ) return 0;
     350         183 :   if( FD_UNLIKELY( memcmp( e0->nonce_auth,       e1->nonce_auth,       32UL ) ) ) return 0;
     351         183 :   return 1;
     352         183 : }
     353             : 
     354             : #if FD_HAS_INT128
     355             : 
     356             : /* unrolled xxHash3 */
     357             : 
     358             : static inline ulong
     359             : noncemap_key_hash_internal( ulong              seed,
     360        3118 :                             fd_txn_e_t const * k ) {
     361        3118 :   noncemap_extract_t e[1];
     362        3118 :   noncemap_extract( k, e );
     363             : 
     364        3118 :   ulong k0 = FD_LOAD( ulong, e->nonce_acct->b   + 0 );
     365        3118 :   ulong k1 = FD_LOAD( ulong, e->nonce_acct->b   + 8 );
     366        3118 :   ulong k2 = FD_LOAD( ulong, e->nonce_acct->b   +16 );
     367        3118 :   ulong k3 = FD_LOAD( ulong, e->nonce_acct->b   +24 );
     368        3118 :   ulong k4 = FD_LOAD( ulong, e->nonce_auth->b   + 0 );
     369        3118 :   ulong k5 = FD_LOAD( ulong, e->nonce_auth->b   + 8 );
     370        3118 :   ulong k6 = FD_LOAD( ulong, e->nonce_auth->b   +16 );
     371        3118 :   ulong k7 = FD_LOAD( ulong, e->nonce_auth->b   +24 );
     372             : 
     373        3118 :   ulong acc = 96 * 0x9E3779B185EBCA87ULL;
     374        3118 :   acc += fd_xxh3_mix16b( k4, k5, 0xcb00c391bb52283cUL, 0xa32e531b8b65d088UL, seed );
     375        3118 :   acc += fd_xxh3_mix16b( k6, k7, 0x4ef90da297486471UL, 0xd8acdea946ef1938UL, seed );
     376        3118 :   acc += fd_xxh3_mix16b( k2, k3, 0x78e5c0cc4ee679cbUL, 0x2172ffcc7dd05a82UL, seed );
     377        3118 :   acc += fd_xxh3_mix16b( k0, k1, 0xbe4ba423396cfeb8UL, 0x1cad21f72c81017cUL, seed );
     378        3118 :   acc = acc ^ (acc >> 37);
     379        3118 :   acc *= 0x165667919E3779F9ULL;
     380        3118 :   acc = acc ^ (acc >> 32);
     381        3118 :   return acc;
     382        3118 : }
     383             : 
     384             : #else
     385             : 
     386             : static inline ulong
     387             : noncemap_key_hash_internal( ulong              seed,
     388             :                             fd_txn_e_t const * k ) {
     389             :   noncemap_extract_t e[1];
     390             :   noncemap_extract( k, e );
     391             : 
     392             :   uchar buf[ 64 ];
     393             :   memcpy( buf,      e->nonce_acct->b,     32UL );
     394             :   memcpy( buf+32UL, e->nonce_auth->b,     32UL );
     395             :   return fd_hash( seed, buf, 64UL );
     396             : }
     397             : 
     398             : #endif
     399             : 
     400             : #define MAP_NAME               noncemap
     401             : #define MAP_OPTIMIZE_RANDOM_ACCESS_REMOVAL 1
     402             : #define MAP_MULTI              0
     403         384 : #define MAP_ELE_T              fd_pack_ord_txn_t
     404         412 : #define MAP_PREV               noncemap_prev
     405         967 : #define MAP_NEXT               noncemap_next
     406        4686 : #define MAP_IDX_T              ushort
     407             : #define MAP_KEY_T              fd_txn_e_t
     408         784 : #define MAP_KEY                _txn_e
     409         189 : #define MAP_KEY_EQ(k0,k1)      noncemap_key_eq_internal( (k0), (k1) )
     410        3118 : #define MAP_KEY_HASH(key,seed) noncemap_key_hash_internal( (seed), (key) )
     411             : #include "../../util/tmpl/fd_map_chain.c"
     412             : 
     413             : 
     414             : static const fd_acct_addr_t null_addr = { 0 };
     415             : 
     416             : #define MAP_NAME              acct_uses
     417      491769 : #define MAP_T                 fd_pack_addr_use_t
     418      603048 : #define MAP_KEY_T             fd_acct_addr_t
     419    12026513 : #define MAP_KEY_NULL          null_addr
     420             : #if FD_HAS_AVX
     421      603048 : # define MAP_KEY_INVAL(k)     _mm256_testz_si256( wb_ldu( (k).b ), wb_ldu( (k).b ) )
     422             : #else
     423             : # define MAP_KEY_INVAL(k)     MAP_KEY_EQUAL(k, null_addr)
     424             : #endif
     425      381200 : #define MAP_KEY_EQUAL(k0,k1)  (!memcmp((k0).b,(k1).b, FD_TXN_ACCT_ADDR_SZ))
     426             : #define MAP_KEY_EQUAL_IS_SLOW 1
     427             : #define MAP_MEMOIZE           0
     428      696377 : #define MAP_KEY_HASH(key,s)   ((uint)fd_hash32( (key).b, (s) ))
     429             : #include "../../util/tmpl/fd_map_dynamic.c"
     430             : 
     431             : #define MAP_NAME              wcost_map
     432        4842 : #define MAP_ELE_T             fd_pack_wcost_ele_t
     433             : #define MAP_KEY_T             fd_acct_addr_t
     434      190795 : #define MAP_IDX_T             uint
     435       17148 : #define MAP_NEXT              map_next
     436       12158 : #define MAP_PREV              map_prev
     437             : #define MAP_OPTIMIZE_RANDOM_ACCESS_REMOVAL 1
     438       94992 : #define MAP_KEY_EQ(k0,k1)     (!memcmp((k0)->b,(k1)->b, FD_TXN_ACCT_ADDR_SZ))
     439      135670 : #define MAP_KEY_HASH(key,s)   ((uint)fd_hash32( (key)->b, (s) ))
     440             : #include "../../util/tmpl/fd_map_chain.c"
     441             : 
     442             : #define POOL_NAME             wcost_pool
     443        1140 : #define POOL_T                fd_pack_wcost_ele_t
     444             : #define POOL_IDX_T            uint
     445    91216831 : #define POOL_NEXT             pool_next
     446             : #include "../../util/tmpl/fd_pool.c"
     447             : 
     448             : #define DLIST_NAME            wcost_dlist
     449             : #define DLIST_ELE_T           fd_pack_wcost_ele_t
     450             : #define DLIST_IDX_T           uint
     451       16831 : #define DLIST_NEXT            dlist_next
     452       11992 : #define DLIST_PREV            dlist_prev
     453             : #include "../../util/tmpl/fd_dlist.c"
     454             : 
     455             : #define MAP_NAME              bitset_map
     456      451714 : #define MAP_T                 fd_pack_bitset_acct_mapping_t
     457      524886 : #define MAP_KEY_T             fd_acct_addr_t
     458    83690397 : #define MAP_KEY_NULL          null_addr
     459             : #if FD_HAS_AVX
     460    71538774 : # define MAP_KEY_INVAL(k)     _mm256_testz_si256( wb_ldu( (k).b ), wb_ldu( (k).b ) )
     461             : #else
     462             : # define MAP_KEY_INVAL(k)     MAP_KEY_EQUAL(k, null_addr)
     463             : #endif
     464      368089 : #define MAP_KEY_EQUAL(k0,k1)  (!memcmp((k0).b,(k1).b, FD_TXN_ACCT_ADDR_SZ))
     465             : #define MAP_KEY_EQUAL_IS_SLOW 1
     466             : #define MAP_MEMOIZE           0
     467      449452 : #define MAP_KEY_HASH(key,s)   ((uint)fd_hash32( (key).b, (s) ))
     468             : #include "../../util/tmpl/fd_map_dynamic.c"
     469             : 
     470             : 
     471             : #define MAP_NAME              acct_blocklist
     472      215604 : #define MAP_T                 wrapped_acct_t
     473             : /* Add 1 to the slot cnt to ensure the map is sparse even at capacity */
     474      234045 : #define MAP_LG_SLOT_CNT       (FD_PACK_ACCT_BLOCKLIST_LG_MAX+1)
     475      215037 : #define MAP_KEY_T             fd_acct_addr_t
     476       18432 : #define MAP_KEY_NULL          null_addr
     477             : #if FD_HAS_AVX
     478      431841 : # define MAP_KEY_INVAL(k)     _mm256_testz_si256( wb_ldu( (k).b ), wb_ldu( (k).b ) )
     479             : #else
     480             : # define MAP_KEY_INVAL(k)     MAP_KEY_EQUAL(k, null_addr)
     481             : #endif
     482      214974 : #define MAP_KEY_EQUAL(k0,k1)  (!memcmp((k0).b,(k1).b, FD_TXN_ACCT_ADDR_SZ))
     483             : /* It would be nice if this were seeded, but since fd_map doesn't have
     484             :    any auxiliary data, there's not a clear place to store the seed.
     485             :    It's okay though, because the insert process is trusted, since it
     486             :    comes from operator config. */
     487      215028 : #define MAP_KEY_HASH(key)     ((uint)fd_ulong_hash( fd_ulong_load_8( (key).b ) ))
     488             : #define MAP_KEY_EQUAL_IS_SLOW 1
     489             : #define MAP_MEMOIZE           0
     490             : #define MAX_QUERY_OPT         2 /* rare hits */
     491             : #include "../../util/tmpl/fd_map.c"
     492             : 
     493             : /* Since transactions can also expire, we also maintain a parallel
     494             :    priority queue.  This means elements are simultaneously part of the
     495             :    treap (ordered by priority) and the expiration queue (ordered by
     496             :    expiration).  It's tempting to use the priority field of the treap
     497             :    for this purpose, but that can result in degenerate treaps in some
     498             :    cases. */
     499             : #define PRQ_NAME             expq
     500      108021 : #define PRQ_T                fd_pack_expq_t
     501       64377 : #define PRQ_TIMEOUT_T        ulong
     502       64377 : #define PRQ_TIMEOUT          expires_at
     503       52017 : #define PRQ_TMP_ST(p,t)      do {                                   \
     504       52017 :                                (p)[0] = (t);                        \
     505       52017 :                                t.txn->expq_idx = (ulong)((p)-heap); \
     506       52017 :                              } while( 0 )
     507             : #include "../../util/tmpl/fd_prq.c"
     508             : 
     509             : /* With realistic traffic patterns, we often see many, many transactions
     510             :    competing for the same writable account.  Since only one of these can
     511             :    execute at a time, we sometimes waste lots of scheduling time going
     512             :    through them one at a time.  To combat that, when a transaction
     513             :    writes to an account with more than PENALTY_TREAP_THRESHOLD
     514             :    references (readers or writers), instead of inserting it into the
     515             :    main treap, we insert it into a penalty treap for that specific hot
     516             :    account address.  These transactions are not immediately available
     517             :    for scheduling.  Then, when a transaction that writes to the hot
     518             :    address completes, we move the most lucrative transaction from the
     519             :    penalty treap to the main treap, making it available for scheduling.
     520             :    This policy may slightly violate the price-time priority scheduling
     521             :    approach pack normally uses: if the most lucrative transaction
     522             :    competing for hot state arrives after PENALTY_TREAP_THRESHOLD has
     523             :    been hit, it may be scheduled second instead of first.  However, if
     524             :    the account is in use at the time the new transaction arrives, it
     525             :    will be scheduled next, as desired.  This minor difference seems
     526             :    reasonable to reduce complexity.
     527             : 
     528             :    fd_pack_penalty_treap is one account-specific penalty treap.  All the
     529             :    transactions in the penalty_treap treap write to key.
     530             : 
     531             :    penalty_map is the fd_map_dynamic that maps accounts to their
     532             :    respective penalty treaps. */
     533             : struct fd_pack_penalty_treap {
     534             :   fd_acct_addr_t key;
     535             :   treap_t penalty_treap[1];
     536             : };
     537             : typedef struct fd_pack_penalty_treap fd_pack_penalty_treap_t;
     538             : 
     539             : #define MAP_NAME              penalty_map
     540       73444 : #define MAP_T                 fd_pack_penalty_treap_t
     541       72319 : #define MAP_KEY_T             fd_acct_addr_t
     542     1306509 : #define MAP_KEY_NULL          null_addr
     543             : #if FD_HAS_AVX
     544     1181911 : # define MAP_KEY_INVAL(k)     _mm256_testz_si256( wb_ldu( (k).b ), wb_ldu( (k).b ) )
     545             : #else
     546             : # define MAP_KEY_INVAL(k)     MAP_KEY_EQUAL(k, null_addr)
     547             : #endif
     548       72277 : #define MAP_KEY_EQUAL(k0,k1)  (!memcmp((k0).b,(k1).b, FD_TXN_ACCT_ADDR_SZ))
     549             : #define MAP_KEY_EQUAL_IS_SLOW 1
     550             : #define MAP_MEMOIZE           0
     551       72298 : #define MAP_KEY_HASH(key,s)   ((uint)fd_hash32( (key).b, (s) ))
     552             : #include "../../util/tmpl/fd_map_dynamic.c"
     553             : 
     554             : /* PENALTY_TREAP_THRESHOLD: How many references to an account do we
     555             :    allow before subsequent transactions that write to the account go to
     556             :    the penalty treap. */
     557      164511 : #define PENALTY_TREAP_THRESHOLD 64UL
     558             : 
     559             : 
     560             : /* FD_PACK_SKIP_CNT: How many times we'll skip a transaction (for
     561             :    reasons other than account conflicts) before we won't consider it
     562             :    until the next slot.  For performance reasons, this doesn't reset at
     563             :    the end of a slot, so e.g. we might skip twice in slot 1, then three
     564             :    times in slot 2, which would be enough to prevent considering it
     565             :    until slot 3.  The main reason this is not 1 is that some skips that
     566             :    seem permanent until the end of the slot can actually go away based
     567             :    on rebates. */
     568       35481 : #define FD_PACK_SKIP_CNT 50UL
     569             : 
     570             : /* FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY: the maximum number of the
     571             :    bundles that arrived before our leader rotation which we execute
     572             :    during our leader rotation.  Any extra pre-rotation bundles are
     573             :    dropped, in order of their declared tip. */
     574       13275 : #define FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY 16UL
     575             : 
     576             : /* fd_pack_pre_rotation_bundle represents a single pre-rotation bundle:
     577             :    its transactions, in bundle order, in treap, the declared tip, and
     578             :    the sequence number representing the order of insertion. */
     579             : struct fd_pack_pre_rotation_bundle {
     580             :   treap_t treap[1];
     581             :   ulong   tip;
     582             :   ulong   seq;
     583             : };
     584             : typedef struct fd_pack_pre_rotation_bundle fd_pack_pre_rotation_bundle_t;
     585             : 
     586             : /* Finally, we can now declare the main pack data structure */
     587             : struct fd_pack_private {
     588             :   ulong      pack_depth;
     589             :   ulong      bundle_meta_sz; /* if 0, bundles are disabled */
     590             :   ulong      bank_tile_cnt;
     591             : 
     592             :   fd_pack_limits_t lim[1];
     593             : 
     594             :   ulong      pending_txn_cnt; /* Summed across all treaps */
     595             :   ulong      microblock_cnt; /* How many microblocks have we
     596             :                                 generated in this block? */
     597             :   ulong      data_bytes_consumed; /* How much data is in this block so
     598             :                                      far ? */
     599             :   /* There's a limit on the total amount that transactions in a block
     600             :      can allocate.  How much of that limit have we consumed? */
     601             :   ulong      alloc_consumed;
     602             : 
     603             :   /* counters / gauge for schedule outcome enums */
     604             :   ulong      sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_CNT ];
     605             : 
     606             :   fd_rng_t * rng;
     607             : 
     608             :   ulong      cumulative_block_cost;
     609             : 
     610             :   /* expire_before: Any transactions with expires_at strictly less than
     611             :      the current expire_before are removed from the available pending
     612             :      transaction.  Here, "expire" is used as a verb: cause all
     613             :      transactions before this time to expire. */
     614             :   ulong      expire_before;
     615             : 
     616             :   /* outstanding_microblock_mask: a bitmask indicating which banking
     617             :      tiles have outstanding microblocks, i.e. fd_pack has generated a
     618             :      microblock for that banking tile and the banking tile has not yet
     619             :      notified fd_pack that it has completed it. */
     620             :   ulong      outstanding_microblock_mask;
     621             : 
     622             :   /* The actual footprint for the pool and maps is allocated
     623             :      in the same order in which they are declared immediately following
     624             :      the struct.  I.e. these pointers point to memory not far after the
     625             :      struct.  The trees are just pointers into the pool so don't take up
     626             :      more space. */
     627             : 
     628             :   fd_pack_ord_txn_t * pool;
     629             : 
     630             :   /* Treaps (sorted by priority) of pending transactions.  We store the
     631             :      transactions that come from bundles separately. */
     632             :   treap_t pending[1];
     633             :   treap_t pending_bundles[1];
     634             : 
     635             :   /* Bundles that arrived before our leader rotation has started are
     636             :      stored in pre_rotation_bundles, one bundle per treap.
     637             :      rotation_end_ns stores the timestamp, in ns, of the end of the
     638             :      last leader rotation, so that we can determine if a bundle arrived
     639             :      during the start of the leader rotation or not.
     640             :      pre_rotation_seq stores an incrementing sequence number, which we
     641             :      use to track the order in which the pre-rotation bundles arrived.
     642             : 
     643             :      We could use a more complex data structure to track the best and
     644             :      worse pre-rotation bundle, but since
     645             :      FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY is so small it's not worth
     646             :      the added complexity. */
     647             :   fd_pack_pre_rotation_bundle_t pre_rotation_bundles[ FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY ];
     648             :   ulong                         pre_rotation_bundle_cnt;
     649             :   ulong                         pre_rotation_seq;
     650             :   long                          rotation_end_ns;
     651             : 
     652             :   /* penalty_treaps: an fd_map_dynamic mapping hotly contended account
     653             :      addresses to treaps of transactions that write to them.  We try not
     654             :      to allow more than roughly PENALTY_TREAP_THRESHOLD transactions in
     655             :      the main treap that write to each account, though this is not
     656             :      exact. */
     657             :   fd_pack_penalty_treap_t * penalty_treaps;
     658             : 
     659             :   /* initializer_bundle_state: The current state of the initialization
     660             :      bundle state machine.  One of the FD_PACK_IB_STATE_* values.  See
     661             :      the long comment in the header and the comments attached to the
     662             :      respective values for a discussion of what each state means and the
     663             :      transitions between them. */
     664             :   int   initializer_bundle_state;
     665             : 
     666             :   /* relative_bundle_idx: the number of bundles that have been inserted
     667             :      since the last time pending_bundles was empty.  See the long
     668             :      comment about encoding this index in the rewards field of each
     669             :      transaction in the bundle, and why it is important that this reset
     670             :      to 0 as frequently as possible. */
     671             :   ulong relative_bundle_idx;
     672             : 
     673             :   /* pending_smallest: keep a conservative estimate of the
     674             :      smallest transaction (by cost units and by bytes) in the pending
     675             :      treap.  Both CUs and bytes should be set to ULONG_MAX if the treap
     676             :      is empty. */
     677             :   fd_pack_smallest_t pending_smallest[1];
     678             : 
     679             :   /* expiration_q: At the same time that a transaction is in exactly one
     680             :      of the above treaps, it is also in the expiration queue, sorted by
     681             :      its expiration time.  This enables deleting all transactions that
     682             :      have expired, regardless of which treap they are in. */
     683             :   fd_pack_expq_t * expiration_q;
     684             : 
     685             :   /* acct_in_use: Map from account address to bitmask indicating which
     686             :      bank tiles are using the account and whether that use is read or
     687             :      write (msb). */
     688             :   fd_pack_addr_use_t   * acct_in_use;
     689             : 
     690             :   /* bitset_{w, rw}_in_use stores a subset of the information in
     691             :      acct_in_use using the compressed set format explained at the top of
     692             :      this file.  rw_in_use stores accounts in use for read or write
     693             :      while w_in_use stores only those in use for write. */
     694             :   FD_PACK_BITSET_DECLARE( bitset_rw_in_use );
     695             :   FD_PACK_BITSET_DECLARE( bitset_w_in_use  );
     696             : 
     697             :   /* writer_costs: Map (fd_map_chain) from account addresses to the sum
     698             :      of costs of transactions that write to the account.  Used for
     699             :      enforcing limits on the max write cost per account per block. */
     700             :   wcost_map_t   * writer_costs;
     701             : 
     702             :   /* written_list: At the end of every slot, we have to clear out
     703             :      writer_costs.  The map is large, but typically very sparsely
     704             :      populated.  As an optimization, we keep a doubly linked list of the
     705             :      elements actually used */
     706             :   wcost_dlist_t  written_list[1];
     707             : 
     708             :   /* writers: This is the fd_pool that backs writer_costs and
     709             :      written_list.  Each element is either in writers (as a fd_pool) OR
     710             :      in both writer_costs and written_list. */
     711             :   fd_pack_wcost_ele_t  * writers;
     712             : 
     713             :   /* top_writers: A simple max heap of the top 5 writers in the slot,
     714             :      used by downstream consumers for monitoring purposes. */
     715             :   fd_pack_addr_use_t top_writers[ FD_PACK_TOP_WRITERS_CNT ];
     716             : 
     717             :   /* At initialization time, the caller can configure a blocklist of
     718             :      accounts.  Any transaction that includes one of these accounts will
     719             :      be rejected.  This is an fd_map, and it's effectively const. */
     720             :   wrapped_acct_t        acct_blocklist[ 2*FD_PACK_ACCT_BLOCKLIST_MAX ];
     721             : 
     722             :   /* Noncemap is a map_chain that maps from tuples (nonce account,
     723             :      recent blockhash value, nonce authority) to a transaction.  This
     724             :      map stores exactly the transactions in pool that have the nonce
     725             :      flag set. */
     726             :   noncemap_t * noncemap;
     727             : 
     728             :   sig2txn_t * signature_map; /* Stores pointers into pool for deleting by signature */
     729             : 
     730             :   /* bundle_temp_map: A fd_map_dynamic (although it could be an fd_map)
     731             :      used during fd_pack_try_schedule_bundle to store information about
     732             :      what accounts are used by transactions in the bundle.  It's empty
     733             :      (in a map sense) outside of calls to try_schedule_bundle, and each
     734             :      call to try_schedule_bundle clears it after use.  If bundles are
     735             :      disabled, this is a valid fd_map_dynamic, but it's as small as
     736             :      convenient and remains empty. */
     737             :   fd_pack_addr_use_t * bundle_temp_map;
     738             : 
     739             : 
     740             :   /* use_by_bank: An array of size (max_txn_per_microblock *
     741             :      FD_TXN_ACCT_ADDR_MAX) for each banking tile.  Only the MSB of
     742             :      in_use_by is relevant.  Addressed use_by_bank[i][j] where i is in
     743             :      [0, bank_tile_cnt) and j is in [0, use_by_bank_cnt[i]).  Used
     744             :      mostly for clearing the proper bits of acct_in_use when a
     745             :      microblock finishes.
     746             : 
     747             :      use_by_bank_txn: indexed [i][j], where i is in [0, bank_tile_cnt)
     748             :      and j is in [0, max_txn_per_microblock).  Transaction j in the
     749             :      microblock currently scheduled to bank i uses account addresses in
     750             :      use_by_bank[i][k] where k is in [0, use_by_bank[i][j]).  For
     751             :      example, if use_by_bank[i][0] = 2 and use_by_bank[i][1] = 3, then
     752             :      all the accounts that the first transaction in the outstanding
     753             :      microblock for bank 0 uses are contained in the set
     754             :                { use_by_bank[i][0], use_by_bank[i][1] },
     755             :      and all the accounts in the second transaction in the microblock
     756             :      are in the set
     757             :         { use_by_bank[i][0], use_by_bank[i][1], use_by_bank[i][2] }.
     758             :      Each transaction writes to at least one account (the fee payer)
     759             :      that no other transaction scheduled to the bank uses, which means
     760             :      that use_by_bank_txn[i][j] - use_by_bank_txn[i][j-1] >= 1 (with 0
     761             :      for use_by_bank_txn[i][-1]).  This means we can stop iterating when
     762             :      use_by_bank_txn[i][j] == use_by_bank_cnt[i].  */
     763             :   fd_pack_addr_use_t * use_by_bank    [ FD_PACK_MAX_EXECLE_TILES ];
     764             :   ulong                use_by_bank_cnt[ FD_PACK_MAX_EXECLE_TILES ];
     765             :   ulong *              use_by_bank_txn[ FD_PACK_MAX_EXECLE_TILES ];
     766             : 
     767             :   fd_histf_t txn_per_microblock[ 1 ];
     768             : 
     769             :   fd_histf_t scheduled_cus_per_block[ 1 ];
     770             :   fd_histf_t rebated_cus_per_block  [ 1 ];
     771             :   fd_histf_t net_cus_per_block      [ 1 ];
     772             :   fd_histf_t pct_cus_per_block      [ 1 ];
     773             :   ulong      cumulative_rebated_cus;
     774             : 
     775             : 
     776             :   /* compressed_slot_number: a number in (FD_PACK_SKIP_CNT, USHORT_MAX]
     777             :      that advances each time we start packing for a new slot. */
     778             :   ushort     compressed_slot_number;
     779             : 
     780             :   /* bitset_avail: a stack of which bits are not currently reserved and
     781             :      can be used to represent an account address.
     782             :      Indexed [0, bitset_avail_cnt].  Element 0 is fixed at
     783             :      FD_PACK_BITSET_SLOWPATH. */
     784             :   ushort bitset_avail[ 1UL+FD_PACK_BITSET_MAX ];
     785             :   ulong  bitset_avail_cnt;
     786             : 
     787             :   /* acct_to_bitset: an fd_map_dynamic that maps acct addresses to the
     788             :      reference count, which bit, etc. */
     789             :   fd_pack_bitset_acct_mapping_t * acct_to_bitset;
     790             : 
     791             :   /* chdkup: scratch memory chkdup needs for its internal processing */
     792             :   fd_chkdup_t chkdup[ 1 ];
     793             : 
     794             :   /* bundle_meta: an array, parallel to the pool, with each element
     795             :      having size bundle_meta_sz.  I.e. if pool[i] has an associated
     796             :      bundle meta, it's located at bundle_meta[j] for j in
     797             :      [i*bundle_meta_sz, (i+1)*bundle_meta_sz). */
     798             :   void * bundle_meta;
     799             : };
     800             : 
     801             : typedef struct fd_pack_private fd_pack_t;
     802             : 
     803             : FD_STATIC_ASSERT( offsetof(fd_pack_t, pending_txn_cnt)==FD_PACK_PENDING_TXN_CNT_OFF, txn_cnt_off );
     804             : 
     805             : /* Forward-declare some helper functions */
     806             : static ulong delete_transaction( fd_pack_t * pack, fd_pack_ord_txn_t * txn, int delete_full_bundle, int move_from_penalty_treap );
     807             : static inline void insert_bundle_impl( fd_pack_t * pack, ulong bundle_idx, ulong txn_cnt, fd_pack_ord_txn_t * * bundle, ulong expires_at );
     808             : static inline ulong insert_pre_rotation_bundle_impl( fd_pack_t * pack, ulong txn_cnt, fd_pack_ord_txn_t * * bundle, ulong expires_at, ulong pre_rotation_tip );
     809             : 
     810             : FD_FN_PURE ulong
     811             : fd_pack_footprint( ulong                    pack_depth,
     812             :                    ulong                    bundle_meta_sz,
     813             :                    ulong                    bank_tile_cnt,
     814         561 :                    fd_pack_limits_t const * limits         ) {
     815         561 :   if( FD_UNLIKELY( (bank_tile_cnt==0) | (bank_tile_cnt>FD_PACK_MAX_EXECLE_TILES) ) ) return 0UL;
     816         561 :   if( FD_UNLIKELY( pack_depth<4UL ) ) return 0UL;
     817             : 
     818         561 :   int enable_bundles = !!bundle_meta_sz;
     819         561 :   ulong l;
     820         561 :   ulong extra_depth        = fd_ulong_if( enable_bundles, 1UL+2UL*FD_PACK_MAX_TXN_PER_BUNDLE, 1UL ); /* space for use between init and fini */
     821         561 :   ulong max_acct_in_treap  = pack_depth * FD_TXN_ACCT_ADDR_MAX;
     822         561 :   ulong max_txn_per_mblk   = fd_ulong_max( limits->max_txn_per_microblock,
     823         561 :                                            fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE, 0UL ) );
     824         561 :   ulong max_acct_in_flight = bank_tile_cnt * (FD_TXN_ACCT_ADDR_MAX * max_txn_per_mblk + 1UL);
     825         561 :   ulong max_txn_in_flight  = bank_tile_cnt * max_txn_per_mblk;
     826             : 
     827         561 :   ulong max_w_per_block    = fd_ulong_min( limits->max_cost_per_block / FD_PACK_COST_PER_WRITABLE_ACCT,
     828         561 :                                            max_txn_per_mblk * limits->max_microblocks_per_block * FD_TXN_ACCT_ADDR_MAX );
     829         561 :   ulong wcost_chain_cnt    = wcost_map_chain_cnt_est( max_w_per_block );
     830         561 :   ulong bundle_temp_accts  = fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE*FD_TXN_ACCT_ADDR_MAX, 1UL );
     831         561 :   ulong sig_chain_cnt      = sig2txn_chain_cnt_est( pack_depth );
     832         561 :   ulong nonce_chain_cnt    = noncemap_chain_cnt_est( pack_depth );
     833             : 
     834             :   /* log base 2, but with a 2* so that the hash table stays sparse */
     835         561 :   int lg_uses_tbl_sz = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_flight                        ) );
     836         561 :   int lg_acct_in_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap                         ) );
     837         561 :   int lg_penalty_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap/PENALTY_TREAP_THRESHOLD ) );
     838         561 :   int lg_bundle_temp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*bundle_temp_accts                         ) );
     839             : 
     840         561 :   l = FD_LAYOUT_INIT;
     841         561 :   l = FD_LAYOUT_APPEND( l, FD_PACK_ALIGN,       sizeof(fd_pack_t)                               );
     842         561 :   l = FD_LAYOUT_APPEND( l, trp_pool_align (),   trp_pool_footprint ( pack_depth+extra_depth   ) ); /* pool           */
     843         561 :   l = FD_LAYOUT_APPEND( l, penalty_map_align(), penalty_map_footprint( lg_penalty_trp         ) ); /* penalty_treaps */
     844         561 :   l = FD_LAYOUT_APPEND( l, expq_align     (),   expq_footprint     ( pack_depth               ) ); /* expiration prq */
     845         561 :   l = FD_LAYOUT_APPEND( l, acct_uses_align(),   acct_uses_footprint( lg_uses_tbl_sz           ) ); /* acct_in_use    */
     846         561 :   l = FD_LAYOUT_APPEND( l, wcost_map_align(),   wcost_map_footprint( wcost_chain_cnt          ) ); /* writer_costs   */
     847         561 :   l = FD_LAYOUT_APPEND( l, wcost_pool_align(),  wcost_pool_footprint( max_w_per_block         ) ); /* writers        */
     848         561 :   l = FD_LAYOUT_APPEND( l, noncemap_align (),   noncemap_footprint ( nonce_chain_cnt          ) ); /* noncemap       */
     849         561 :   l = FD_LAYOUT_APPEND( l, sig2txn_align  (),   sig2txn_footprint  ( sig_chain_cnt            ) ); /* signature_map  */
     850         561 :   l = FD_LAYOUT_APPEND( l, acct_uses_align(),   acct_uses_footprint( lg_bundle_temp           ) ); /* bundle_temp_map*/
     851         561 :   l = FD_LAYOUT_APPEND( l, 32UL,                sizeof(fd_pack_addr_use_t)*max_acct_in_flight   ); /* use_by_bank    */
     852         561 :   l = FD_LAYOUT_APPEND( l, 32UL,                sizeof(ulong)*max_txn_in_flight                 ); /* use_by_bank_txn*/
     853         561 :   l = FD_LAYOUT_APPEND( l, bitset_map_align(),  bitset_map_footprint( lg_acct_in_trp          ) ); /* acct_to_bitset */
     854         561 :   l = FD_LAYOUT_APPEND( l, 64UL,                (pack_depth+extra_depth)*bundle_meta_sz         ); /* bundle_meta */
     855         561 :   return FD_LAYOUT_FINI( l, FD_PACK_ALIGN );
     856         561 : }
     857             : 
     858             : void *
     859             : fd_pack_new( void                   * mem,
     860             :              ulong                    pack_depth,
     861             :              ulong                    bundle_meta_sz,
     862             :              ulong                    bank_tile_cnt,
     863             :              fd_pack_limits_t const * limits,
     864             :              fd_acct_addr_t const *   acct_blocklist,
     865             :              ulong                    acct_blocklist_cnt,
     866         576 :              fd_rng_t               * rng           ) {
     867             : 
     868         576 :   int enable_bundles = !!bundle_meta_sz;
     869         576 :   ulong extra_depth        = fd_ulong_if( enable_bundles, 1UL+2UL*FD_PACK_MAX_TXN_PER_BUNDLE, 1UL );
     870         576 :   ulong max_acct_in_treap  = pack_depth * FD_TXN_ACCT_ADDR_MAX;
     871         576 :   ulong max_txn_per_mblk   = fd_ulong_max( limits->max_txn_per_microblock,
     872         576 :                                            fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE, 0UL ) );
     873         576 :   ulong max_acct_in_flight = bank_tile_cnt * (FD_TXN_ACCT_ADDR_MAX * max_txn_per_mblk + 1UL);
     874         576 :   ulong max_txn_in_flight  = bank_tile_cnt * max_txn_per_mblk;
     875             : 
     876         576 :   ulong max_w_per_block    = fd_ulong_min( limits->max_cost_per_block / FD_PACK_COST_PER_WRITABLE_ACCT,
     877         576 :                                            max_txn_per_mblk * limits->max_microblocks_per_block * FD_TXN_ACCT_ADDR_MAX );
     878         576 :   ulong wcost_chain_cnt    = wcost_map_chain_cnt_est( max_w_per_block );
     879         576 :   ulong bundle_temp_accts  = fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE*FD_TXN_ACCT_ADDR_MAX, 1UL );
     880         576 :   ulong sig_chain_cnt      = sig2txn_chain_cnt_est( pack_depth );
     881         576 :   ulong nonce_chain_cnt    = noncemap_chain_cnt_est( pack_depth );
     882             : 
     883             :   /* log base 2, but with a 2* so that the hash table stays sparse */
     884         576 :   int lg_uses_tbl_sz = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_flight                        ) );
     885         576 :   int lg_acct_in_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap                         ) );
     886         576 :   int lg_penalty_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap/PENALTY_TREAP_THRESHOLD ) );
     887         576 :   int lg_bundle_temp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*bundle_temp_accts                         ) );
     888             : 
     889         576 :   FD_SCRATCH_ALLOC_INIT( l, mem );
     890         576 :   fd_pack_t * pack    = FD_SCRATCH_ALLOC_APPEND( l,  FD_PACK_ALIGN,       sizeof(fd_pack_t)                             );
     891             :   /* The pool has one extra element that is used between insert_init and
     892             :      cancel/fini. */
     893         576 :   void * _pool        = FD_SCRATCH_ALLOC_APPEND( l,  trp_pool_align(),    trp_pool_footprint ( pack_depth+extra_depth ) );
     894         576 :   void * _penalty_map = FD_SCRATCH_ALLOC_APPEND( l,  penalty_map_align(), penalty_map_footprint( lg_penalty_trp       ) );
     895         576 :   void * _expq        = FD_SCRATCH_ALLOC_APPEND( l,  expq_align(),        expq_footprint     ( pack_depth             ) );
     896         576 :   void * _uses        = FD_SCRATCH_ALLOC_APPEND( l,  acct_uses_align(),   acct_uses_footprint( lg_uses_tbl_sz         ) );
     897         576 :   void * _writer_cost = FD_SCRATCH_ALLOC_APPEND( l,  wcost_map_align(),   wcost_map_footprint( wcost_chain_cnt        ) );
     898         576 :   void * _written_lst = FD_SCRATCH_ALLOC_APPEND( l,  wcost_pool_align(),  wcost_pool_footprint( max_w_per_block       ) );
     899         576 :   void * _noncemap    = FD_SCRATCH_ALLOC_APPEND( l,  noncemap_align(),    noncemap_footprint ( nonce_chain_cnt        ) );
     900         576 :   void * _sig_map     = FD_SCRATCH_ALLOC_APPEND( l,  sig2txn_align(),     sig2txn_footprint  ( sig_chain_cnt          ) );
     901         576 :   void * _bundle_temp = FD_SCRATCH_ALLOC_APPEND( l,  acct_uses_align(),   acct_uses_footprint( lg_bundle_temp         ) );
     902         576 :   void * _use_by_bank = FD_SCRATCH_ALLOC_APPEND( l,  32UL,                sizeof(fd_pack_addr_use_t)*max_acct_in_flight );
     903         576 :   void * _use_by_txn  = FD_SCRATCH_ALLOC_APPEND( l,  32UL,                sizeof(ulong)*max_txn_in_flight               );
     904         576 :   void * _acct_bitset = FD_SCRATCH_ALLOC_APPEND( l,  bitset_map_align(),  bitset_map_footprint( lg_acct_in_trp        ) );
     905         576 :   void * bundle_meta  = FD_SCRATCH_ALLOC_APPEND( l,  64UL,                (pack_depth+extra_depth)*bundle_meta_sz       );
     906             : 
     907         576 :   pack->pack_depth                  = pack_depth;
     908         576 :   pack->bundle_meta_sz              = bundle_meta_sz;
     909         576 :   pack->bank_tile_cnt               = bank_tile_cnt;
     910         576 :   pack->lim[0]                      = *limits;
     911         576 :   pack->pending_txn_cnt             = 0UL;
     912         576 :   pack->microblock_cnt              = 0UL;
     913         576 :   pack->data_bytes_consumed         = 0UL;
     914         576 :   pack->alloc_consumed              = 0UL;
     915         576 :   memset( pack->sched_results, 0, sizeof(pack->sched_results) );
     916         576 :   pack->rng                         = rng;
     917         576 :   pack->cumulative_block_cost       = 0UL;
     918         576 :   pack->expire_before               = 0UL;
     919         576 :   pack->outstanding_microblock_mask = 0UL;
     920         576 :   pack->cumulative_rebated_cus      = 0UL;
     921         576 :   pack->initializer_bundle_state    = FD_PACK_IB_STATE_NOT_INITIALIZED;
     922         576 :   pack->relative_bundle_idx         = 1UL;
     923             : 
     924         576 :   acct_blocklist_new( pack->acct_blocklist );
     925         576 :   int ins_failed = acct_blocklist_cnt>FD_PACK_ACCT_BLOCKLIST_MAX;
     926         642 :   for( ulong i=0UL; (!ins_failed) & (i<acct_blocklist_cnt); i++ ) {
     927          66 :     ins_failed |= acct_blocklist_key_inval( acct_blocklist[i] ) ||
     928          66 :                   (NULL==acct_blocklist_insert( pack->acct_blocklist, acct_blocklist[i] ));
     929          66 :   }
     930         576 :   if( FD_UNLIKELY( ins_failed ) ) {
     931           6 :     FD_LOG_WARNING(( "constructing the account blocklist failed.  Ensure the list contains no more than %lu "
     932           6 :                      "entries, and does not contain duplicates or the System Program (11...111)", FD_PACK_ACCT_BLOCKLIST_MAX ));
     933           6 :     return NULL;
     934           6 :   }
     935             : 
     936         570 :   trp_pool_new(  _pool,        pack_depth+extra_depth );
     937             : 
     938         570 :   fd_pack_ord_txn_t * pool = trp_pool_join( _pool );
     939         570 :   treap_seed( pool, pack_depth+extra_depth, fd_rng_ulong( rng ) );
     940      620052 :   for( ulong i=0UL; i<pack_depth+extra_depth; i++ ) pool[i].root = FD_ORD_TXN_ROOT_FREE;
     941             : 
     942         570 :   (void)trp_pool_leave( pool );
     943             : 
     944         570 :   penalty_map_new( _penalty_map, lg_penalty_trp, fd_rng_ulong( rng ) );
     945             : 
     946             :   /* These treaps can have at most pack_depth elements at any moment,
     947             :      but they come from a pool of size pack_depth+extra_depth. */
     948         570 :   treap_new( (void*)pack->pending,         pack_depth+extra_depth );
     949         570 :   treap_new( (void*)pack->pending_bundles, pack_depth+extra_depth );
     950        9690 :   for( ulong i=0UL; i<FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY; i++ ) {
     951        9120 :     treap_new( (void*)pack->pre_rotation_bundles[ i ].treap, pack_depth+extra_depth );
     952        9120 :   }
     953             : 
     954         570 :   pack->pre_rotation_bundle_cnt = 0UL;
     955         570 :   pack->pre_rotation_seq        = 0UL;
     956         570 :   pack->rotation_end_ns         = 0L;
     957             : 
     958         570 :   pack->pending_smallest->cus         = ULONG_MAX;
     959         570 :   pack->pending_smallest->bytes       = ULONG_MAX;
     960             : 
     961         570 :   expq_new( _expq, pack_depth );
     962             : 
     963         570 :   FD_PACK_BITSET_CLEAR( pack->bitset_rw_in_use );
     964         570 :   FD_PACK_BITSET_CLEAR( pack->bitset_w_in_use  );
     965             : 
     966         570 :   acct_uses_new( _uses,        lg_uses_tbl_sz, fd_rng_ulong( rng ) );
     967         570 :   acct_uses_new( _bundle_temp, lg_bundle_temp, fd_rng_ulong( rng ) );
     968             : 
     969         570 :   wcost_map_new  ( _writer_cost, wcost_chain_cnt, fd_rng_ulong( rng ) );
     970         570 :   wcost_dlist_new( pack->written_list                                 );
     971         570 :   wcost_pool_new ( _written_lst, max_w_per_block                      );
     972             : 
     973         570 :   noncemap_new( _noncemap, nonce_chain_cnt, fd_rng_ulong( rng ) );
     974             : 
     975         570 :   sig2txn_new( _sig_map, sig_chain_cnt, fd_rng_ulong( rng ) );
     976             : 
     977         570 :   fd_pack_addr_use_t * use_by_bank     = (fd_pack_addr_use_t *)_use_by_bank;
     978         570 :   ulong *              use_by_bank_txn = (ulong *)_use_by_txn;
     979        6840 :   for( ulong i=0UL; i<bank_tile_cnt; i++ ) {
     980        6270 :     pack->use_by_bank    [i] = use_by_bank + i*(FD_TXN_ACCT_ADDR_MAX*max_txn_per_mblk+1UL);
     981        6270 :     pack->use_by_bank_cnt[i] = 0UL;
     982        6270 :     pack->use_by_bank_txn[i] = use_by_bank_txn + i*max_txn_per_mblk;
     983        6270 :     pack->use_by_bank_txn[i][0] = 0UL;
     984        6270 :   }
     985       29640 :   for( ulong i=bank_tile_cnt; i<FD_PACK_MAX_EXECLE_TILES; i++ ) {
     986       29070 :     pack->use_by_bank    [i] = NULL;
     987       29070 :     pack->use_by_bank_cnt[i] = 0UL;
     988       29070 :     pack->use_by_bank_txn[i] = NULL;
     989       29070 :   }
     990             : 
     991         570 :   fd_histf_new( pack->txn_per_microblock, FD_MHIST_MIN( PACK, TXN_PER_MICROBLOCK ),
     992         570 :                                           FD_MHIST_MAX( PACK, TXN_PER_MICROBLOCK ) );
     993             : 
     994         570 :   fd_histf_new( pack->scheduled_cus_per_block, FD_MHIST_MIN( PACK, COST_SCHEDULED_PER_BLOCK ),
     995         570 :                                                FD_MHIST_MAX( PACK, COST_SCHEDULED_PER_BLOCK ) );
     996         570 :   fd_histf_new( pack->rebated_cus_per_block,   FD_MHIST_MIN( PACK, CU_REBATED_PER_BLOCK     ),
     997         570 :                                                FD_MHIST_MAX( PACK, CU_REBATED_PER_BLOCK     ) );
     998         570 :   fd_histf_new( pack->net_cus_per_block,       FD_MHIST_MIN( PACK, COST_NET_PER_BLOCK       ),
     999         570 :                                                FD_MHIST_MAX( PACK, COST_NET_PER_BLOCK       ) );
    1000         570 :   fd_histf_new( pack->pct_cus_per_block,       FD_MHIST_MIN( PACK, COST_PER_BLOCK_PCT       ),
    1001         570 :                                                FD_MHIST_MAX( PACK, COST_PER_BLOCK_PCT       ) );
    1002             : 
    1003         570 :   pack->compressed_slot_number = (ushort)(FD_PACK_SKIP_CNT+1);
    1004             : 
    1005         570 :   pack->bitset_avail[ 0 ] = FD_PACK_BITSET_SLOWPATH;
    1006      195130 :   for( ulong i=0UL; i<FD_PACK_BITSET_MAX; i++ ) pack->bitset_avail[ i+1UL ] = (ushort)i;
    1007         570 :   pack->bitset_avail_cnt = FD_PACK_BITSET_MAX;
    1008             : 
    1009         570 :   bitset_map_new( _acct_bitset, lg_acct_in_trp, fd_rng_ulong( rng ) );
    1010             : 
    1011         570 :   fd_chkdup_new( pack->chkdup, rng );
    1012             : 
    1013         570 :   pack->bundle_meta = bundle_meta;
    1014             : 
    1015         570 :   return mem;
    1016         576 : }
    1017             : 
    1018             : fd_pack_t *
    1019         570 : fd_pack_join( void * mem ) {
    1020         570 :   FD_SCRATCH_ALLOC_INIT( l, mem );
    1021         570 :   fd_pack_t * pack  = FD_SCRATCH_ALLOC_APPEND( l, FD_PACK_ALIGN, sizeof(fd_pack_t) );
    1022             : 
    1023         570 :   int enable_bundles = !!pack->bundle_meta_sz;
    1024         570 :   ulong pack_depth             = pack->pack_depth;
    1025         570 :   ulong extra_depth            = fd_ulong_if( enable_bundles, 1UL+2UL*FD_PACK_MAX_TXN_PER_BUNDLE, 1UL );
    1026         570 :   ulong bank_tile_cnt          = pack->bank_tile_cnt;
    1027         570 :   ulong max_txn_per_microblock = fd_ulong_max( pack->lim->max_txn_per_microblock,
    1028         570 :                                                fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE, 0UL ) );
    1029             : 
    1030         570 :   ulong max_acct_in_treap  = pack_depth * FD_TXN_ACCT_ADDR_MAX;
    1031         570 :   ulong max_acct_in_flight = bank_tile_cnt * (FD_TXN_ACCT_ADDR_MAX * max_txn_per_microblock + 1UL);
    1032         570 :   ulong max_txn_in_flight  = bank_tile_cnt * max_txn_per_microblock;
    1033         570 :   ulong max_w_per_block    = fd_ulong_min( pack->lim->max_cost_per_block / FD_PACK_COST_PER_WRITABLE_ACCT,
    1034         570 :                                            max_txn_per_microblock * pack->lim->max_microblocks_per_block * FD_TXN_ACCT_ADDR_MAX );
    1035         570 :   ulong wcost_chain_cnt    = wcost_map_chain_cnt_est( max_w_per_block );
    1036         570 :   ulong bundle_temp_accts  = fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE*FD_TXN_ACCT_ADDR_MAX, 1UL );
    1037         570 :   ulong sig_chain_cnt      = sig2txn_chain_cnt_est( pack_depth );
    1038         570 :   ulong nonce_chain_cnt    = noncemap_chain_cnt_est( pack_depth );
    1039             : 
    1040         570 :   int lg_uses_tbl_sz = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_flight                        ) );
    1041         570 :   int lg_acct_in_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap                         ) );
    1042         570 :   int lg_penalty_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap/PENALTY_TREAP_THRESHOLD ) );
    1043         570 :   int lg_bundle_temp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*bundle_temp_accts                         ) );
    1044             : 
    1045             : 
    1046         570 :   pack->pool          = trp_pool_join(   FD_SCRATCH_ALLOC_APPEND( l, trp_pool_align(),   trp_pool_footprint   ( pack_depth+extra_depth  ) ) );
    1047         570 :   pack->penalty_treaps= penalty_map_join(FD_SCRATCH_ALLOC_APPEND( l, penalty_map_align(),penalty_map_footprint( lg_penalty_trp          ) ) );
    1048         570 :   pack->expiration_q  = expq_join    (   FD_SCRATCH_ALLOC_APPEND( l, expq_align(),       expq_footprint       ( pack_depth              ) ) );
    1049         570 :   pack->acct_in_use   = acct_uses_join(  FD_SCRATCH_ALLOC_APPEND( l, acct_uses_align(),  acct_uses_footprint  ( lg_uses_tbl_sz          ) ) );
    1050         570 :   pack->writer_costs  = wcost_map_join(  FD_SCRATCH_ALLOC_APPEND( l, wcost_map_align(),  wcost_map_footprint  ( wcost_chain_cnt         ) ) );
    1051         570 :   pack->writers       = wcost_pool_join( FD_SCRATCH_ALLOC_APPEND( l, wcost_pool_align(), wcost_pool_footprint( max_w_per_block          ) ) );
    1052         570 :   pack->noncemap      = noncemap_join(   FD_SCRATCH_ALLOC_APPEND( l, noncemap_align(),   noncemap_footprint   ( nonce_chain_cnt         ) ) );
    1053         570 :   pack->signature_map = sig2txn_join(    FD_SCRATCH_ALLOC_APPEND( l, sig2txn_align(),    sig2txn_footprint    ( sig_chain_cnt           ) ) );
    1054         570 :   pack->bundle_temp_map=acct_uses_join(  FD_SCRATCH_ALLOC_APPEND( l, acct_uses_align(),  acct_uses_footprint  ( lg_bundle_temp          ) ) );
    1055         570 :   /* */                                  FD_SCRATCH_ALLOC_APPEND( l, 32UL,               sizeof(fd_pack_addr_use_t)*max_acct_in_flight      );
    1056         570 :   /* */                                  FD_SCRATCH_ALLOC_APPEND( l, 32UL,               sizeof(ulong)*max_txn_in_flight                    );
    1057         570 :   pack->acct_to_bitset= bitset_map_join( FD_SCRATCH_ALLOC_APPEND( l, bitset_map_align(), bitset_map_footprint( lg_acct_in_trp           ) ) );
    1058         570 :   /* */                                  FD_SCRATCH_ALLOC_APPEND( l, 64UL,               (pack_depth+extra_depth)*pack->bundle_meta_sz      );
    1059             : 
    1060         570 :   wcost_dlist_join( pack->written_list );
    1061             : 
    1062         570 :   FD_MGAUGE_SET( PACK, TXN_PENDING_CAPACITY, pack->pack_depth );
    1063         570 :   memset( pack->top_writers, 0, sizeof(pack->top_writers) );
    1064             : 
    1065         570 :   return pack;
    1066         570 : }
    1067             : 
    1068             : 
    1069             : /* Returns 0 on failure, 1 on success. */
    1070             : static int
    1071             : fd_pack_estimate_rewards_and_compute( fd_txn_e_t             * txne,
    1072             :                                       fd_pack_ord_txn_t      * out,
    1073       35076 :                                       fd_pack_limits_t const * lim ) {
    1074       35076 :   fd_txn_t * txn = TXN(txne->txnp);
    1075       35076 :   ulong sig_rewards = FD_PACK_FEE_PER_SIGNATURE * txn->signature_cnt; /* Easily in [5000, 635000] */
    1076             : 
    1077       35076 :   ulong requested_execution_cus;
    1078       35076 :   ulong priority_rewards;
    1079       35076 :   ulong precompile_sigs;
    1080       35076 :   ulong requested_loaded_accounts_data_cost;
    1081       35076 :   ulong allocated_data;
    1082       35076 :   ulong cost_estimate = fd_pack_compute_cost( txn, txne->txnp->payload, &requested_execution_cus, &priority_rewards, &precompile_sigs, &requested_loaded_accounts_data_cost, &allocated_data );
    1083             : 
    1084       35076 :   if( FD_UNLIKELY( !cost_estimate ) ) return 0;
    1085             : 
    1086             :   /* precompile_sigs <= 16320, so after the addition,
    1087             :      sig_rewards < 83,000,000 */
    1088       35073 :   sig_rewards += FD_PACK_FEE_PER_SIGNATURE * precompile_sigs;
    1089       35073 :   sig_rewards = sig_rewards * FD_PACK_TXN_FEE_BURN_PCT / 100UL;
    1090             : 
    1091             :   /* No fancy CU estimation in this version of pack
    1092             :   for( ulong i=0UL; i<(ulong)txn->instr_cnt; i++ ) {
    1093             :     uchar prog_id_idx = txn->instr[ i ].program_id;
    1094             :     fd_acct_addr_t const * acct_addr = fd_txn_get_acct_addrs( txn, txnp->payload ) + (ulong)prog_id_idx;
    1095             :   }
    1096             :   */
    1097       35073 :   out->rewards                              = (priority_rewards < (UINT_MAX - sig_rewards)) ? (uint)(sig_rewards + priority_rewards) : UINT_MAX;
    1098       35073 :   out->compute_est                          = (uint)cost_estimate;
    1099       35073 :   out->txn->pack_cu.requested_exec_plus_acct_data_cus = (uint)(requested_execution_cus + requested_loaded_accounts_data_cost);
    1100       35073 :   out->txn->pack_cu.non_execution_cus       = (uint)(cost_estimate - requested_execution_cus - requested_loaded_accounts_data_cost);
    1101       35073 :   out->txn->pack_alloc                      = (uint)allocated_data;
    1102             : 
    1103             :   /* If a transaction allocates a lot, we want to treat it as if it
    1104             :      requests more CUs.  However, we use compute_est in the block
    1105             :      limit calculations, so we can't touch it.  To have the same
    1106             :      effect, we decrease rewards.
    1107             :      divisor is 1 unless
    1108             :             allocated_data                       cost_estimate
    1109             :       ----------------------------    >=       ------------------
    1110             :       max_allocated_data_per_block             max_cost_per_block
    1111             : 
    1112             :      0       <=allocated_data      <=20 * 1024^2
    1113             :      30*10^6 <= max_cost_per_block < 2^32
    1114             :      1020    <= cost_estimate      < 1.6 * 10^6
    1115             :      50*10^6 <= max_allocated_data_per_block <= 100 * 1000^2
    1116             :                 (changes with the slot time duration)
    1117             :      So the numerator (<2^57) and denominator (<2^48) can't overflow.
    1118             :      Both cost_estimate and max_allocated_data_per_block non-zero,
    1119             :      so the denominator is never zero.
    1120             :      1 <= divisor <= 1 + (max_cost_per_block * .000206)
    1121             :      */
    1122       35073 :   ulong divisor = 1UL + (allocated_data * lim->max_cost_per_block) / (cost_estimate * lim->max_allocated_data_per_block);
    1123       35073 :   out->rewards /= (uint)divisor;
    1124             : 
    1125       35073 :   return 1;
    1126       35076 : }
    1127             : 
    1128             : /* Returns 0 on failure, 1 if not a durable nonce transaction, and 2 if
    1129             :    it is.  FIXME: These return codes are set to harmonize with
    1130             :    estimate_rewards_and_compute but -1/0/1 makes a lot more sense to me.
    1131             :    */
    1132             : static int
    1133       35073 : fd_pack_validate_durable_nonce( fd_txn_e_t * txne ) {
    1134       35073 :   fd_txn_t const * txn = TXN(txne->txnp);
    1135             : 
    1136             :   /* First instruction invokes system program with 4 bytes of
    1137             :      instruction data with the little-endian value 4.  It also has 3
    1138             :      accounts: the nonce account, recent blockhashes sysvar, and the
    1139             :      nonce authority.  It seems like technically the nonce authority may
    1140             :      not need to be passed in, but we disallow that.  We also allow
    1141             :      trailing data and trailing accounts.  We want to organize the
    1142             :      checks somewhat to minimize cache misses. */
    1143       35073 :   if( FD_UNLIKELY( txn->instr_cnt==0            ) ) return 1;
    1144       35073 :   if( FD_UNLIKELY( txn->instr[ 0 ].data_sz<4UL  ) ) return 1;
    1145       35073 :   if( FD_UNLIKELY( txn->instr[ 0 ].acct_cnt<3UL ) ) return 1; /* It seems like technically 2 is allowed, but never used */
    1146        4998 :   if( FD_LIKELY  ( fd_uint_load_4( txne->txnp->payload + txn->instr[ 0 ].data_off )!=4U ) ) return 1;
    1147             :   /* The program has to be a static account */
    1148        1188 :   fd_acct_addr_t const * accts = fd_txn_get_acct_addrs( txn, txne->txnp->payload );
    1149        1188 :   if( FD_UNLIKELY( !fd_memeq( accts[ txn->instr[ 0 ].program_id ].b, null_addr.b, 32UL       ) ) ) return 1;
    1150        1188 :   if( FD_UNLIKELY( !fd_txn_is_writable( txn, txne->txnp->payload[ txn->instr[ 0 ].acct_off ] ) ) ) return 1;
    1151        1179 :   if( FD_UNLIKELY( !fd_txn_is_signer( txn, txne->txnp->payload[ txn->instr[ 0 ].acct_off+2 ] ) ) ) return 0;
    1152             :   /* We could check recent blockhash, but it's not necessary */
    1153        1176 :   return 2;
    1154        1179 : }
    1155             : 
    1156             : /* Can the fee payer afford to pay a transaction with the specified
    1157             :    price?  Returns 1 if so, 0 otherwise.  This is just a stub that
    1158             :    always returns 1 for now, and the real check is deferred to the bank
    1159             :    tile.  In general, this function can't be totally accurate, because
    1160             :    the transactions immediately prior to this one can affect the balance
    1161             :    of this fee payer, but a simple check here may be helpful for
    1162             :    reducing spam. */
    1163             : static int
    1164             : fd_pack_can_fee_payer_afford( fd_acct_addr_t const * acct_addr,
    1165       35064 :                               ulong                  price /* in lamports */) {
    1166       35064 :   (void)acct_addr;
    1167       35064 :   (void)price;
    1168       35064 :   return 1;
    1169       35064 : }
    1170             : 
    1171             : 
    1172             : 
    1173             : 
    1174             : 
    1175             : fd_txn_e_t *
    1176       32922 : fd_pack_insert_txn_init( fd_pack_t * pack ) {
    1177       32922 :   fd_pack_ord_txn_t * ord = trp_pool_ele_acquire( pack->pool );
    1178             :   /* fini clears the bitsets; nothing on the way there touches those
    1179             :      lines and a just-evicted element has them cold.  The two sets are
    1180             :      adjacent and span at most two lines, whatever the bitset mode. */
    1181       32922 :   __builtin_prefetch( &ord->rw_bitset,                                         1, 3 );
    1182       32922 :   __builtin_prefetch( (uchar const *)&ord->w_bitset+sizeof(ord->w_bitset)-1UL, 1, 3 );
    1183       32922 :   return ord->txn_e;
    1184       32922 : }
    1185           0 : void         fd_pack_insert_txn_cancel( fd_pack_t * pack, fd_txn_e_t * txn ) { trp_pool_ele_release( pack->pool, (fd_pack_ord_txn_t*)txn ); }
    1186             : 
    1187          72 : #define REJECT( reason ) do {                                       \
    1188          72 :                            trp_pool_ele_release( pack->pool, ord ); \
    1189          72 :                            return FD_PACK_INSERT_REJECT_ ## reason; \
    1190          72 :                          } while( 0 )
    1191             : 
    1192             : /* These require txn, accts, and alt_adj to be defined as per usual */
    1193       30253 : #define ACCT_IDX_TO_PTR( idx ) (__extension__( {                                               \
    1194       30253 :       ulong __idx = (ulong)(idx);                                                              \
    1195       30253 :       fd_ptr_if( __idx<fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM ), accts, alt_adj )+__idx; \
    1196       30253 :       }))
    1197     1496304 : #define ACCT_ITER_TO_PTR( iter ) (__extension__( {                                             \
    1198     1496304 :       ulong __idx = fd_txn_acct_iter_idx( iter );                                              \
    1199     1496304 :       fd_ptr_if( __idx<fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM ), accts, alt_adj )+__idx; \
    1200     1496304 :       }))
    1201             : 
    1202             : 
    1203             : /* Tries to find the worst transaction in any treap in pack.  If that
    1204             :    transaction's score is worse than or equal to threshold_score, it
    1205             :    initiates a delete and returns the number of deleted transactions
    1206             :    (potentially more than 1 for a bundle).  If it's higher than
    1207             :    threshold_score, it returns 0.  To force this function to delete the
    1208             :    worst transaction if there are any eligible ones, pass FLT_MAX as
    1209             :    threshold_score. */
    1210             : static inline ulong
    1211             : delete_worst( fd_pack_t * pack,
    1212        3156 :               float       threshold_score ) {
    1213             :   /* If the tree is full, we want to see if this is better than the
    1214             :      worst element in the pool before inserting.  If the new transaction
    1215             :      is better than that one, we'll delete it and insert the new
    1216             :      transaction. Otherwise, we'll throw away this transaction.
    1217             : 
    1218             :      We want to bias the definition of "worst" here to provide better
    1219             :      quality of service.  For example, if the pool is filled with
    1220             :      transactions that all write to the same account, we want to bias
    1221             :      towards treating one of those transactions as the worst, even if
    1222             :      they pay slightly higher fees per computer unit, since we know we
    1223             :      won't actually be able to schedule them all.
    1224             : 
    1225             :      This is a tricky task, however.  All our notions of priority and
    1226             :      better/worse are based on static information about the transaction,
    1227             :      and there's not an easy way to take into account global
    1228             :      information, for example, how many other transactions contend with
    1229             :      this one.  One idea is to build a heap (not a treap, since we only
    1230             :      need pop-min, insert, and delete) with one element for each element
    1231             :      in the pool, with a "delete me" score that's related but not
    1232             :      identical to the normal score.  This would allow building in some
    1233             :      global information.  The downside is that the global information
    1234             :      that gets integrated is static.  E.g. if you bias a transaction's
    1235             :      "delete me" score to make it more likely to be deleted because
    1236             :      there are many conflicting transactions in the pool, the score
    1237             :      stays biased, even if the global conditions change (unless you come
    1238             :      up with some complicated re-scoring scheme).  This can work, since
    1239             :      when the pool is full, the global bias factors are unlikely to
    1240             :      change significantly at the relevant timescales.
    1241             : 
    1242             :      However, rather than this, we implement a simpler probabilistic
    1243             :      scheme.  We'll sample M transactions, find the worst transaction in
    1244             :      each of the M treaps, compute a "delete me" score for those <= M
    1245             :      transactions, and delete the worst.  If one penalty treap is
    1246             :      starting to get big, then it becomes very likely that the random
    1247             :      sample will find it and choose to delete a transaction from it.
    1248             : 
    1249             :      The exact formula for the "delete me" score should be the matter of
    1250             :      some more intense quantitative research.  For now, we'll just use
    1251             :      this:
    1252             : 
    1253             :      Treap with N transactions        Scale Factor
    1254             :      Pending                      1.0
    1255             :      Penalty treap                1.0 at <= 100 transactions, then sqrt(100/N)
    1256             :      Pending bundles              inf (since the rewards value is fudged)
    1257             : 
    1258             :      We'll also use M=8. */
    1259             : 
    1260        3156 :   float worst_score = FLT_MAX;
    1261        3156 :   fd_pack_ord_txn_t * worst = NULL;
    1262        3156 :   uint  pool_max = (uint)trp_pool_max( pack->pool );
    1263        3156 :   ulong samples[ 8UL ];
    1264       28404 :   for( ulong i=0UL; i<8UL; i++ ) {
    1265             :     /* Roll all 8 first so the root loads (8 cold lines) overlap */
    1266       25248 :     samples[ i ] = fd_rng_uint_roll( pack->rng, pool_max );
    1267       25248 :     __builtin_prefetch( &pack->pool[ samples[ i ] ].root, 0, 3 );
    1268       25248 :   }
    1269       28404 :   for( ulong i=0UL; i<8UL; i++ ) {
    1270       25248 :     ulong sample_i = samples[ i ];
    1271             : 
    1272       25248 :     fd_pack_ord_txn_t * sample = &pack->pool[ sample_i ];
    1273             :     /* Presumably if we're calling this, the pool is almost entirely
    1274             :        full, so the probability of choosing a free one is small.  If
    1275             :        it does happen, find the first one that isn't free. */
    1276       28016 :     while( FD_UNLIKELY( sample->root==FD_ORD_TXN_ROOT_FREE ) ) sample = &pack->pool[ (++sample_i)%pool_max ];
    1277             : 
    1278       25248 :     int       root_idx   = sample->root;
    1279       25248 :     float     multiplier = 0.0f; /* The smaller this is, the more biased we'll be to deleting it */
    1280       25248 :     treap_t * treap;
    1281       25248 :     switch( root_idx & FD_ORD_TXN_ROOT_TAG_MASK ) {
    1282           0 :       default:
    1283           0 :       case FD_ORD_TXN_ROOT_FREE: {
    1284           0 :         FD_LOG_CRIT(( "Double free detected" ));
    1285           0 :         return ULONG_MAX; /* Can't be hit */
    1286           0 :       }
    1287        3637 :       case FD_ORD_TXN_ROOT_PENDING: {
    1288        3637 :         treap = pack->pending;
    1289        3637 :         multiplier = 1.0f;
    1290        3637 :         break;
    1291           0 :       }
    1292           0 :       case FD_ORD_TXN_ROOT_PENDING_BUNDLE: {
    1293             :         /* We don't have a way to tell how much these actually pay in
    1294             :            rewards, so we just assume they are very high. */
    1295           0 :         treap = pack->pending_bundles;
    1296             :         /* We cap rewards at UINT_MAX lamports for estimation, and min
    1297             :            CUs is about 1000, which means rewards/compute < 5e6.
    1298             :            FLT_MAX is around 3e38. That means, 1e20*rewards/compute is
    1299             :            much less than FLT_MAX, so we won't have any issues with
    1300             :            overflow.  On the other hand, if rewards==1 lamport and
    1301             :            compute is 2 million CUs, 1e20*1/2e6 is still higher than any
    1302             :            normal transaction. */
    1303           0 :         multiplier = 1e20f;
    1304           0 :         break;
    1305           0 :       }
    1306         355 :       case FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE( 0 ): {
    1307         355 :         treap      = pack->pre_rotation_bundles[ FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE_IDX( root_idx ) ].treap;
    1308         355 :         multiplier = 1e20f;
    1309         355 :         break;
    1310           0 :       }
    1311       21256 :       case FD_ORD_TXN_ROOT_PENALTY( 0 ): {
    1312       21256 :         fd_txn_t * txn = TXN( sample->txn );
    1313       21256 :         fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, sample->txn->payload );
    1314       21256 :         fd_acct_addr_t const * alt_adj = sample->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1315       21256 :         fd_acct_addr_t penalty_acct = *ACCT_IDX_TO_PTR( FD_ORD_TXN_ROOT_PENALTY_ACCT_IDX( root_idx ) );
    1316       21256 :         fd_pack_penalty_treap_t * q = penalty_map_query( pack->penalty_treaps, penalty_acct, NULL );
    1317       21256 :         FD_TEST( q );
    1318       21256 :         ulong cnt = treap_ele_cnt( q->penalty_treap );
    1319       21256 :         treap = q->penalty_treap;
    1320             : 
    1321       21256 :         multiplier = sqrtf( 100.0f / (float)fd_ulong_max( 100UL, cnt ) );
    1322       21256 :         break;
    1323       21256 :       }
    1324       25248 :     }
    1325             :     /* Get the worst from the sampled treap */
    1326       25248 :     treap_fwd_iter_t _cur=treap_fwd_iter_init( treap, pack->pool );
    1327       25248 :     FD_TEST( !treap_fwd_iter_done( _cur ) ); /* It can't be empty because we just sampled an element from it. */
    1328       25248 :     sample = treap_fwd_iter_ele( _cur, pack->pool );
    1329             : 
    1330       25248 :     float score = multiplier * (float)sample->rewards / (float)sample->compute_est;
    1331       25248 :     worst = fd_ptr_if( score<worst_score, sample, worst );
    1332       25248 :     worst_score = fd_float_if( worst_score<score, worst_score, score );
    1333       25248 :   }
    1334             : 
    1335        3156 :   if( FD_UNLIKELY( !worst                      ) ) return 0;
    1336        3156 :   if( FD_UNLIKELY( threshold_score<worst_score ) ) return 0;
    1337             : 
    1338             :   /* The next eviction most likely takes worst's in-order successor;
    1339             :      warm what delete_transaction reads of it: the treap node, the
    1340             :      payload's account addresses, the metadata and the parsed txn. */
    1341        3123 :   treap_fwd_iter_t nxt = treap_fwd_iter_next( (treap_fwd_iter_t)treap_idx_fast( worst, pack->pool ), pack->pool );
    1342        3123 :   if( FD_LIKELY( !treap_fwd_iter_done( nxt ) ) ) {
    1343        3123 :     fd_pack_ord_txn_t const * n = pack->pool + nxt;
    1344        3123 :     __builtin_prefetch( &n->root,              0, 3 );
    1345        3123 :     __builtin_prefetch( &n->rewards,           0, 3 );
    1346        3123 :     __builtin_prefetch( n->txn->payload+ 64UL, 0, 3 );
    1347        3123 :     __builtin_prefetch( n->txn->payload+128UL, 0, 3 );
    1348        3123 :     __builtin_prefetch( &n->txn->payload_sz,   0, 3 );
    1349        3123 :     __builtin_prefetch( TXN( n->txn ),         0, 3 );
    1350        3123 :   }
    1351             : 
    1352        3123 :   return delete_transaction( pack, worst, 1, 1 );
    1353        3156 : }
    1354             : 
    1355             : static inline int
    1356             : validate_transaction( fd_pack_t               * pack,
    1357             :                       fd_pack_ord_txn_t const * ord,
    1358             :                       fd_txn_t          const * txn,
    1359             :                       fd_acct_addr_t    const * accts,
    1360             :                       fd_acct_addr_t    const * alt_adj,
    1361       35064 :                       int                       check_bundle_blacklist ) {
    1362       35064 :   int writes_to_sysvar = 0;
    1363       35064 :   for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    1364      121290 :       iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    1365       86226 :     writes_to_sysvar |= fd_pack_unwritable_contains( ACCT_ITER_TO_PTR( iter ) );
    1366       86226 :   }
    1367             : 
    1368       35064 :   int bundle_blacklist = 0;
    1369       35064 :   int acct_blocklist   = 0;
    1370       35064 :   for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_ALL );
    1371      251802 :       iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    1372      216738 :     bundle_blacklist |= (3==fd_pack_tip_prog_check_blacklist( ACCT_ITER_TO_PTR( iter ) ));
    1373             :     /* querying for the inval key is a violation of the fd_map
    1374             :        contract, even though it's actually fine... */
    1375      216738 :     acct_blocklist   |= (!acct_blocklist_key_inval( *ACCT_ITER_TO_PTR( iter ) )) &&
    1376      216738 :                         !!acct_blocklist_query( pack->acct_blocklist, *ACCT_ITER_TO_PTR( iter ), NULL );
    1377      216738 :   }
    1378             : 
    1379       35064 :   fd_acct_addr_t const * alt     = ord->txn_e->alt_accts;
    1380       35064 :   fd_chkdup_t * chkdup = pack->chkdup;
    1381       35064 :   ulong imm_cnt = fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1382       35064 :   ulong alt_cnt = fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_ALT );
    1383             : 
    1384             :   /* Throw out transactions ... */
    1385             :   /*           ... that are unfunded */
    1386       35064 :   if( FD_UNLIKELY( !fd_pack_can_fee_payer_afford( accts, ord->rewards    ) ) ) return FD_PACK_INSERT_REJECT_UNAFFORDABLE;
    1387             :   /*           ... that are so big they'll never run */
    1388       35064 :   if( FD_UNLIKELY( ord->compute_est >= pack->lim->max_cost_per_block       ) ) return FD_PACK_INSERT_REJECT_TOO_LARGE;
    1389             :   /*           ... that load too many accounts (ignoring 9LZdXeKGeBV6hRLdxS1rHbHoEUsKqesCC2ZAPTPKJAbK) */
    1390       35064 :   if( FD_UNLIKELY( fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_ALL )>64UL     ) ) return FD_PACK_INSERT_REJECT_ACCOUNT_CNT;
    1391             :   /*           ... that duplicate an account address */
    1392       35061 :   if( FD_UNLIKELY( fd_chkdup_check( chkdup, accts, imm_cnt, alt, alt_cnt ) ) ) return FD_PACK_INSERT_REJECT_DUPLICATE_ACCT;
    1393             :   /*           ... that try to write to a sysvar */
    1394       35058 :   if( FD_UNLIKELY( writes_to_sysvar                                        ) ) return FD_PACK_INSERT_REJECT_WRITES_SYSVAR;
    1395             :   /*           ... that use an account that violates bundle rules */
    1396       34965 :   if( FD_UNLIKELY( bundle_blacklist & !!check_bundle_blacklist             ) ) return FD_PACK_INSERT_REJECT_BUNDLE_BLACKLIST;
    1397             :   /*           ... that use a blocklisted account */
    1398       34965 :   if( FD_UNLIKELY( acct_blocklist                                          ) ) return FD_PACK_INSERT_REJECT_ACCT_BLOCKLIST;
    1399             : 
    1400       34950 :   return 0;
    1401       34965 : }
    1402             : 
    1403             : 
    1404             : 
    1405             : /* returns cumulative penalty "points", i.e. the sum of the populated
    1406             :    section of penalties (which also tells the caller how much of the
    1407             :    array is populated. */
    1408             : static inline ulong
    1409             : populate_bitsets( fd_pack_t         * pack,
    1410             :                   fd_pack_ord_txn_t * ord,
    1411             :                   ushort              penalties  [ static FD_TXN_ACCT_ADDR_MAX ],
    1412       33852 :                   uchar               penalty_idx[ static FD_TXN_ACCT_ADDR_MAX ] ) {
    1413       33852 :   FD_PACK_BITSET_CLEAR( ord->rw_bitset );
    1414       33852 :   FD_PACK_BITSET_CLEAR( ord->w_bitset  );
    1415             : 
    1416       33852 :   fd_txn_t * txn   = TXN(ord->txn);
    1417       33852 :   uchar * payload  = ord->txn->payload;
    1418             : 
    1419       33852 :   fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, payload );
    1420             :   /* alt_adj is the pointer to the ALT expansion, adjusted so that if
    1421             :      account address n is the first that comes from the ALT, it can be
    1422             :      accessed with adj_lut[n]. */
    1423       33852 :   fd_acct_addr_t const * alt_adj = ord->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1424             : 
    1425       33852 :   ulong  cumulative_penalty = 0UL;
    1426       33852 :   ulong  penalty_i          = 0UL;
    1427             : 
    1428             :   /* Scheduling this transaction looks every account up in acct_in_use,
    1429             :      whose slot for a fresh account is a cold line; warm them now. */
    1430       33852 :   {
    1431       33852 :     ulong uses_seed = acct_uses_seed( pack->acct_in_use );
    1432       33852 :     ulong uses_mask = acct_uses_slot_cnt( pack->acct_in_use )-1UL;
    1433       33852 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE|FD_TXN_ACCT_CAT_READONLY );
    1434      239718 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    1435      205866 :       ulong slot = acct_uses_key_hash( *ACCT_ITER_TO_PTR( iter ), uses_seed ) & uses_mask;
    1436      205866 :       __builtin_prefetch( pack->acct_in_use+slot, 0, 2 );
    1437      205866 :     }
    1438       33852 :   }
    1439             : 
    1440       33852 :   for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    1441      115254 :       iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    1442       81402 :     fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    1443       81402 :     fd_pack_bitset_acct_mapping_t * q = bitset_map_query( pack->acct_to_bitset, acct, NULL );
    1444       81402 :     if( FD_UNLIKELY( q==NULL ) ) {
    1445       57391 :       q = bitset_map_insert( pack->acct_to_bitset, acct );
    1446       57391 :       q->ref_cnt                  = 0UL;
    1447       57391 :       q->first_instance           = ord;
    1448       57391 :       q->first_instance_was_write = 1;
    1449       57391 :       q->bit                      = FD_PACK_BITSET_FIRST_INSTANCE;
    1450       57391 :     } else if( FD_UNLIKELY( q->bit == FD_PACK_BITSET_FIRST_INSTANCE ) ) {
    1451        1874 :       q->bit = pack->bitset_avail[ pack->bitset_avail_cnt ];
    1452        1874 :       pack->bitset_avail_cnt = fd_ulong_if( !!pack->bitset_avail_cnt, pack->bitset_avail_cnt-1UL, 0UL );
    1453             : 
    1454        1874 :       FD_PACK_BITSET_SETN( q->first_instance->rw_bitset, q->bit );
    1455        1874 :       if( q->first_instance_was_write ) FD_PACK_BITSET_SETN( q->first_instance->w_bitset, q->bit );
    1456        1874 :     }
    1457       81402 :     ulong penalty = fd_ulong_max( q->ref_cnt, PENALTY_TREAP_THRESHOLD )-PENALTY_TREAP_THRESHOLD;
    1458       81402 :     if( FD_UNLIKELY( penalty ) ) {
    1459       17667 :       penalties  [ penalty_i ] = (ushort)penalty;
    1460       17667 :       penalty_idx[ penalty_i ] = (uchar )fd_txn_acct_iter_idx( iter );
    1461       17667 :       penalty_i++;
    1462       17667 :       cumulative_penalty += penalty;
    1463       17667 :     }
    1464             : 
    1465       81402 :     q->ref_cnt++;
    1466       81402 :     FD_PACK_BITSET_SETN( ord->rw_bitset, q->bit );
    1467       81402 :     FD_PACK_BITSET_SETN( ord->w_bitset , q->bit );
    1468       81402 :   }
    1469             : 
    1470       33852 :   for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_READONLY );
    1471      158316 :       iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    1472             : 
    1473      124464 :     fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    1474      124464 :     if( FD_UNLIKELY( fd_pack_unwritable_contains( &acct ) ) ) continue;
    1475             : 
    1476       81759 :     fd_pack_bitset_acct_mapping_t * q = bitset_map_query( pack->acct_to_bitset, acct, NULL );
    1477       81759 :     if( FD_UNLIKELY( q==NULL ) ) {
    1478       24120 :       q = bitset_map_insert( pack->acct_to_bitset, acct );
    1479       24120 :       q->ref_cnt                  = 0UL;
    1480       24120 :       q->first_instance           = ord;
    1481       24120 :       q->first_instance_was_write = 0;
    1482       24120 :       q->bit                      = FD_PACK_BITSET_FIRST_INSTANCE;
    1483       57639 :     } else if( FD_UNLIKELY( q->bit == FD_PACK_BITSET_FIRST_INSTANCE ) ) {
    1484        3726 :       q->bit = pack->bitset_avail[ pack->bitset_avail_cnt ];
    1485        3726 :       pack->bitset_avail_cnt = fd_ulong_if( !!pack->bitset_avail_cnt, pack->bitset_avail_cnt-1UL, 0UL );
    1486             : 
    1487        3726 :       FD_PACK_BITSET_SETN( q->first_instance->rw_bitset, q->bit );
    1488        3726 :       if( q->first_instance_was_write ) FD_PACK_BITSET_SETN( q->first_instance->w_bitset, q->bit );
    1489        3726 :     }
    1490             : 
    1491       81759 :     q->ref_cnt++;
    1492       81759 :     FD_PACK_BITSET_SETN( ord->rw_bitset, q->bit );
    1493       81759 :   }
    1494       33852 :   return cumulative_penalty;
    1495       33852 : }
    1496             : 
    1497             : int
    1498             : fd_pack_insert_txn_fini( fd_pack_t  * pack,
    1499             :                          fd_txn_e_t * txne,
    1500             :                          ulong        expires_at,
    1501       32922 :                          ulong      * delete_cnt ) {
    1502       32922 :   *delete_cnt = 0UL;
    1503             : 
    1504       32922 :   fd_pack_ord_txn_t * ord = (fd_pack_ord_txn_t *)txne;
    1505             : 
    1506       32922 :   fd_txn_t * txn   = TXN(txne->txnp);
    1507       32922 :   uchar * payload  = txne->txnp->payload;
    1508             : 
    1509       32922 :   fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, payload );
    1510             :   /* alt_adj is the pointer to the ALT expansion, adjusted so that if
    1511             :      account address n is the first that comes from the ALT, it can be
    1512             :      accessed with adj_lut[n]. */
    1513       32922 :   fd_acct_addr_t const * alt_adj = ord->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1514             : 
    1515       32922 :   int est_result = fd_pack_estimate_rewards_and_compute( txne, ord, pack->lim );
    1516       32922 :   if( FD_UNLIKELY( !est_result ) ) REJECT( ESTIMATION_FAIL );
    1517             : 
    1518       32919 :   int nonce_result = fd_pack_validate_durable_nonce( txne );
    1519       32919 :   if( FD_UNLIKELY( !nonce_result ) ) REJECT( INVALID_NONCE );
    1520       32916 :   int is_durable_nonce = nonce_result==2;
    1521       32916 :   ord->txn->flags &= ~FD_TXN_P_FLAGS_DURABLE_NONCE;
    1522       32916 :   ord->txn->flags |= fd_uint_if( is_durable_nonce, FD_TXN_P_FLAGS_DURABLE_NONCE, 0U );
    1523             : 
    1524       32916 :   int validation_result = validate_transaction( pack, ord, txn, accts, alt_adj, !!pack->bundle_meta_sz );
    1525       32916 :   if( FD_UNLIKELY( validation_result ) ) {
    1526         114 :     trp_pool_ele_release( pack->pool, ord );
    1527         114 :     return validation_result;
    1528         114 :   }
    1529             : 
    1530             :   /* Reject any transactions that have already expired */
    1531       32802 :   if( FD_UNLIKELY( (!is_durable_nonce) & (expires_at<pack->expire_before )) ) REJECT( EXPIRED          );
    1532             : 
    1533       32781 :   ord->nonce_expires_at = fd_ulong_if( is_durable_nonce, expires_at, 0UL );
    1534             : 
    1535       32781 :   int replaces = 0;
    1536             :   /* If it's a durable nonce and we already have one, delete one or the
    1537             :      other. */
    1538       32781 :   if( FD_UNLIKELY( is_durable_nonce ) ) {
    1539         132 :     fd_pack_ord_txn_t * same_nonce = noncemap_ele_query( pack->noncemap, txne, NULL, pack->pool );
    1540         132 :     if( FD_LIKELY( same_nonce ) ) { /* Seems like most nonce transactions are effectively duplicates */
    1541         111 :       if( FD_LIKELY( same_nonce->root == FD_ORD_TXN_ROOT_PENDING_BUNDLE || (same_nonce->root & FD_ORD_TXN_ROOT_TAG_MASK) == FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE( 0 ) ||
    1542         111 :             same_nonce->nonce_expires_at>expires_at ||
    1543         111 :             (same_nonce->nonce_expires_at==expires_at && COMPARE_WORSE( ord, same_nonce ) ) ) ) REJECT( NONCE_PRIORITY );
    1544          99 :       ulong _delete_cnt = delete_transaction( pack, same_nonce, 0, 0 ); /* Not a bundle, so delete_full_bundle is 0 */
    1545          99 :       *delete_cnt += _delete_cnt;
    1546          99 :       replaces = 1;
    1547          99 :     }
    1548             :     /* Replace the expires_at value with a synthetic one to give nonce
    1549             :        transactions a finite lifetime. */
    1550         120 :     expires_at = pack->expire_before + FD_PACK_NONCE_SYNTHETIC_LIFETIME;
    1551         120 :   }
    1552             : 
    1553       32769 :   ord->expires_at = expires_at;
    1554             : 
    1555       32769 :   if( FD_UNLIKELY( pack->pending_txn_cnt == pack->pack_depth ) ) {
    1556        3156 :     float threshold_score = (float)ord->rewards/(float)ord->compute_est;
    1557        3156 :     ulong _delete_cnt = delete_worst( pack, threshold_score );
    1558        3156 :     *delete_cnt += _delete_cnt;
    1559        3156 :     if( FD_UNLIKELY( !_delete_cnt ) ) REJECT( PRIORITY );
    1560        3123 :     replaces = 1;
    1561        3123 :   }
    1562             : 
    1563       32736 :   ord->txn->flags &= ~(FD_TXN_P_FLAGS_BUNDLE | FD_TXN_P_FLAGS_INITIALIZER_BUNDLE);
    1564       32736 :   ord->skip = FD_PACK_SKIP_CNT;
    1565             : 
    1566             :   /* At this point, we know we have space to insert the transaction and
    1567             :      we've committed to insert it. */
    1568             : 
    1569             :   /* Since the pool uses ushorts, the size of the pool is < USHORT_MAX.
    1570             :      Each transaction can reference an account at most once, which means
    1571             :      that the total number of references for an account is < USHORT_MAX.
    1572             :      If these were ulongs, the array would be 512B, which is kind of a
    1573             :      lot to zero out.*/
    1574       32736 :   ushort penalties[ FD_TXN_ACCT_ADDR_MAX ] = {0};
    1575       32736 :   uchar  penalty_idx[ FD_TXN_ACCT_ADDR_MAX ];
    1576       32736 :   ulong cumulative_penalty = populate_bitsets( pack, ord, penalties, penalty_idx );
    1577             : 
    1578       32736 :   treap_t * insert_into = pack->pending;
    1579             : 
    1580       32736 :   if( FD_UNLIKELY( cumulative_penalty ) ) { /* Optimize for high parallelism case */
    1581             :     /* Compute a weighted random choice */
    1582        6159 :     ulong roll = (ulong)fd_rng_uint_roll( pack->rng, (uint)cumulative_penalty ); /* cumulative_penalty < USHORT_MAX*64 < UINT_MAX */
    1583        6159 :     ulong i = 0UL;
    1584             :     /* Find the right one.  This can be done in O(log N), but I imagine
    1585             :        N is normally so small that doesn't matter. */
    1586       11941 :     while( roll>=penalties[i] ) roll -= (ulong)penalties[i++];
    1587             : 
    1588        6159 :     fd_acct_addr_t penalty_acct = *ACCT_IDX_TO_PTR( penalty_idx[i] );
    1589        6159 :     fd_pack_penalty_treap_t * q = penalty_map_query( pack->penalty_treaps, penalty_acct, NULL );
    1590        6159 :     if( FD_UNLIKELY( q==NULL ) ) {
    1591          21 :       q = penalty_map_insert( pack->penalty_treaps, penalty_acct );
    1592          21 :       treap_new( q->penalty_treap, trp_pool_max( pack->pool ) );
    1593          21 :     }
    1594        6159 :     insert_into = q->penalty_treap;
    1595        6159 :     ord->root = FD_ORD_TXN_ROOT_PENALTY( penalty_idx[i] );
    1596       26577 :   } else {
    1597       26577 :     ord->root = FD_ORD_TXN_ROOT_PENDING;
    1598             : 
    1599       26577 :     pack->pending_smallest->cus   = fd_ulong_min( pack->pending_smallest->cus,   ord->compute_est       );
    1600       26577 :     pack->pending_smallest->bytes = fd_ulong_min( pack->pending_smallest->bytes, txne->txnp->payload_sz );
    1601       26577 :   }
    1602             : 
    1603       32736 :   pack->pending_txn_cnt++;
    1604             : 
    1605       32736 :   sig2txn_ele_insert( pack->signature_map, ord, pack->pool );
    1606             : 
    1607       32736 :   if( FD_UNLIKELY( is_durable_nonce ) ) noncemap_ele_insert( pack->noncemap, ord, pack->pool );
    1608             : 
    1609       32736 :   fd_pack_expq_t temp[ 1 ] = {{ .expires_at = expires_at, .txn = ord }};
    1610       32736 :   expq_insert( pack->expiration_q, temp );
    1611             : 
    1612       32736 :   treap_ele_insert( insert_into, ord, pack->pool );
    1613       32736 :   return (replaces<<1) | (is_durable_nonce<<2);
    1614       32769 : }
    1615             : #undef REJECT
    1616             : 
    1617             : fd_txn_e_t * const *
    1618             : fd_pack_insert_bundle_init( fd_pack_t          * pack,
    1619             :                             fd_txn_e_t *       * bundle,
    1620         708 :                             ulong                txn_cnt ) {
    1621         708 :   FD_TEST( txn_cnt<=FD_PACK_MAX_TXN_PER_BUNDLE  );
    1622         708 :   FD_TEST( trp_pool_free( pack->pool )>=txn_cnt );
    1623        2892 :   for( ulong i=0UL; i<txn_cnt; i++ ) bundle[ i ] = trp_pool_ele_acquire( pack->pool )->txn_e;
    1624         708 :   return bundle;
    1625         708 : }
    1626             : 
    1627             : void
    1628             : fd_pack_insert_bundle_cancel( fd_pack_t          * pack,
    1629             :                               fd_txn_e_t * const * bundle,
    1630         261 :                               ulong                txn_cnt ) {
    1631             :   /* There's no real reason these have to be released in reverse, but it
    1632             :      seems fitting to release them in the opposite order they were
    1633             :      acquired. */
    1634        1329 :   for( ulong i=0UL; i<txn_cnt; i++ ) trp_pool_ele_release( pack->pool, (fd_pack_ord_txn_t*)bundle[ txn_cnt-1UL-i ] );
    1635         261 : }
    1636             : 
    1637             : /* Explained below */
    1638             : #define BUNDLE_L_PRIME 37896771UL
    1639             : #define BUNDLE_N       313721UL
    1640         981 : #define RC_TO_REL_BUNDLE_IDX( r, c ) (BUNDLE_N - ((ulong)(r) * 1UL<<32)/((ulong)(c) * BUNDLE_L_PRIME))
    1641             : 
    1642             : /* bundle_txn_declared_tip returns the tip that this transaction sends
    1643             :    to the tip accounts using top-level System program transfers.
    1644             : 
    1645             :    This does not include tips paid during CPI calls. */
    1646             : static ulong
    1647         198 : bundle_txn_declared_tip( fd_pack_ord_txn_t const * ord ) {
    1648         198 :   fd_txn_t       const * txn     = TXN( ord->txn );
    1649         198 :   uchar          const * payload = ord->txn->payload;
    1650         198 :   fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, payload );
    1651         198 :   fd_acct_addr_t const * alt_adj = ord->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1652             : 
    1653         198 :   ulong tip = 0UL;
    1654         618 :   for( ulong i=0UL; i<(ulong)txn->instr_cnt; i++ ) {
    1655         420 :     fd_txn_instr_t const * instr = txn->instr+i;
    1656         420 :     uchar          const * data  = payload + instr->data_off;
    1657         420 :     if( FD_LIKELY( (instr->data_sz<12) | (instr->acct_cnt<2) || FD_LOAD( uint, data )!=2U ) ) continue;
    1658         186 :     if( FD_LIKELY( memcmp( accts[ instr->program_id ].b, &(uchar[32]){ 0 }, FD_TXN_ACCT_ADDR_SZ ) ) ) continue;
    1659         186 :     if( fd_pack_tip_is_tip_account( ACCT_IDX_TO_PTR( payload[ instr->acct_off+1UL ] ) ) ) tip = fd_ulong_sat_add( tip, FD_LOAD( ulong, data+4UL ) );
    1660         186 :   }
    1661         198 :   return tip;
    1662         198 : }
    1663             : 
    1664             : /* pre_rotation_bundle_worse returns 1 if bundle x has a smaller tip,
    1665             :    or the same tip but arrived later.  */
    1666             : static inline int
    1667             : pre_rotation_bundle_worse( fd_pack_pre_rotation_bundle_t const * x,
    1668         621 :                            fd_pack_pre_rotation_bundle_t const * y ) {
    1669         621 :   return (x->tip<y->tip) | ((x->tip==y->tip) & (x->seq>y->seq));
    1670         621 : }
    1671             : 
    1672             : static inline ulong
    1673          90 : pre_rotation_best_bundle_idx( fd_pack_t const * pack ) {
    1674          90 :   ulong best = ULONG_MAX;
    1675        1530 :   for( ulong i=0UL; i<FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY; i++ ) {
    1676        1440 :     if( !treap_ele_cnt( pack->pre_rotation_bundles[ i ].treap ) ) continue;
    1677         468 :     if( best==ULONG_MAX || pre_rotation_bundle_worse( pack->pre_rotation_bundles+best, pack->pre_rotation_bundles+i ) ) {
    1678         417 :       best = i;
    1679         417 :     }
    1680         468 :   }
    1681          90 :   return best;
    1682          90 : }
    1683             : 
    1684             : static inline ulong
    1685          15 : pre_rotation_worst_bundle_idx( fd_pack_t const * pack ) {
    1686          15 :   ulong worst = ULONG_MAX;
    1687         255 :   for( ulong i=0UL; i<FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY; i++ ) {
    1688         240 :     if( !treap_ele_cnt( pack->pre_rotation_bundles[ i ].treap ) ) continue;
    1689         240 :     if( worst==ULONG_MAX || pre_rotation_bundle_worse( pack->pre_rotation_bundles+i, pack->pre_rotation_bundles+worst ) ) {
    1690          60 :       worst = i;
    1691          60 :     }
    1692         240 :   }
    1693          15 :   return worst;
    1694          15 : }
    1695             : 
    1696             : static inline void
    1697             : pre_rotation_bundle_remove( fd_pack_t                     * pack,
    1698             :                             fd_pack_pre_rotation_bundle_t * pre_rotation_bundle,
    1699         108 :                             ulong                           idx ) {
    1700         108 :   treap_idx_remove( pre_rotation_bundle->treap, idx, pack->pool );
    1701         108 :   if( !treap_ele_cnt( pre_rotation_bundle->treap ) ) {
    1702          96 :     pack->pre_rotation_bundle_cnt--;
    1703          96 :   }
    1704         108 : }
    1705             : 
    1706             : int
    1707             : fd_pack_insert_bundle_fini( fd_pack_t          * pack,
    1708             :                             fd_txn_e_t * const * bundle,
    1709             :                             ulong                txn_cnt,
    1710             :                             ulong                expires_at,
    1711             :                             int                  initializer_bundle,
    1712             :                             void         const * bundle_meta,
    1713         708 :                             ulong              * delete_cnt ) {
    1714             : 
    1715         708 :   int err = 0;
    1716         708 :   *delete_cnt = 0UL;
    1717             : 
    1718         708 :   ulong pending_b_txn_cnt = treap_ele_cnt( pack->pending_bundles );
    1719         708 :   int is_pre_rotation     = (bundle[ 0 ]->txnp->scheduler_arrival_time_nanos>=pack->rotation_end_ns) & (!initializer_bundle);
    1720             :     /* We want to prevent bundles from consuming the whole treap, but in
    1721             :        general, we assume bundles are lucrative.  We'll set the policy
    1722             :        on capping bundles at half of the pack depth.  We assume that the
    1723             :        bundles are coming in a pre-prioritized order, so it doesn't make
    1724             :        sense to drop an earlier bundle for this one.  That means that
    1725             :        really, the best thing to do is drop this one. */
    1726         708 :   if( FD_UNLIKELY( (!initializer_bundle)&(pending_b_txn_cnt+txn_cnt>pack->pack_depth/2UL) ) ) err = FD_PACK_INSERT_REJECT_PRIORITY;
    1727             : 
    1728         708 :   if( FD_UNLIKELY( expires_at<pack->expire_before                                         ) ) err = FD_PACK_INSERT_REJECT_EXPIRED;
    1729             : 
    1730             :   /* Before evicting a transaction in favour of a pre-rotation
    1731             :      bundle, check that the bundle will actually be inserted into the
    1732             :      pre-rotation treap: it's valid and has a high enough tip.
    1733             : 
    1734             :      Otherwise, we could end up discarding a transaction with a
    1735             :      duplicate nonce, but because the conflicting bundle didn't
    1736             :      actually make it into the pre-rotation treap we would have
    1737             :      discarded the transaction unnecessarily. */
    1738         708 :   ulong pre_rotation_tip = 0UL;
    1739         708 :   fd_pack_pre_rotation_bundle_t cand[ 1 ] = {{ .tip = 0UL, .seq = pack->pre_rotation_seq }};
    1740         708 :   if( FD_UNLIKELY( is_pre_rotation & !err ) ) {
    1741         378 :     for( ulong i=0UL; i<txn_cnt; i++ ) {
    1742         198 :       pre_rotation_tip = fd_ulong_sat_add( pre_rotation_tip, bundle_txn_declared_tip( (fd_pack_ord_txn_t *)bundle[ i ] ) );
    1743         198 :     }
    1744         180 :     cand->tip = pre_rotation_tip;
    1745         180 :     if( FD_UNLIKELY( pack->pre_rotation_bundle_cnt>=FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY ) ) {
    1746             :       /* If we have to evict a pre-rotation bundle from the treap,
    1747             :          check that the new bundle we are inserting does in fact have a
    1748             :          higher tip than the lowest already in the treap. */
    1749          12 :       ulong worst = pre_rotation_worst_bundle_idx( pack );
    1750          12 :       if( FD_UNLIKELY( !pre_rotation_bundle_worse( pack->pre_rotation_bundles+worst, cand ) ) ) {
    1751           9 :         FD_MCNT_INC( PACK, PRE_ROTATION_BUNDLE_REJECTED, 1UL );
    1752           9 :         err = FD_PACK_INSERT_REJECT_PRIORITY;
    1753           9 :       }
    1754          12 :     }
    1755         180 :   }
    1756             : 
    1757         708 :   int   replaces      = 0;
    1758         708 :   ulong nonce_txn_cnt = 0UL;
    1759             : 
    1760             :   /* Collect nonce hashes to detect duplicate nonces.
    1761             :      Use a constant-time duplicate-detection algorithm -- Vacant entries
    1762             :      have the MSB set, occupied entries are the noncemap hash, with the
    1763             :      MSB set to 0. */
    1764         708 :   ulong nonce_hash63[ FD_PACK_MAX_TXN_PER_BUNDLE ];
    1765        4248 :   for( ulong i=0UL; i<FD_PACK_MAX_TXN_PER_BUNDLE; i++ ) {
    1766        3540 :     nonce_hash63[ i ] = ULONG_MAX-i;
    1767        3540 :   }
    1768             : 
    1769        2856 :   for( ulong i=0UL; (i<txn_cnt) && !err; i++ ) {
    1770        2154 :     fd_pack_ord_txn_t * ord = (fd_pack_ord_txn_t *)bundle[ i ];
    1771             : 
    1772        2154 :     fd_txn_t const * txn     = TXN(bundle[ i ]->txnp);
    1773        2154 :     uchar    const * payload = bundle[ i ]->txnp->payload;
    1774             : 
    1775        2154 :     fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, payload );
    1776        2154 :     fd_acct_addr_t const * alt_adj = ord->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1777             : 
    1778        2154 :     int est_result = fd_pack_estimate_rewards_and_compute( bundle[ i ], ord, pack->lim );
    1779        2154 :     if( FD_UNLIKELY( est_result==0 ) ) { err = FD_PACK_INSERT_REJECT_ESTIMATION_FAIL;  break; }
    1780        2154 :     int nonce_result = fd_pack_validate_durable_nonce( ord->txn_e );
    1781        2154 :     if( FD_UNLIKELY( !nonce_result ) ) { err = FD_PACK_INSERT_REJECT_INVALID_NONCE;    break; }
    1782             :     /* The expires_at field is interpreted differently for nonce vs.
    1783             :        non-nonce transactions, but bundles are required to have the same
    1784             :        value for that field, so we've lost the value we would put in
    1785             :        nonce_expires_at.  Turns out, that's never read for bundles
    1786             :        though.  So for now, we just use the incorrect expires_at.
    1787             :        If you're already getting revert protection from being a bundle,
    1788             :        it seems dumb to use a durable nonce as another form of revert
    1789             :        protection anyway.  We're expecting the sender of the bundles to
    1790             :        do the nonce filtering anyway. */
    1791        2154 :     int is_durable_nonce = nonce_result==2;
    1792        2154 :     nonce_txn_cnt += !!is_durable_nonce;
    1793             : 
    1794        2154 :     bundle[ i ]->txnp->flags |= FD_TXN_P_FLAGS_BUNDLE;
    1795        2154 :     bundle[ i ]->txnp->flags &= ~(FD_TXN_P_FLAGS_INITIALIZER_BUNDLE | FD_TXN_P_FLAGS_DURABLE_NONCE);
    1796        2154 :     bundle[ i ]->txnp->flags |= fd_uint_if( initializer_bundle, FD_TXN_P_FLAGS_INITIALIZER_BUNDLE, 0U );
    1797        2154 :     bundle[ i ]->txnp->flags |= fd_uint_if( is_durable_nonce,   FD_TXN_P_FLAGS_DURABLE_NONCE,      0U );
    1798        2154 :     ord->skip       = FD_PACK_SKIP_CNT;
    1799        2154 :     ord->expires_at = expires_at;
    1800             : 
    1801        2154 :     if( FD_UNLIKELY( is_durable_nonce ) ) {
    1802        1044 :       ord->nonce_expires_at = expires_at;
    1803        1044 :       nonce_hash63[ i ] = noncemap_key_hash( ord->txn_e, pack->noncemap->seed ) & 0x7FFFFFFFFFFFFFFFUL;
    1804        1044 :       fd_pack_ord_txn_t * same_nonce = noncemap_ele_query( pack->noncemap, ord->txn_e, NULL, pack->pool );
    1805        1044 :       if( FD_LIKELY( same_nonce ) ) {
    1806             :         /* bundles take priority over non-bundles, and bundles that run
    1807             :            sooner take priority over bundles that run later.
    1808             : 
    1809             :            Fresh bundles take priority over pre-rotation bundles, and
    1810             :            pre-rotation bundles with higher tips take priority over
    1811             :            pre-rotation bundles with lower tips. */
    1812          15 :         int holder_root     = same_nonce->root & FD_ORD_TXN_ROOT_TAG_MASK;
    1813          15 :         int holder_is_fresh = holder_root==FD_ORD_TXN_ROOT_PENDING_BUNDLE;
    1814          15 :         int holder_is_pre   = holder_root==FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE( 0 );
    1815          15 :         int holder_out_tips = (is_pre_rotation & holder_is_pre) && !pre_rotation_bundle_worse( pack->pre_rotation_bundles + FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE_IDX( same_nonce->root ), cand );
    1816          15 :         if( FD_UNLIKELY( holder_is_fresh | (holder_is_pre & holder_out_tips) ) ) {
    1817           6 :           err = FD_PACK_INSERT_REJECT_NONCE_PRIORITY;
    1818           6 :           break;
    1819           9 :         } else {
    1820           9 :           ulong _delete_cnt = delete_transaction( pack, same_nonce, 1, 0 );
    1821           9 :           *delete_cnt += _delete_cnt;
    1822           9 :           replaces = 1;
    1823           9 :         }
    1824          15 :       }
    1825        1044 :     }
    1826             : 
    1827        2148 :     int validation_result = validate_transaction( pack, ord, txn, accts, alt_adj, !initializer_bundle );
    1828        2148 :     if( FD_UNLIKELY( validation_result ) ) { err = validation_result; break; }
    1829        2148 :   }
    1830             : 
    1831         708 :   if( FD_UNLIKELY( err ) ) {
    1832          18 :     fd_pack_insert_bundle_cancel( pack, bundle, txn_cnt );
    1833          18 :     return err;
    1834          18 :   }
    1835             : 
    1836         690 :   if( FD_UNLIKELY( initializer_bundle && pending_b_txn_cnt>0UL ) ) {
    1837           0 :     treap_rev_iter_t _cur=treap_rev_iter_init( pack->pending_bundles, pack->pool );
    1838           0 :     FD_TEST( !treap_rev_iter_done( _cur ) );
    1839           0 :     fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pack->pool );
    1840           0 :     int is_ib = !!(cur->txn->flags & FD_TXN_P_FLAGS_INITIALIZER_BUNDLE);
    1841             : 
    1842             :     /* Delete the previous IB if there is one */
    1843           0 :     if( FD_UNLIKELY( is_ib && 0UL==RC_TO_REL_BUNDLE_IDX( cur->rewards, cur->compute_est ) ) ) {
    1844           0 :       ulong _delete_cnt = delete_transaction( pack, cur, 1, 0 );
    1845           0 :       *delete_cnt += _delete_cnt;
    1846           0 :     }
    1847           0 :   }
    1848             : 
    1849         690 :   while( FD_UNLIKELY( pack->pending_txn_cnt+txn_cnt > pack->pack_depth ) ) {
    1850           0 :     ulong _delete_cnt = delete_worst( pack, FLT_MAX );
    1851           0 :     *delete_cnt += _delete_cnt;
    1852           0 :     if( FD_UNLIKELY( !_delete_cnt ) ) {
    1853           0 :       fd_pack_insert_bundle_cancel( pack, bundle, txn_cnt );
    1854           0 :       return FD_PACK_INSERT_REJECT_PRIORITY;
    1855           0 :     }
    1856           0 :     replaces = 1;
    1857           0 :   }
    1858             : 
    1859         690 :   if( FD_UNLIKELY( !pending_b_txn_cnt ) ) {
    1860         678 :     pack->relative_bundle_idx = 1UL;
    1861         678 :   }
    1862             : 
    1863         690 :   if( FD_LIKELY( bundle_meta ) ) {
    1864           0 :     memcpy( (uchar *)pack->bundle_meta + (ulong)((fd_pack_ord_txn_t *)bundle[0]-pack->pool)*pack->bundle_meta_sz, bundle_meta, pack->bundle_meta_sz );
    1865           0 :   }
    1866             : 
    1867         690 :   if( FD_UNLIKELY( nonce_txn_cnt>1UL ) ) {
    1868             :     /* Do a ILP-friendly duplicate detect, naive O(n^2) algo.  With max
    1869             :        5 txns per bundle, this requires 10 comparisons.  ~ 25 cycle.  */
    1870         375 :     uint conflict_detected = 0u;
    1871        1875 :     for( ulong i=0UL; i<FD_PACK_MAX_TXN_PER_BUNDLE-1; i++ ) {
    1872        5250 :       for( ulong j=i+1; j<FD_PACK_MAX_TXN_PER_BUNDLE; j++ ) {
    1873        3750 :         ulong const ele_i = nonce_hash63[ i ];
    1874        3750 :         ulong const ele_j = nonce_hash63[ j ];
    1875        3750 :         conflict_detected |= (ele_i==ele_j);
    1876        3750 :       }
    1877        1500 :     }
    1878         375 :     if( FD_UNLIKELY( conflict_detected ) ) {
    1879         243 :       fd_pack_insert_bundle_cancel( pack, bundle, txn_cnt );
    1880         243 :       return FD_PACK_INSERT_REJECT_NONCE_CONFLICT;
    1881         243 :     }
    1882         375 :   }
    1883             : 
    1884             :   /* If the bundle is a pre-rotation bundle, insert it into the
    1885             :      pre-rotation treap. */
    1886         447 :   if( FD_UNLIKELY( is_pre_rotation ) ) {
    1887         168 :     ulong evicted = insert_pre_rotation_bundle_impl( pack, txn_cnt, (fd_pack_ord_txn_t * *)bundle, expires_at, pre_rotation_tip );
    1888         168 :     *delete_cnt += evicted;
    1889         168 :     replaces    |= evicted>0UL;
    1890         168 :     return (0) | (replaces<<1) | ((!!nonce_txn_cnt)<<2);
    1891         168 :   }
    1892             : 
    1893             :   /* We put bundles in a treap just like all the other transactions, but
    1894             :      we actually want to sort them in a very specific order; the order
    1895             :      within the bundle is determined at bundle creation time, and the
    1896             :      order among the bundles is FIFO.  However, it's going to be a pain
    1897             :      to use a different sorting function for this treap, since it's
    1898             :      fixed as part of the treap creation for performance.  Don't fear
    1899             :      though; we can pull a cool math trick out of the bag to shoehorn
    1900             :      the order we'd like into the sort function we need, and to get even
    1901             :      more.
    1902             : 
    1903             :      Recall that the sort function is r_i/c_i, smallest to largest,
    1904             :      where r_i is the rewards and c_i is the cost units.  r_i and c_i
    1905             :      are both uints, and the comparison is done by cross-multiplication
    1906             :      as ulongs.  We actually use the c_i value for testing if
    1907             :      transactions fit, etc.  so let's assume that's fixed, and we know
    1908             :      it's in the range [1020, 1,551,570].
    1909             : 
    1910             :      This means, if c_0, c_1, ... c_4 are the CU costs of the
    1911             :      transactions in the first bundle, we require r_0/c_0 > r_1/c_1 >
    1912             :      ... > r_4/c_4.  Then, if c_5, ... c_9 are the CU costs of the
    1913             :      transactions in the second bundle, we also require that r_4/c_4 >
    1914             :      r_5/c_5.  For convenience, we'll impose a slightly stronger
    1915             :      constraint: we want the kth bundle to obey L*(N-k) <= r_i/c_i <
    1916             :      L*(N+1-k), for fixed constants L and N, real and integer,
    1917             :      respectively, that we'll determine. For example, this means r_4/c_4
    1918             :      >= L*N > r_5/c_5.  This enables us to group the transactions in the
    1919             :      same bundle more easily.
    1920             : 
    1921             :      For convenience in the math below, we'll set j=N-k and relabel the
    1922             :      transactions from the jth bundle c_0, ... c_4.
    1923             :      From above, we know that Lj <= r_4/c_4.  We'd like to make it as
    1924             :      close as possible given that r_4 is an integers.  Thus, put
    1925             :      r_4 = ceil( c_4 * Lj ).  r_4 is clearly an integer, and it satisfies
    1926             :      the required inequality because:
    1927             :             r_4/c_4 = ceil( c_4 * Lj)/c_4 >= c_4*Lj / c_4 >= Lj.
    1928             : 
    1929             :      Following in the same spirit, put r_3 = ceil( c_3 * (r_4+1)/c_4 ).
    1930             :      Again, r_3 is clearly an integer, and
    1931             :                 r_3/c_3  = ceil(c_3*(r_4+1)/c_4)/c_3
    1932             :                         >= (c_3*(r_4+1))/(c_3 * c_4)
    1933             :                         >= r_4/c_4 + 1/c_4
    1934             :                         >  r_4/c_4.
    1935             :      Following the pattern, we put
    1936             :                 r_2 = ceil( c_2 * (r_3+1)/c_3 )
    1937             :                 r_1 = ceil( c_1 * (r_2+1)/c_2 )
    1938             :                 r_0 = ceil( c_0 * (r_1+1)/c_1 )
    1939             :      which work for the same reason that as r_3.
    1940             : 
    1941             :      We now need for r_0 to satisfy the final inequality with L, and
    1942             :      we'll use this to guide our choice of L.  Theoretically, r_0 can be
    1943             :      expressed in terms of L, j, and c_0, ... c_4, but that's a truly
    1944             :      inscrutible expression.  Instead, we need some bounds so we can get
    1945             :      rid of all the ceil using the property that x <= ceil(x) < x+1.
    1946             :                      c_4 * Lj <= r_4 < c_4 * Lj + 1
    1947             :      The lower bound on r_3 is easy:
    1948             :          r_3 >= c_3 * (c_4 * Lj + 1)/c_4 = c_3 * Lj + c_3/c_4
    1949             :      For the upper bound,
    1950             :          r_3 < 1 + c_3*(r_4+1)/c_4 < 1 + c_3*(c_4*Lj+1 + 1)/c_4
    1951             :                                    = 1 + c_3 * Lj + 2*c_3/c_4
    1952             :      Continuing similarly gives
    1953             :        c_2*Lj +                     c_2/c_3 + c_2/c_4 <= r_2
    1954             :        c_1*Lj +           c_1/c_2 + c_1/c_c + c_1/c_4 <= r_1
    1955             :        c_0*Lj + c_0/c_1 + c_0/c_2 + c_0/c_3 + c_0/c_4 <= r_0
    1956             :      and
    1957             :        r_2 < 1 + c_2*Lj +                       2c_2/c_3 + 2c_2/c_4
    1958             :        r_1 < 1 + c_1*Lj +            2c_1/c_2 + 2c_1/c_3 + 2c_1/c_4
    1959             :        r_0 < 1 + c_0*Lj + 2c_0/c_1 + 2c_0/c_2 + 2c_0/c_3 + 2c_0/c_4.
    1960             : 
    1961             :      Setting L(j+1)>=(1 + c_0*Lj+2c_0/c_1+2c_0/c_2+2c_0/c_3+2c_0/c_4)/c_0
    1962             :      is then sufficient to ensure the whole sequence of 5 fits between Lj
    1963             :      and L(j+1).  Simplifying gives
    1964             :               L<= 1/c_0 + 2/c_1 + 2/c_2 + 2/c_3 + 2/c_4
    1965             :      but L must be a constant and not depend on individual values of c_i,
    1966             :      so, given that c_i >= 1020, we set L = 9/1020.
    1967             : 
    1968             :      Now all that remains is to determine N.  It's a bit unfortunate
    1969             :      that we require N, since it limits our capacity, but it's necessary
    1970             :      in any system that tries to compute priorities to enforce a FIFO
    1971             :      order.  If we've inserted more than N bundles without ever having
    1972             :      the bundle treap go empty, we'll briefly break the FIFO ordering as
    1973             :      we underflow.
    1974             : 
    1975             :      Thus, we'd like to make N as big as possible, avoiding overflow.
    1976             :      r_0, ..., r_4 are all uints, and taking the bounds from above,
    1977             :      given that for any i, i' c_i/c_{i'} <= 1551570/1020 < 1522, we have
    1978             :                r_i < 1 + 1551570 * Lj + 8*1522.
    1979             :      To avoid overflow, we assert the right-hand side is < 2^32, which
    1980             :      implies N <= 313721.
    1981             : 
    1982             :      We want to use a fixed point representation for L so that the
    1983             :      entire computation can be done with integer arithmetic.  We can do
    1984             :      the arithmetic as ulongs, which means defining L' >= L * 2^s, and
    1985             :      we compute ceil( c_4*Lj ) as floor( (c_4 * L' * j + 2^s - 1)/2^s ),
    1986             :      so c_4 * L' * j + 2^s should fit in a ulong.  With j<=N, this gives
    1987             :      s<=32, so we set s=32, which means L' = 37896771 >= 9/1020 * 2^32.
    1988             :      Note that 1 + 1551570 * L' * N + 8*1522 + 2^32 is approximately
    1989             :      2^63.999992.
    1990             : 
    1991             :      Note that this is all checked by a proof of the code translated
    1992             :      into Z3.  Unfortunately CBMC was too slow to prove this code
    1993             :      directly. */
    1994         279 :      FD_STATIC_ASSERT( FD_PACK_MIN_TXN_COST==   1020UL, adjust_constants );
    1995         279 :      FD_STATIC_ASSERT( FD_PACK_MAX_TXN_COST==1551570UL, adjust_constants );
    1996        1428 : #define BUNDLE_L_PRIME 37896771UL
    1997        1428 : #define BUNDLE_N       313721UL
    1998             : 
    1999         279 :   if( FD_UNLIKELY( pack->relative_bundle_idx>BUNDLE_N ) ) {
    2000           0 :     FD_LOG_WARNING(( "Too many bundles inserted without allowing pending bundles to go empty. "
    2001           0 :                      "Ordering of bundles may be incorrect." ));
    2002           0 :     pack->relative_bundle_idx = 1UL;
    2003           0 :   }
    2004         279 :   ulong bundle_idx = fd_ulong_if( initializer_bundle, 0UL, pack->relative_bundle_idx );
    2005         279 :   insert_bundle_impl( pack, bundle_idx, txn_cnt, (fd_pack_ord_txn_t * *)bundle, expires_at );
    2006             :   /* if IB this is max( 1, x ), which is x.  Otherwise, this is max(x,
    2007             :      x+1) which is x++ */
    2008         279 :   pack->relative_bundle_idx = fd_ulong_max( bundle_idx+1UL, pack->relative_bundle_idx );
    2009             : 
    2010         279 :   return (0) | (replaces<<1) | ((!!nonce_txn_cnt)<<2);
    2011         447 : }
    2012             : static inline void
    2013             : insert_bundle_impl( fd_pack_t           * pack,
    2014             :                     ulong                 bundle_idx,
    2015             :                     ulong                 txn_cnt,
    2016             :                     fd_pack_ord_txn_t * * bundle,
    2017         279 :                     ulong                 expires_at ) {
    2018         279 :   ulong prev_reward = ((BUNDLE_L_PRIME * (BUNDLE_N - bundle_idx))) - 1UL;
    2019         279 :   ulong prev_cost = 1UL<<32;
    2020             : 
    2021             :   /* Assign last to first */
    2022        1212 :   for( ulong i=0UL; i<txn_cnt; i++ ) {
    2023         933 :     fd_pack_ord_txn_t * ord = bundle[ txn_cnt-1UL - i ];
    2024         933 :     ord->rewards = (uint)(((ulong)ord->compute_est * (prev_reward + 1UL) + prev_cost-1UL)/prev_cost);
    2025         933 :     ord->root    = FD_ORD_TXN_ROOT_PENDING_BUNDLE;
    2026         933 :     prev_reward = ord->rewards;
    2027         933 :     prev_cost   = ord->compute_est;
    2028             : 
    2029             :     /* The penalty information isn't used for bundles. */
    2030         933 :     ushort penalties  [ FD_TXN_ACCT_ADDR_MAX ];
    2031         933 :     uchar  penalty_idx[ FD_TXN_ACCT_ADDR_MAX ];
    2032         933 :     populate_bitsets( pack, ord, penalties, penalty_idx );
    2033             : 
    2034         933 :     treap_ele_insert( pack->pending_bundles, ord, pack->pool );
    2035         933 :     pack->pending_txn_cnt++;
    2036             : 
    2037         933 :     if( FD_UNLIKELY( ord->txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE ) ) noncemap_ele_insert( pack->noncemap, ord, pack->pool );
    2038         933 :     sig2txn_ele_insert( pack->signature_map, ord, pack->pool );
    2039             : 
    2040         933 :     fd_pack_expq_t temp[ 1 ] = {{ .expires_at = expires_at, .txn = ord }};
    2041         933 :     expq_insert( pack->expiration_q, temp );
    2042         933 :   }
    2043             : 
    2044         279 : }
    2045             : 
    2046             : /* insert_pre_rotation_bundle_impl is like insert_bundle_impl, but puts
    2047             :    the bundle in a free entry of pre_rotation_bundles.  If none is
    2048             :    free, it first evicts the worst bundle.  Returns the number of txns
    2049             :    evicted. */
    2050             : static inline ulong
    2051             : insert_pre_rotation_bundle_impl( fd_pack_t           * pack,
    2052             :                                  ulong                 txn_cnt,
    2053             :                                  fd_pack_ord_txn_t * * bundle,
    2054             :                                  ulong                 expires_at,
    2055         168 :                                  ulong                 pre_rotation_tip ) {
    2056             :   /* Evict from the pre-rotation treap if we have reached the limit */
    2057         168 :   ulong evicted = 0UL;
    2058         168 :   if( FD_UNLIKELY( pack->pre_rotation_bundle_cnt>=FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY ) ) {
    2059           3 :     treap_t           * worst_treap = pack->pre_rotation_bundles[ pre_rotation_worst_bundle_idx( pack ) ].treap;
    2060           3 :     fd_pack_ord_txn_t * worst       = treap_fwd_iter_ele( treap_fwd_iter_init( worst_treap, pack->pool ), pack->pool );
    2061           3 :     evicted = delete_transaction( pack, worst, 1, 0 );
    2062           3 :     FD_MCNT_INC( PACK, PRE_ROTATION_BUNDLE_EVICTED, 1UL );
    2063           3 :   }
    2064             : 
    2065         168 :   ulong pre_rotation_bundle_idx = 0UL;
    2066         939 :   while( treap_ele_cnt( pack->pre_rotation_bundles[ pre_rotation_bundle_idx ].treap ) ) {
    2067         771 :     pre_rotation_bundle_idx++;
    2068         771 :   }
    2069         168 :   fd_pack_pre_rotation_bundle_t * pre_rotation_bundle = pack->pre_rotation_bundles + pre_rotation_bundle_idx;
    2070         168 :   pre_rotation_bundle->tip = pre_rotation_tip;
    2071         168 :   pre_rotation_bundle->seq = pack->pre_rotation_seq++;
    2072             : 
    2073         168 :   ulong prev_reward = ((BUNDLE_L_PRIME * (BUNDLE_N - 1UL))) - 1UL;
    2074         168 :   ulong prev_cost   = 1UL<<32;
    2075             : 
    2076             :   /* Assign last to first */
    2077         351 :   for( ulong i=0UL; i<txn_cnt; i++ ) {
    2078         183 :     fd_pack_ord_txn_t * ord = bundle[ txn_cnt-1UL - i ];
    2079         183 :     ord->rewards = (uint)(((ulong)ord->compute_est * (prev_reward + 1UL) + prev_cost-1UL)/prev_cost);
    2080         183 :     ord->root    = FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE( (int)pre_rotation_bundle_idx );
    2081         183 :     prev_reward  = ord->rewards;
    2082         183 :     prev_cost    = ord->compute_est;
    2083             : 
    2084             :     /* The penalty information isn't used for bundles. */
    2085         183 :     ushort penalties  [ FD_TXN_ACCT_ADDR_MAX ];
    2086         183 :     uchar  penalty_idx[ FD_TXN_ACCT_ADDR_MAX ];
    2087         183 :     populate_bitsets( pack, ord, penalties, penalty_idx );
    2088             : 
    2089         183 :     treap_ele_insert( pre_rotation_bundle->treap, ord, pack->pool );
    2090         183 :     pack->pending_txn_cnt++;
    2091             : 
    2092         183 :     if( FD_UNLIKELY( ord->txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE ) ) noncemap_ele_insert( pack->noncemap, ord, pack->pool );
    2093         183 :     sig2txn_ele_insert( pack->signature_map, ord, pack->pool );
    2094             : 
    2095         183 :     fd_pack_expq_t temp[ 1 ] = {{ .expires_at = expires_at, .txn = ord }};
    2096         183 :     expq_insert( pack->expiration_q, temp );
    2097         183 :   }
    2098             : 
    2099         168 :   pack->pre_rotation_bundle_cnt++;
    2100         168 :   FD_MCNT_INC( PACK, PRE_ROTATION_BUNDLE_INSERTED, 1UL );
    2101         168 :   return evicted;
    2102         168 : }
    2103             : 
    2104             : void const *
    2105           6 : fd_pack_peek_bundle_meta( fd_pack_t const * pack ) {
    2106           6 :   int ib_state = pack->initializer_bundle_state;
    2107           6 :   if( FD_UNLIKELY( (ib_state==FD_PACK_IB_STATE_PENDING) | (ib_state==FD_PACK_IB_STATE_FAILED) ) ) return NULL;
    2108             : 
    2109           6 :   treap_rev_iter_t _cur=treap_rev_iter_init( pack->pending_bundles, pack->pool );
    2110             :   /* If there are no normal bundles, the pre-rotation bundles will
    2111             :      be scheduled. */
    2112           6 :   if( FD_UNLIKELY( treap_rev_iter_done( _cur ) ) ) {
    2113           3 :     ulong best = pre_rotation_best_bundle_idx( pack );
    2114           3 :     if( FD_UNLIKELY( best==ULONG_MAX ) ) return NULL;
    2115           3 :     _cur = treap_rev_iter_init( pack->pre_rotation_bundles[ best ].treap, pack->pool );
    2116           3 :   }
    2117           6 :   if( FD_UNLIKELY( treap_rev_iter_done( _cur ) ) ) return NULL; /* empty */
    2118             : 
    2119           6 :   fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pack->pool );
    2120           6 :   int is_ib = !!(cur->txn->flags & FD_TXN_P_FLAGS_INITIALIZER_BUNDLE);
    2121           6 :   if( FD_UNLIKELY( is_ib ) ) return NULL;
    2122             : 
    2123           3 :   return (void const *)((uchar const *)pack->bundle_meta + (ulong)_cur * pack->bundle_meta_sz);
    2124           6 : }
    2125             : 
    2126             : void
    2127         162 : fd_pack_set_initializer_bundles_ready( fd_pack_t * pack ) {
    2128         162 :   pack->initializer_bundle_state = FD_PACK_IB_STATE_READY;
    2129         162 : }
    2130             : 
    2131             : void
    2132             : fd_pack_set_rotation_end_ns( fd_pack_t * pack,
    2133         618 :                              long        end_ns ) {
    2134         618 :   pack->rotation_end_ns = end_ns;
    2135         618 : }
    2136             : 
    2137             : void
    2138          63 : fd_pack_metrics_write( fd_pack_t const * pack ) {
    2139          63 :   ulong pending_regular      = treap_ele_cnt( pack->pending         );
    2140          63 :   ulong pending_bundle       = treap_ele_cnt( pack->pending_bundles );
    2141        1071 :   for( ulong i=0UL; i<FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY; i++ ) {
    2142        1008 :     pending_bundle += treap_ele_cnt( pack->pre_rotation_bundles[ i ].treap );
    2143        1008 :   }
    2144          63 :   ulong pending_pre_rotation = pack->pre_rotation_bundle_cnt;
    2145          63 :   ulong conflicting          = pack->pending_txn_cnt - pending_regular - pending_bundle;
    2146          63 :   ulong smallest_cost        = fd_ulong_if( pack->pending_smallest->cus==ULONG_MAX, 0UL, pack->pending_smallest->cus );
    2147          63 :   FD_MGAUGE_SET( PACK, TXN_PENDING_USED_REGULAR,     pending_regular             );
    2148          63 :   FD_MGAUGE_SET( PACK, TXN_PENDING_USED_VOTE,        0UL                         );
    2149          63 :   FD_MGAUGE_SET( PACK, TXN_PENDING_USED_CONFLICTING, conflicting                 );
    2150          63 :   FD_MGAUGE_SET( PACK, TXN_PENDING_USED_BUNDLE,      pending_bundle              );
    2151          63 :   FD_MGAUGE_SET( PACK, PRE_ROTATION_BUNDLE_PENDING,  pending_pre_rotation        );
    2152          63 :   FD_MGAUGE_SET( PACK, TXN_PENDING_SMALLEST_COST,    smallest_cost               );
    2153          63 :   FD_MGAUGE_SET( PACK, BLOCK_COST,                   pack->cumulative_block_cost );
    2154             : 
    2155          63 :   FD_MCNT_ENUM_COPY( PACK, TXN_SCHEDULE_ATTEMPTED, pack->sched_results );
    2156          63 : }
    2157             : 
    2158             : void
    2159           0 : fd_pack_get_sched_metrics( fd_pack_t const * pack, ulong * metrics ) {
    2160           0 :   fd_memcpy( metrics, pack->sched_results, sizeof(pack->sched_results) );
    2161           0 : }
    2162             : 
    2163             : typedef struct {
    2164             :   ushort clear_rw_bit;
    2165             :   ushort clear_w_bit;
    2166             : } release_result_t;
    2167             : 
    2168             : static inline release_result_t
    2169             : release_bit_reference( fd_pack_t            * pack,
    2170      156519 :                        fd_acct_addr_t const * acct ) {
    2171             : 
    2172      156519 :   fd_pack_bitset_acct_mapping_t * q = bitset_map_query( pack->acct_to_bitset, *acct, NULL );
    2173      156519 :   FD_TEST( q ); /* q==NULL not be possible */
    2174             : 
    2175      156519 :   q->ref_cnt--;
    2176             : 
    2177      156519 :   if( FD_UNLIKELY( q->ref_cnt==0UL ) ) {
    2178       75148 :     ushort bit = q->bit;
    2179       75148 :     bitset_map_remove( pack->acct_to_bitset, q );
    2180       75148 :     if( FD_LIKELY( bit<FD_PACK_BITSET_MAX ) ) pack->bitset_avail[ ++(pack->bitset_avail_cnt) ] = bit;
    2181             : 
    2182       75148 :     fd_pack_addr_use_t * use = acct_uses_query( pack->acct_in_use,  *acct, NULL );
    2183       75148 :     if( FD_LIKELY( use ) ) {
    2184       69787 :       use->in_use_by |= FD_PACK_IN_USE_BIT_CLEARED;
    2185       69787 :       release_result_t ret = { .clear_rw_bit = bit,
    2186       69787 :                                .clear_w_bit = fd_ushort_if( !!(use->in_use_by & FD_PACK_IN_USE_WRITABLE), bit, FD_PACK_BITSET_MAX ) };
    2187       69787 :       return ret;
    2188       69787 :     }
    2189       75148 :   }
    2190       86732 :   release_result_t ret = { .clear_rw_bit = FD_PACK_BITSET_MAX, .clear_w_bit = FD_PACK_BITSET_MAX };
    2191       86732 :   return ret;
    2192      156519 : }
    2193             : 
    2194             : typedef struct {
    2195             :   ulong cus_scheduled;
    2196             :   ulong txns_scheduled;
    2197             :   ulong bytes_scheduled;
    2198             :   ulong alloc_scheduled;
    2199             : } sched_return_t;
    2200             : 
    2201             : static inline sched_return_t
    2202             : fd_pack_schedule_impl( fd_pack_t          * pack,
    2203             :                        treap_t            * sched_from,
    2204             :                        ulong                cu_limit,
    2205             :                        ulong                txn_limit,
    2206             :                        ulong                byte_limit,
    2207             :                        ulong                alloc_limit,
    2208             :                        ulong                bank_tile,
    2209             :                        fd_pack_smallest_t * smallest_in_treap,
    2210             :                        ulong              * use_by_bank_txn,
    2211       14841 :                        fd_txn_e_t         * out ) {
    2212       14841 :   if( FD_UNLIKELY( (cu_limit<smallest_in_treap->cus) | (txn_limit==0UL) | (byte_limit<smallest_in_treap->bytes) ) ) {
    2213         176 :     sched_return_t to_return = { .cus_scheduled = 0UL, .txns_scheduled = 0UL, .bytes_scheduled = 0UL };
    2214         176 :     return to_return;
    2215         176 :   }
    2216             : 
    2217       14665 :   fd_pack_ord_txn_t   * pool         = pack->pool;
    2218       14665 :   fd_pack_addr_use_t  * acct_in_use  = pack->acct_in_use;
    2219       14665 :   wcost_map_t         * writer_costs = pack->writer_costs;
    2220       14665 :   fd_pack_wcost_ele_t * writers      = pack->writers;
    2221       14665 :   wcost_dlist_t       * written_list = pack->written_list;
    2222             : 
    2223       14665 :   FD_PACK_BITSET_DECLARE( bitset_rw_in_use );
    2224       14665 :   FD_PACK_BITSET_DECLARE( bitset_w_in_use  );
    2225       14665 :   FD_PACK_BITSET_COPY( bitset_rw_in_use, pack->bitset_rw_in_use );
    2226       14665 :   FD_PACK_BITSET_COPY( bitset_w_in_use,  pack->bitset_w_in_use  );
    2227             : 
    2228       14665 :   fd_pack_addr_use_t * use_by_bank     = pack->use_by_bank    [bank_tile];
    2229       14665 :   ulong                use_by_bank_cnt = pack->use_by_bank_cnt[bank_tile];
    2230             : 
    2231       14665 :   ulong max_write_cost_per_acct = pack->lim->max_write_cost_per_acct;
    2232             : 
    2233       14665 :   ushort compressed_slot_number = pack->compressed_slot_number;
    2234             : 
    2235       14665 :   ulong txns_scheduled  = 0UL;
    2236       14665 :   ulong cus_scheduled   = 0UL;
    2237       14665 :   ulong bytes_scheduled = 0UL;
    2238       14665 :   ulong alloc_scheduled = 0UL;
    2239             : 
    2240       14665 :   ulong bank_tile_mask = 1UL << bank_tile;
    2241             : 
    2242       14665 :   ulong fast_path     = 0UL;
    2243       14665 :   ulong slow_path     = 0UL;
    2244       14665 :   ulong cu_limit_c    = 0UL;
    2245       14665 :   ulong byte_limit_c  = 0UL;
    2246       14665 :   ulong alloc_limit_c = 0UL;
    2247       14665 :   ulong write_limit_c = 0UL;
    2248       14665 :   ulong skip_c        = 0UL;
    2249             : 
    2250       14665 :   ulong min_cus   = ULONG_MAX;
    2251       14665 :   ulong min_bytes = ULONG_MAX;
    2252             : 
    2253       14665 :   treap_rev_iter_t prev = treap_idx_null();
    2254      240753 :   for( treap_rev_iter_t _cur=treap_rev_iter_init( sched_from, pool ); !treap_rev_iter_done( _cur ); _cur=prev ) {
    2255             :     /* Capture next so that we can delete while we iterate. */
    2256      228901 :     prev = treap_rev_iter_next( _cur, pool );
    2257             : 
    2258      228901 : #   if FD_HAS_X86
    2259      228901 :     _mm_prefetch( &(pool[ prev ].prev),      _MM_HINT_T0 );
    2260      228901 : #   endif
    2261             : 
    2262      228901 :     fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pool );
    2263             : 
    2264      228901 :     min_cus   = fd_ulong_min( min_cus,   cur->compute_est     );
    2265      228901 :     min_bytes = fd_ulong_min( min_bytes, cur->txn->payload_sz );
    2266             : 
    2267      228901 :     ulong conflicts = 0UL;
    2268             : 
    2269      228901 :     if( FD_UNLIKELY( cur->compute_est>cu_limit ) ) {
    2270             :       /* Too big to be scheduled at the moment, but might be okay for
    2271             :          the next microblock, so we don't want to delay it. */
    2272           0 :       cu_limit_c++;
    2273           0 :       continue;
    2274           0 :     }
    2275             : 
    2276      228901 :     if( FD_UNLIKELY( cur->txn->pack_alloc>alloc_limit ) ) {
    2277             :       /* We don't want to consider this until the next block, but
    2278             :          checking alloc is as cheap as checking cur->skip, so there's
    2279             :          not a big difference. */
    2280          18 :       alloc_limit_c++;
    2281          18 :       continue;
    2282          18 :     }
    2283             : 
    2284             :     /* Likely? Unlikely? */
    2285      228883 :     if( FD_LIKELY( !FD_PACK_BITSET_INTERSECT4_EMPTY( bitset_rw_in_use, bitset_w_in_use, cur->w_bitset, cur->rw_bitset ) ) ) {
    2286      202795 :       fast_path++;
    2287      202795 :       continue;
    2288      202795 :     }
    2289             : 
    2290       26088 :     if( FD_UNLIKELY( cur->skip==compressed_slot_number ) ) {
    2291           0 :       skip_c++;
    2292           0 :       continue;
    2293           0 :     }
    2294             : 
    2295             :     /* If skip>FD_PACK_MAX_SKIP but not compressed_slot_number, it means
    2296             :        it's the compressed slot number of a previous slot.  We don't
    2297             :        care unless we're going to update the value though, so we don't
    2298             :        need to eagerly reset it to FD_PACK_MAX_SKIP.
    2299             :        compressed_slot_number is a ushort, so it's possible for it to
    2300             :        roll over, but the transaction lifetime is much shorter than
    2301             :        that, so it won't be a problem. */
    2302             : 
    2303       26088 :     if( FD_UNLIKELY( cur->txn->payload_sz>byte_limit ) ) {
    2304           6 :       byte_limit_c++;
    2305           6 :       continue;
    2306           6 :     }
    2307             : 
    2308             : 
    2309       26082 :     fd_txn_t const * txn = TXN(cur->txn);
    2310       26082 :     fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, cur->txn->payload );
    2311       26082 :     fd_acct_addr_t const * alt_adj = cur->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    2312             :     /* Check conflicts between this transaction's writable accounts and
    2313             :        current readers */
    2314       26082 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    2315       84396 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2316             : 
    2317       58317 :       fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    2318             : 
    2319       58317 :       fd_pack_wcost_ele_t const * in_wcost_table = wcost_map_ele_query_const( writer_costs, &acct, NULL, writers );
    2320       58317 :       if( FD_UNLIKELY( in_wcost_table && in_wcost_table->total_cost+cur->compute_est > max_write_cost_per_acct ) ) {
    2321             :         /* Can't be scheduled until the next block */
    2322           3 :         conflicts = ULONG_MAX;
    2323           3 :         break;
    2324           3 :       }
    2325             : 
    2326       58314 :       fd_pack_addr_use_t * use = acct_uses_query( acct_in_use, acct, NULL );
    2327       58314 :       if( FD_UNLIKELY( use ) ) conflicts |= use->in_use_by; /* break? */
    2328       58314 :     }
    2329             : 
    2330       26082 :     if( FD_UNLIKELY( conflicts==ULONG_MAX ) ) {
    2331             :       /* The logic for how to adjust skip is a bit complicated, and we
    2332             :          want to do it branchlessly. Let psc=FD_PACK_SKIP_CNT,
    2333             :            Before                   After
    2334             :              1               compressed_slot_number
    2335             :            x in [2, psc]             x-1
    2336             :            x where x>psc            psc-1
    2337             : 
    2338             :          Set A=min(x, 5), B=min(A-2, compressed_slot_number-1), and
    2339             :          note that compressed_slot_number is in [psc+1, USHORT_MAX].
    2340             :          Then:
    2341             :              x                A     A-2          B      B+1
    2342             :              1                1  USHORT_MAX    csn-1    csn
    2343             :            x in [2, psc]      x     x-2         x-2     x-1
    2344             :            x where x>psc     psc   psc-2       psc-2   psc-1
    2345             :          So B+1 is the desired value. */
    2346           3 :       cur->skip = (ushort)(1+fd_ushort_min( (ushort)(compressed_slot_number-1),
    2347           3 :                                             (ushort)(fd_ushort_min( cur->skip, FD_PACK_SKIP_CNT )-2) ) );
    2348           3 :       write_limit_c++;
    2349           3 :       continue;
    2350           3 :     }
    2351             : 
    2352       26079 :     if( FD_UNLIKELY( conflicts ) ) {
    2353           6 :       slow_path++;
    2354           6 :       continue;
    2355           6 :     }
    2356             : 
    2357             :     /* Check conflicts between this transaction's readonly accounts and
    2358             :        current writers */
    2359       26073 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_READONLY );
    2360      119070 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2361             : 
    2362       92997 :       fd_acct_addr_t const * acct = ACCT_ITER_TO_PTR( iter );
    2363       92997 :       if( fd_pack_unwritable_contains( acct ) ) continue; /* No need to track sysvars because they can't be writable */
    2364             : 
    2365       65130 :       fd_pack_addr_use_t * use = acct_uses_query( acct_in_use,  *acct, NULL );
    2366       65130 :       if( use ) conflicts |= (use->in_use_by & FD_PACK_IN_USE_WRITABLE) ? use->in_use_by : 0UL;
    2367       65130 :     }
    2368             : 
    2369       26073 :     if( FD_UNLIKELY( conflicts ) ) {
    2370           0 :       slow_path++;
    2371           0 :       continue;
    2372           0 :     }
    2373             : 
    2374             :     /* Include this transaction in the microblock! */
    2375       26073 :     FD_PACK_BITSET_OR( bitset_rw_in_use, cur->rw_bitset );
    2376       26073 :     FD_PACK_BITSET_OR( bitset_w_in_use,  cur->w_bitset  );
    2377             : 
    2378       26073 :     fd_txn_p_t * out_txnp = out->txnp;
    2379       26073 :     if( FD_LIKELY( cur->txn->payload_sz>=1024UL ) ) pack_memcpy_out( out_txnp->payload, cur->txn->payload, cur->txn->payload_sz );
    2380       13281 :     else                                            fd_memcpy      ( out_txnp->payload, cur->txn->payload, cur->txn->payload_sz );
    2381             : 
    2382       26073 :     out_txnp->payload_sz                                = cur->txn->payload_sz;
    2383       26073 :     out_txnp->pack_cu.requested_exec_plus_acct_data_cus = cur->txn->pack_cu.requested_exec_plus_acct_data_cus;
    2384       26073 :     out_txnp->pack_cu.non_execution_cus                 = cur->txn->pack_cu.non_execution_cus;
    2385       26073 :     out_txnp->pack_alloc                                = cur->txn->pack_alloc;
    2386       26073 :     out_txnp->scheduler_arrival_time_nanos              = cur->txn->scheduler_arrival_time_nanos;
    2387       26073 :     out_txnp->first_seen_nanos                          = cur->txn->first_seen_nanos;
    2388       26073 :     out_txnp->source_tpu                                = cur->txn->source_tpu;
    2389       26073 :     out_txnp->source_ipv4                               = cur->txn->source_ipv4;
    2390       26073 :     out_txnp->flags                                     = cur->txn->flags;
    2391       26073 :     fd_memcpy( TXN(out_txnp), txn, fd_txn_footprint( txn->instr_cnt, txn->addr_table_lookup_cnt ) );
    2392             : 
    2393             :     /* Copy the ALT accounts from the source fd_txn_e_t */
    2394       26073 :     ulong alt_acct_cnt = (ulong)txn->addr_table_adtl_cnt;
    2395       26073 :     if( FD_UNLIKELY( alt_acct_cnt ) ) pack_memcpy_out( out->alt_accts, cur->txn_e->alt_accts, alt_acct_cnt*sizeof(fd_acct_addr_t) );
    2396       26073 :     out++;
    2397             : 
    2398       26073 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    2399       84372 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2400       58299 :       fd_acct_addr_t acct_addr = *ACCT_ITER_TO_PTR( iter );
    2401             : 
    2402       58299 :       fd_pack_wcost_ele_t * in_wcost_table = wcost_map_ele_query( writer_costs, &acct_addr, NULL, writers );
    2403       58299 :       if( !in_wcost_table ) {
    2404       11008 :         in_wcost_table = wcost_pool_ele_acquire( writers );
    2405       11008 :         in_wcost_table->key        = acct_addr;
    2406       11008 :         in_wcost_table->total_cost = 0UL;
    2407       11008 :         wcost_map_ele_insert     ( writer_costs, in_wcost_table, writers );
    2408       11008 :         wcost_dlist_ele_push_tail( written_list, in_wcost_table, writers );
    2409       11008 :       }
    2410       58299 :       in_wcost_table->total_cost += cur->compute_est;
    2411             : 
    2412       58299 :       fd_pack_addr_use_t * use = acct_uses_insert( acct_in_use, acct_addr );
    2413       58299 :       use->in_use_by = bank_tile_mask | FD_PACK_IN_USE_WRITABLE;
    2414             : 
    2415       58299 :       use_by_bank[use_by_bank_cnt++] = *use;
    2416             : 
    2417             :       /* If there aren't any more references to this account in the
    2418             :          heap, it can't cause any conflicts.  That means we actually
    2419             :          don't need to record that we are using it, which is good
    2420             :          because we want to release the bit. */
    2421       58299 :       release_result_t ret = release_bit_reference( pack, &acct_addr );
    2422       58299 :       FD_PACK_BITSET_CLEARN( bitset_rw_in_use, ret.clear_rw_bit );
    2423       58299 :       FD_PACK_BITSET_CLEARN( bitset_w_in_use,  ret.clear_w_bit  );
    2424       58299 :     }
    2425       26073 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_READONLY );
    2426      119070 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2427             : 
    2428       92997 :       fd_acct_addr_t acct_addr = *ACCT_ITER_TO_PTR( iter );
    2429             : 
    2430       92997 :       if( fd_pack_unwritable_contains( &acct_addr ) ) continue; /* No need to track sysvars because they can't be writable */
    2431             : 
    2432       65130 :       fd_pack_addr_use_t * use = acct_uses_query( acct_in_use,  acct_addr, NULL );
    2433       65130 :       if( !use ) { use = acct_uses_insert( acct_in_use, acct_addr ); use->in_use_by = 0UL; }
    2434             : 
    2435       65130 :       if( !(use->in_use_by & bank_tile_mask) ) use_by_bank[use_by_bank_cnt++] = *use;
    2436       65130 :       use->in_use_by |= bank_tile_mask;
    2437       65130 :       use->in_use_by &= ~FD_PACK_IN_USE_BIT_CLEARED;
    2438             : 
    2439             : 
    2440       65130 :       release_result_t ret = release_bit_reference( pack, &acct_addr );
    2441       65130 :       FD_PACK_BITSET_CLEARN( bitset_rw_in_use, ret.clear_rw_bit );
    2442       65130 :       FD_PACK_BITSET_CLEARN( bitset_w_in_use,  ret.clear_w_bit  );
    2443       65130 :     }
    2444             : 
    2445       26073 :     txns_scheduled  += 1UL;                      txn_limit       -= 1UL;
    2446       26073 :     cus_scheduled   += cur->compute_est;         cu_limit        -= cur->compute_est;
    2447       26073 :     bytes_scheduled += cur->txn->payload_sz;     byte_limit      -= cur->txn->payload_sz;
    2448       26073 :     alloc_scheduled += cur->txn->pack_alloc;     alloc_limit     -= cur->txn->pack_alloc;
    2449             : 
    2450       26073 :     *(use_by_bank_txn++) = use_by_bank_cnt;
    2451             : 
    2452       26073 :     if( FD_UNLIKELY( cur->txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE ) ) noncemap_ele_remove_fast( pack->noncemap, cur, pack->pool );
    2453       26073 :     sig2txn_ele_remove_fast( pack->signature_map, cur, pool );
    2454             : 
    2455       26073 :     cur->root = FD_ORD_TXN_ROOT_FREE;
    2456       26073 :     expq_remove( pack->expiration_q, cur->expq_idx );
    2457       26073 :     treap_idx_remove( sched_from, _cur, pool );
    2458       26073 :     trp_pool_idx_release( pool, _cur );
    2459       26073 :     pack->pending_txn_cnt--;
    2460             : 
    2461       26073 :     if( FD_UNLIKELY( (cu_limit<smallest_in_treap->cus) | (txn_limit==0UL) | (byte_limit<smallest_in_treap->bytes) ) ) break;
    2462       26073 :   }
    2463             : 
    2464       14665 :   pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_TAKEN_IDX               ] += txns_scheduled;
    2465       14665 :   pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CU_LIMIT_IDX            ] += cu_limit_c;
    2466       14665 :   pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CONFLICT_FAST_IDX       ] += fast_path;
    2467       14665 :   pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_BYTE_LIMIT_IDX          ] += byte_limit_c;
    2468       14665 :   pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_ALLOC_LIMIT_IDX         ] += alloc_limit_c;
    2469       14665 :   pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_WRITE_COST_IDX          ] += write_limit_c;
    2470       14665 :   pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CONFLICT_SLOW_IDX       ] += slow_path;
    2471       14665 :   pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_WRITE_COST_DEFERRED_IDX ] += skip_c;
    2472             : 
    2473             :   /* If we scanned the whole treap and didn't break early, we now have a
    2474             :      better estimate of the smallest. */
    2475       14665 :   if( FD_UNLIKELY( treap_rev_iter_done( prev ) ) ) {
    2476       14396 :     smallest_in_treap->cus   = min_cus;
    2477       14396 :     smallest_in_treap->bytes = min_bytes;
    2478       14396 :   }
    2479             : 
    2480       14665 :   pack->use_by_bank_cnt[bank_tile] = use_by_bank_cnt;
    2481       14665 :   FD_PACK_BITSET_COPY( pack->bitset_rw_in_use, bitset_rw_in_use );
    2482       14665 :   FD_PACK_BITSET_COPY( pack->bitset_w_in_use,  bitset_w_in_use  );
    2483             : 
    2484       14665 :   sched_return_t to_return = { .cus_scheduled=cus_scheduled,     .txns_scheduled=txns_scheduled,
    2485       14665 :                                .bytes_scheduled=bytes_scheduled, .alloc_scheduled=alloc_scheduled };
    2486       14665 :   return to_return;
    2487       14841 : }
    2488             : 
    2489             : int
    2490             : fd_pack_microblock_complete( fd_pack_t * pack,
    2491       14952 :                              ulong       bank_tile ) {
    2492             :   /* If the account is in use writably, and it's in use by this banking
    2493             :      tile, then this banking tile must be the sole writer to it, so it's
    2494             :      always okay to clear the writable bit. */
    2495       14952 :   ulong clear_mask = ~((1UL<<bank_tile) | FD_PACK_IN_USE_WRITABLE);
    2496             : 
    2497             :   /* If nothing outstanding, bail quickly */
    2498       14952 :   if( FD_UNLIKELY( !(pack->outstanding_microblock_mask & (1UL<<bank_tile)) ) ) return 0;
    2499             : 
    2500        8686 :   FD_PACK_BITSET_DECLARE( bitset_rw_in_use );
    2501        8686 :   FD_PACK_BITSET_DECLARE( bitset_w_in_use  );
    2502        8686 :   FD_PACK_BITSET_COPY( bitset_rw_in_use, pack->bitset_rw_in_use );
    2503        8686 :   FD_PACK_BITSET_COPY( bitset_w_in_use,  pack->bitset_w_in_use  );
    2504             : 
    2505        8686 :   fd_pack_addr_use_t * base = pack->use_by_bank[bank_tile];
    2506             : 
    2507        8686 :   fd_pack_ord_txn_t       * best         = NULL;
    2508        8686 :   fd_pack_penalty_treap_t * best_penalty = NULL;
    2509        8686 :   ulong                     txn_cnt      = 0UL;
    2510             : 
    2511      113807 :   for( ulong i=0UL; i<pack->use_by_bank_cnt[bank_tile]; i++ ) {
    2512      105121 :     fd_pack_addr_use_t * use = acct_uses_query( pack->acct_in_use, base[i].key, NULL );
    2513      105121 :     FD_TEST( use );
    2514      105121 :     use->in_use_by &= clear_mask;
    2515             : 
    2516             :     /* In order to properly bound the size of bitset_map, we need to
    2517             :        release the "reference" to the account when we schedule it.
    2518             :        However, that poses a bit of a problem here, because by the time
    2519             :        we complete the microblock, that account could have been assigned
    2520             :        a different bit in the bitset.  The scheduling step tells us if
    2521             :        that is the case, and if so, we know that the bits in
    2522             :        bitset_w_in_use and bitset_rw_in_use were already cleared as
    2523             :        necessary.
    2524             : 
    2525             :        Note that it's possible for BIT_CLEARED to be set and then unset
    2526             :        by later uses, but then the account would be in use on other
    2527             :        banks, so we wouldn't try to observe the old value.  For example:
    2528             :        Suppose bit 0->account A, bit 1->account B, and we have two
    2529             :        transactions that read A, B.  We schedule a microblock to bank 0,
    2530             :        taking both transactions, which sets the counts for A, B to 0,
    2531             :        and releases the bits, clearing bits 0 and 1, and setting
    2532             :        BIT_CLEARED.  Then we get two more transactions that read
    2533             :        accounts C, D, A, B, and they get assigned 0->C, 1->D, 2->A,
    2534             :        3->B.  We try to schedule a microblock to bank 1 that takes one
    2535             :        of those transactions.  This unsets BIT_CLEARED for A, B.
    2536             :        Finally, the first microblock completes.  Even though the bitset
    2537             :        map has the new bits for A and B which are "wrong" compared to
    2538             :        when the transaction was initially scheduled, those bits have
    2539             :        already been cleared and reset properly in the bitset as needed.
    2540             :        A and B will still be in use by bank 1, so we won't clear any
    2541             :        bits.  If, on the other hand, the microblock scheduled to bank 1
    2542             :        completes first, bits 0 and 1 will be cleared for accounts C and
    2543             :        D, while bits 2 and 3 will remain set, which is correct.  Then
    2544             :        when bank 0 completes, bits 2 and 3 will be cleared. */
    2545      105121 :     if( FD_LIKELY( !use->in_use_by ) ) { /* if in_use_by==0, doesn't include BIT_CLEARED */
    2546       39528 :       fd_pack_bitset_acct_mapping_t * q = bitset_map_query( pack->acct_to_bitset, base[i].key, NULL );
    2547       39528 :       FD_TEST( q );
    2548       39528 :       FD_PACK_BITSET_CLEARN( bitset_w_in_use,  q->bit );
    2549       39528 :       FD_PACK_BITSET_CLEARN( bitset_rw_in_use, q->bit );
    2550             : 
    2551             :       /* Because this account is no longer in use, it might be possible
    2552             :          to schedule a transaction that writes to it.  Check its
    2553             :          penalty treap if it has one, and potentially move it to the
    2554             :          main treap. */
    2555       39528 :       fd_pack_penalty_treap_t * p_trp = penalty_map_query( pack->penalty_treaps, base[i].key, NULL );
    2556       39528 :       if( FD_UNLIKELY( p_trp ) ) {
    2557        5507 :         fd_pack_ord_txn_t * best_in_trp = treap_rev_iter_ele( treap_rev_iter_init( p_trp->penalty_treap, pack->pool ), pack->pool );
    2558        5507 :         if( FD_UNLIKELY( !best || COMPARE_WORSE( best, best_in_trp ) ) ) {
    2559        2806 :           best         = best_in_trp;
    2560        2806 :           best_penalty = p_trp;
    2561        2806 :         }
    2562        5507 :       }
    2563       39528 :     }
    2564             : 
    2565      105121 :     if( FD_LIKELY( !(use->in_use_by & ~FD_PACK_IN_USE_BIT_CLEARED) ) ) acct_uses_remove( pack->acct_in_use, use );
    2566             : 
    2567      105121 :     if( FD_UNLIKELY( i+1UL==pack->use_by_bank_txn[ bank_tile ][ txn_cnt ] ) ) {
    2568       25395 :       txn_cnt++;
    2569       25395 :       if( FD_LIKELY( best ) ) {
    2570             :         /* move best to the main treap */
    2571        2806 :         treap_ele_remove( best_penalty->penalty_treap, best, pack->pool );
    2572        2806 :         best->root = FD_ORD_TXN_ROOT_PENDING;
    2573        2806 :         treap_ele_insert( pack->pending,               best, pack->pool );
    2574             : 
    2575        2806 :         pack->pending_smallest->cus   = fd_ulong_min( pack->pending_smallest->cus,   best->compute_est             );
    2576        2806 :         pack->pending_smallest->bytes = fd_ulong_min( pack->pending_smallest->bytes, best->txn_e->txnp->payload_sz );
    2577             : 
    2578        2806 :         if( FD_UNLIKELY( !treap_ele_cnt( best_penalty->penalty_treap ) ) ) {
    2579          12 :           treap_delete( treap_leave( best_penalty->penalty_treap ) );
    2580             :           /* Removal invalidates any pointers we got from
    2581             :              penalty_map_query, but we immediately set these to NULL, so
    2582             :              we're not keeping any pointers around. */
    2583          12 :           penalty_map_remove( pack->penalty_treaps, best_penalty );
    2584          12 :         }
    2585        2806 :         best         = NULL;
    2586        2806 :         best_penalty = NULL;
    2587        2806 :       }
    2588       25395 :     }
    2589      105121 :   }
    2590             : 
    2591        8686 :   pack->use_by_bank_cnt[bank_tile] = 0UL;
    2592             : 
    2593        8686 :   FD_PACK_BITSET_COPY( pack->bitset_rw_in_use, bitset_rw_in_use );
    2594        8686 :   FD_PACK_BITSET_COPY( pack->bitset_w_in_use,  bitset_w_in_use  );
    2595             : 
    2596             :   /* outstanding_microblock_mask never has the writable bit set, so we
    2597             :      don't care about clearing it here either. */
    2598        8686 :   pack->outstanding_microblock_mask &= clear_mask;
    2599        8686 :   return 1;
    2600        8686 : }
    2601             : 
    2602       14850 : #define TRY_BUNDLE_NO_READY_BUNDLES      0
    2603         234 : #define TRY_BUNDLE_HAS_CONFLICTS       (-1)
    2604         234 : #define TRY_BUNDLE_DOES_NOT_FIT        (-2)
    2605         234 : #define TRY_BUNDLE_SUCCESS(n)          ( n) /* schedule bundle with n transactions */
    2606             : static inline int
    2607             : fd_pack_try_schedule_bundle( fd_pack_t  * pack,
    2608             :                              ulong        bank_tile,
    2609       15084 :                              fd_txn_e_t * out ) {
    2610       15084 :   int state = pack->initializer_bundle_state;
    2611       15084 :   if( FD_UNLIKELY( (state==FD_PACK_IB_STATE_PENDING) | (state==FD_PACK_IB_STATE_FAILED ) ) ) return TRY_BUNDLE_NO_READY_BUNDLES;
    2612             : 
    2613       15081 :   fd_pack_ord_txn_t * pool    = pack->pool;
    2614       15081 :   treap_t           * bundles = pack->pending_bundles;
    2615             : 
    2616       15081 :   int require_ib;
    2617       15081 :   if( FD_UNLIKELY( state==FD_PACK_IB_STATE_NOT_INITIALIZED ) ) { require_ib = 1; }
    2618       15081 :   if( FD_LIKELY  ( state==FD_PACK_IB_STATE_READY           ) ) { require_ib = 0; }
    2619             : 
    2620       15081 :   treap_rev_iter_t _cur  = treap_rev_iter_init( bundles, pool );
    2621       15081 :   ulong bundle_idx = ULONG_MAX;
    2622             : 
    2623             :   /* Skip any that we've marked as won't fit in this block */
    2624       15081 :   while( FD_UNLIKELY( !treap_rev_iter_done( _cur ) && treap_rev_iter_ele( _cur, pool )->skip==pack->compressed_slot_number ) ) {
    2625           0 :     _cur = treap_rev_iter_next( _cur, pool );
    2626           0 :     pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_WRITE_COST_DEFERRED_IDX ]++;
    2627           0 :   }
    2628             : 
    2629             :   /* If there are no normal bundles to run, then fall back to the
    2630             :      pre-rotation treap. This is because fresh bundles usually don't
    2631             :      arrive exactly at the start of our leader rotation, so whilst we
    2632             :      are waiting for fresh bundles we should try the pre-rotation ones. */
    2633       15081 :   int                             is_pre_rotation     = 0;
    2634       15081 :   fd_pack_pre_rotation_bundle_t * pre_rotation_bundle = NULL;
    2635       15081 :   if( FD_UNLIKELY( treap_rev_iter_done( _cur ) ) ) {
    2636       14808 :     if( FD_UNLIKELY( require_ib ) ) return TRY_BUNDLE_NO_READY_BUNDLES;
    2637          87 :     is_pre_rotation = 1;
    2638          87 :     ulong best = pre_rotation_best_bundle_idx( pack );
    2639          87 :     if( FD_UNLIKELY( best==ULONG_MAX ) ) return TRY_BUNDLE_NO_READY_BUNDLES;
    2640          81 :     pre_rotation_bundle = pack->pre_rotation_bundles + best;
    2641          81 :     _cur                = treap_rev_iter_init( pre_rotation_bundle->treap, pool );
    2642          81 :   }
    2643             : 
    2644         354 :   if( FD_UNLIKELY( treap_rev_iter_done( _cur ) ) ) return TRY_BUNDLE_NO_READY_BUNDLES;
    2645             : 
    2646         354 :   treap_rev_iter_t   _txn0 = _cur;
    2647         354 :   fd_pack_ord_txn_t * txn0 = treap_rev_iter_ele( _txn0, pool );
    2648         354 :   int is_ib = !!(txn0->txn->flags & FD_TXN_P_FLAGS_INITIALIZER_BUNDLE);
    2649         354 :   bundle_idx = RC_TO_REL_BUNDLE_IDX( txn0->rewards, txn0->compute_est );
    2650             : 
    2651         354 :   if( FD_UNLIKELY( require_ib & !is_ib ) ) return TRY_BUNDLE_NO_READY_BUNDLES;
    2652             : 
    2653             :   /* At this point, we have our candidate bundle, so we'll schedule it
    2654             :      if we can.  If we can't, we won't schedule anything. */
    2655             : 
    2656             : 
    2657         234 :   fd_pack_addr_use_t * bundle_temp_inserted[ FD_PACK_MAX_TXN_PER_BUNDLE * FD_TXN_ACCT_ADDR_MAX ];
    2658         234 :   ulong bundle_temp_inserted_cnt = 0UL;
    2659             : 
    2660         234 :   ulong bank_tile_mask = 1UL << bank_tile;
    2661             : 
    2662         234 :   int doesnt_fit   = 0;
    2663         234 :   int has_conflict = 0;
    2664         234 :   ulong txn_cnt = 0UL;
    2665             : 
    2666         234 :   ulong cu_limit         = pack->lim->max_cost_per_block           - pack->cumulative_block_cost;
    2667         234 :   ulong byte_limit       = pack->lim->max_data_bytes_per_block     - pack->data_bytes_consumed;
    2668         234 :   ulong microblock_limit = pack->lim->max_microblocks_per_block    - pack->microblock_cnt;
    2669         234 :   ulong alloc_limit      = pack->lim->max_allocated_data_per_block - pack->alloc_consumed;
    2670             : 
    2671         234 :   FD_PACK_BITSET_DECLARE( bitset_rw_in_use );
    2672         234 :   FD_PACK_BITSET_DECLARE( bitset_w_in_use  );
    2673         234 :   FD_PACK_BITSET_COPY( bitset_rw_in_use, pack->bitset_rw_in_use );
    2674         234 :   FD_PACK_BITSET_COPY( bitset_w_in_use,  pack->bitset_w_in_use  );
    2675             : 
    2676             :   /* last_use_in_txn_cnt[i+1] Keeps track of the number of accounts that
    2677             :      have their last reference in transaction i of the bundle.  This
    2678             :      esoteric value is important for computing use_by_bank_txn.
    2679             :      last_use_in_txn_cnt[0] is garbage. */
    2680         234 :   ulong last_use_in_txn_cnt[ 1UL+FD_PACK_MAX_TXN_PER_BUNDLE ] = { 0UL };
    2681             : 
    2682         234 :   fd_pack_addr_use_t   null_use[1]    = {{{{ 0 }}, { 0 }}};
    2683         234 :   fd_pack_wcost_ele_t  null_wcost[1]  = { 0 };
    2684             : 
    2685         720 :   while( !(doesnt_fit | has_conflict) & !treap_rev_iter_done( _cur ) ) {
    2686         495 :     fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pool );
    2687         495 :     ulong this_bundle_idx = RC_TO_REL_BUNDLE_IDX( cur->rewards, cur->compute_est );
    2688         495 :     if( FD_UNLIKELY( this_bundle_idx!=bundle_idx ) ) break;
    2689             : 
    2690         489 :     if( FD_UNLIKELY( cur->compute_est>cu_limit ) ) {
    2691           0 :       doesnt_fit = 1;
    2692           0 :       pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CU_LIMIT_IDX ]++;
    2693           0 :       break;
    2694           0 :     }
    2695         489 :     cu_limit -= cur->compute_est;
    2696             : 
    2697             :     /* Each transaction in a bundle turns into a microblock */
    2698         489 :     if( FD_UNLIKELY( microblock_limit==0UL ) ) {
    2699           0 :       doesnt_fit = 1;
    2700           0 :       FD_MCNT_INC( PACK, BLOCK_MICROBLOCK_LIMIT_REACHED, 1UL );
    2701           0 :       break;
    2702           0 :     }
    2703         489 :     microblock_limit--;
    2704             : 
    2705         489 :     if( FD_UNLIKELY( cur->txn->payload_sz+MICROBLOCK_DATA_OVERHEAD>byte_limit ) ) {
    2706           0 :       doesnt_fit = 1;
    2707           0 :       pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_BYTE_LIMIT_IDX ]++;
    2708           0 :       break;
    2709           0 :     }
    2710         489 :     byte_limit -= cur->txn->payload_sz + MICROBLOCK_DATA_OVERHEAD;
    2711             : 
    2712         489 :     if( FD_UNLIKELY( cur->txn->pack_alloc>alloc_limit ) ) {
    2713           0 :       doesnt_fit = 1;
    2714           0 :       pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_ALLOC_LIMIT_IDX ]++;
    2715           0 :       break;
    2716           0 :     }
    2717         489 :     alloc_limit -= cur->txn->pack_alloc;
    2718             : 
    2719         489 :     if( FD_UNLIKELY( !FD_PACK_BITSET_INTERSECT4_EMPTY( pack->bitset_rw_in_use, pack->bitset_w_in_use, cur->w_bitset, cur->rw_bitset ) ) ) {
    2720           0 :       has_conflict = 1;
    2721           0 :       pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CONFLICT_FAST_IDX ]++;
    2722           0 :       break;
    2723           0 :     }
    2724             : 
    2725             :     /* Don't update the actual in-use bitset, because the transactions
    2726             :        in the bundle are allowed to conflict with each other. */
    2727         489 :     FD_PACK_BITSET_OR( bitset_rw_in_use, cur->rw_bitset );
    2728         489 :     FD_PACK_BITSET_OR( bitset_w_in_use,  cur->w_bitset  );
    2729             : 
    2730             : 
    2731         489 :     fd_txn_t const * txn = TXN(cur->txn);
    2732         489 :     fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, cur->txn->payload );
    2733         489 :     fd_acct_addr_t const * alt_adj = cur->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    2734             : 
    2735             :     /* Check conflicts between this transaction's writable accounts and
    2736             :        current readers */
    2737         489 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    2738        1629 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2739             : 
    2740        1143 :       fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    2741             : 
    2742        1143 :       fd_pack_addr_use_t * in_bundle_temp = acct_uses_query          ( pack->bundle_temp_map, acct, null_use                  );
    2743        1143 :       ulong current_cost                  = wcost_map_ele_query_const( pack->writer_costs,   &acct, null_wcost, pack->writers )->total_cost;
    2744        1143 :       ulong carried_cost                  = (ulong)in_bundle_temp->carried_cost;
    2745        1143 :       if( FD_UNLIKELY( current_cost + carried_cost + cur->compute_est > pack->lim->max_write_cost_per_acct ) ) {
    2746           0 :         doesnt_fit = 1;
    2747           0 :         pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_WRITE_COST_IDX ]++;
    2748           0 :         break;
    2749           0 :       }
    2750             : 
    2751        1143 :       if( FD_LIKELY( in_bundle_temp==null_use ) ) { /* Not in temp bundle table yet */
    2752        1083 :         in_bundle_temp    = acct_uses_insert( pack->bundle_temp_map, acct );
    2753        1083 :         in_bundle_temp->_ = 0UL;
    2754        1083 :         bundle_temp_inserted[ bundle_temp_inserted_cnt++ ] = in_bundle_temp;
    2755        1083 :       }
    2756        1143 :       in_bundle_temp->carried_cost += (uint)cur->compute_est; /* < 2^21, but >0 */
    2757        1143 :       in_bundle_temp->ref_cnt++;
    2758        1143 :       last_use_in_txn_cnt[ in_bundle_temp->last_use_in ]--;
    2759        1143 :       in_bundle_temp->last_use_in = (ushort)(txn_cnt+1UL);
    2760        1143 :       last_use_in_txn_cnt[ in_bundle_temp->last_use_in ]++;
    2761             : 
    2762        1143 :       if( FD_UNLIKELY( acct_uses_query( pack->acct_in_use, acct, null_use )->in_use_by ) ) {
    2763           3 :         has_conflict = 1;
    2764           3 :         pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CONFLICT_SLOW_IDX ]++;
    2765           3 :         break;
    2766           3 :       }
    2767        1143 :     }
    2768         489 :     if( has_conflict | doesnt_fit ) break;
    2769             : 
    2770             :     /* Check conflicts between this transaction's readonly accounts and
    2771             :        current writers */
    2772         486 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_READONLY );
    2773        2445 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2774             : 
    2775        1959 :       fd_acct_addr_t const * acct = ACCT_ITER_TO_PTR( iter );
    2776        1959 :       if( fd_pack_unwritable_contains( acct ) ) continue; /* No need to track sysvars because they can't be writable */
    2777             : 
    2778        1329 :       fd_pack_addr_use_t * in_bundle_temp = acct_uses_query( pack->bundle_temp_map, *acct, null_use );
    2779        1329 :       if( FD_LIKELY( in_bundle_temp==null_use ) ) { /* Not in temp bundle table yet */
    2780        1053 :         in_bundle_temp = acct_uses_insert( pack->bundle_temp_map, *acct );
    2781        1053 :         in_bundle_temp->_ = 0UL;
    2782        1053 :         bundle_temp_inserted[ bundle_temp_inserted_cnt++ ] = in_bundle_temp;
    2783        1053 :       }
    2784        1329 :       in_bundle_temp->ref_cnt++;
    2785        1329 :       last_use_in_txn_cnt[ in_bundle_temp->last_use_in ]--;
    2786        1329 :       in_bundle_temp->last_use_in = (ushort)(txn_cnt+1UL);
    2787        1329 :       last_use_in_txn_cnt[ in_bundle_temp->last_use_in ]++;
    2788             : 
    2789        1329 :       if( FD_UNLIKELY( acct_uses_query( pack->acct_in_use,  *acct, null_use )->in_use_by & FD_PACK_IN_USE_WRITABLE ) ) {
    2790           0 :         has_conflict = 1;
    2791           0 :         pack->sched_results[ FD_METRICS_ENUM_PACK_TXN_SCHEDULE_RESULT_V_CONFLICT_SLOW_IDX ]++;
    2792           0 :         break;
    2793           0 :       }
    2794        1329 :     }
    2795             : 
    2796         486 :     if( has_conflict | doesnt_fit ) break;
    2797             : 
    2798         486 :     txn_cnt++;
    2799         486 :     _cur = treap_rev_iter_next( _cur, pool );
    2800         486 :   }
    2801         234 :   int retval = fd_int_if( doesnt_fit, TRY_BUNDLE_DOES_NOT_FIT,
    2802         234 :                                       fd_int_if( has_conflict, TRY_BUNDLE_HAS_CONFLICTS, TRY_BUNDLE_SUCCESS( (int)txn_cnt ) ) );
    2803             : 
    2804         234 :   if( FD_UNLIKELY( retval<=0 ) ) {
    2805           9 :     for( ulong i=0UL; i<bundle_temp_inserted_cnt; i++ ) {
    2806           6 :       acct_uses_remove( pack->bundle_temp_map, bundle_temp_inserted[ bundle_temp_inserted_cnt-i-1UL ] );
    2807           6 :     }
    2808           3 :     FD_TEST( acct_uses_key_cnt( pack->bundle_temp_map )==0UL );
    2809             : 
    2810           3 :     if( FD_UNLIKELY( retval==TRY_BUNDLE_DOES_NOT_FIT ) ) {
    2811             :       /* Decrement the skip count for the bundle we just tried. */
    2812             : 
    2813           0 :       for( _cur=_txn0; !treap_rev_iter_done( _cur ); _cur=treap_rev_iter_next( _cur, pool ) ) {
    2814           0 :         fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pool );
    2815           0 :         ulong this_bundle_idx = RC_TO_REL_BUNDLE_IDX( cur->rewards, cur->compute_est );
    2816           0 :         if( FD_UNLIKELY( this_bundle_idx!=bundle_idx ) ) break;
    2817             : 
    2818             :         /* See fd_pack_schedule_impl for this line */
    2819           0 :         cur->skip = (ushort)(1+fd_ushort_min( (ushort)(pack->compressed_slot_number-1),
    2820           0 :               (ushort)(fd_ushort_min( cur->skip, FD_PACK_SKIP_CNT )-2) ) );
    2821           0 :       }
    2822           0 :     }
    2823           3 :     return retval;
    2824           3 :   }
    2825             : 
    2826             :   /* This bundle passed validation, so now we'll take it! */
    2827         231 :   pack->outstanding_microblock_mask |= bank_tile_mask;
    2828         231 :   FD_MCNT_INC( PACK, PRE_ROTATION_BUNDLE_SCHEDULED, (ulong)is_pre_rotation );
    2829             : 
    2830         231 :   treap_rev_iter_t   _end  = _cur;
    2831         231 :   treap_rev_iter_t   _next;
    2832             : 
    2833             :   /* We'll carefully incrementally construct use_by_bank and
    2834             :      use_by_bank_txn based on the contents of bundle_temp and
    2835             :      last_use_in_txn_cnt. */
    2836         231 :   fd_pack_addr_use_t * use_by_bank     = pack->use_by_bank    [bank_tile];
    2837         231 :   ulong              * use_by_bank_txn = pack->use_by_bank_txn[bank_tile];
    2838         231 :   ulong cum_sum = 0UL;
    2839         717 :   for( ulong k=0UL; k<txn_cnt; k++ ) { use_by_bank_txn[k] = cum_sum; cum_sum += last_use_in_txn_cnt[ k+1UL ]; }
    2840         231 :   pack->use_by_bank_cnt[bank_tile] = cum_sum;
    2841             : 
    2842             : 
    2843         717 :   for( _cur=_txn0; _cur!=_end; _cur=_next ) {
    2844         486 :     _next = treap_rev_iter_next( _cur, pool );
    2845             : 
    2846         486 :     fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pool );
    2847         486 :     fd_txn_t const    * txn = TXN(cur->txn);
    2848         486 :     fd_txn_p_t        * out_txnp = out->txnp;
    2849         486 :     if( FD_LIKELY( cur->txn->payload_sz>=1024UL ) ) pack_memcpy_out( out_txnp->payload, cur->txn->payload, cur->txn->payload_sz );
    2850         126 :     else                                            fd_memcpy      ( out_txnp->payload, cur->txn->payload, cur->txn->payload_sz );
    2851         486 :     fd_memcpy( TXN(out_txnp),     txn,               fd_txn_footprint( txn->instr_cnt, txn->addr_table_lookup_cnt ) );
    2852         486 :     out_txnp->payload_sz                      = cur->txn->payload_sz;
    2853         486 :     out_txnp->pack_cu.requested_exec_plus_acct_data_cus = cur->txn->pack_cu.requested_exec_plus_acct_data_cus;
    2854         486 :     out_txnp->pack_cu.non_execution_cus       = cur->txn->pack_cu.non_execution_cus;
    2855         486 :     out_txnp->pack_alloc                      = cur->txn->pack_alloc;
    2856         486 :     out_txnp->scheduler_arrival_time_nanos    = cur->txn->scheduler_arrival_time_nanos;
    2857         486 :     out_txnp->first_seen_nanos                = cur->txn->first_seen_nanos;
    2858         486 :     out_txnp->source_tpu                      = cur->txn->source_tpu;
    2859         486 :     out_txnp->source_ipv4                     = cur->txn->source_ipv4;
    2860         486 :     out_txnp->flags                           = cur->txn->flags;
    2861             :     /* Copy the ALT accounts from the source fd_txn_e_t */
    2862         486 :     ulong alt_acct_cnt = (ulong)txn->addr_table_adtl_cnt;
    2863         486 :     if( FD_UNLIKELY( alt_acct_cnt ) ) pack_memcpy_out( out->alt_accts, cur->txn_e->alt_accts, alt_acct_cnt*sizeof(fd_acct_addr_t) );
    2864         486 :     out++;
    2865             : 
    2866         486 :     pack->cumulative_block_cost += cur->compute_est;
    2867         486 :     pack->data_bytes_consumed   += cur->txn->payload_sz + MICROBLOCK_DATA_OVERHEAD;
    2868         486 :     pack->alloc_consumed        += cur->txn->pack_alloc;
    2869         486 :     pack->microblock_cnt        += 1UL;
    2870             : 
    2871         486 :     if( FD_UNLIKELY( cur->txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE ) ) noncemap_ele_remove_fast( pack->noncemap, cur, pack->pool );
    2872         486 :     sig2txn_ele_remove_fast( pack->signature_map, cur, pack->pool );
    2873             : 
    2874         486 :     cur->root = FD_ORD_TXN_ROOT_FREE;
    2875         486 :     expq_remove( pack->expiration_q, cur->expq_idx );
    2876         486 :     if( FD_UNLIKELY( is_pre_rotation ) ) pre_rotation_bundle_remove( pack, pre_rotation_bundle, _cur );
    2877         402 :     else                                 treap_idx_remove( pack->pending_bundles, _cur, pack->pool );
    2878         486 :     trp_pool_idx_release( pack->pool, _cur );
    2879         486 :     pack->pending_txn_cnt--;
    2880         486 :   }
    2881             : 
    2882             : 
    2883        2361 :   for( ulong i=0UL; i<bundle_temp_inserted_cnt; i++ ) {
    2884             :     /* In order to clear bundle_temp_map with the typical trick, we need
    2885             :        to iterate through bundle_temp_inserted backwards. */
    2886        2130 :     fd_pack_addr_use_t * addr_use = bundle_temp_inserted[ bundle_temp_inserted_cnt-i-1UL ];
    2887             : 
    2888        2130 :     int any_writers = addr_use->carried_cost>0U; /* Did any transaction in this bundle write lock this account address? */
    2889             : 
    2890        2130 :     if( FD_LIKELY( any_writers ) ) { /* UNLIKELY? */
    2891        1077 :       fd_pack_wcost_ele_t * in_wcost_table = wcost_map_ele_query( pack->writer_costs, &addr_use->key, NULL, pack->writers );
    2892        1077 :       if( !in_wcost_table ) {
    2893         981 :         in_wcost_table = wcost_pool_ele_acquire( pack->writers );
    2894         981 :         in_wcost_table->key        = addr_use->key;
    2895         981 :         in_wcost_table->total_cost = 0UL;
    2896         981 :         wcost_map_ele_insert     ( pack->writer_costs, in_wcost_table, pack->writers );
    2897         981 :         wcost_dlist_ele_push_tail( pack->written_list, in_wcost_table, pack->writers );
    2898         981 :       }
    2899        1077 :       in_wcost_table->total_cost += (ulong)addr_use->carried_cost;
    2900        1077 :     }
    2901             : 
    2902             :     /* in_use_by must be set before releasing the bit reference */
    2903        2130 :     fd_pack_addr_use_t * use = acct_uses_query( pack->acct_in_use, addr_use->key, NULL );
    2904        2130 :     if( !use ) { use = acct_uses_insert( pack->acct_in_use, addr_use->key ); use->in_use_by = 0UL; }
    2905        2130 :     use->in_use_by |= bank_tile_mask | fd_ulong_if( any_writers, FD_PACK_IN_USE_WRITABLE, 0UL );
    2906        2130 :     use->in_use_by &= ~FD_PACK_IN_USE_BIT_CLEARED;
    2907             : 
    2908        2130 :     use_by_bank[ use_by_bank_txn[ addr_use->last_use_in-1UL ]++ ] = *use;
    2909             : 
    2910        4596 :     for( ulong k=0UL; k<(ulong)addr_use->ref_cnt; k++ ) {
    2911        2466 :       release_result_t ret = release_bit_reference( pack, &(addr_use->key) );
    2912        2466 :       FD_PACK_BITSET_CLEARN( bitset_rw_in_use, ret.clear_rw_bit );
    2913        2466 :       FD_PACK_BITSET_CLEARN( bitset_w_in_use,  ret.clear_w_bit  );
    2914        2466 :     }
    2915             : 
    2916        2130 :     acct_uses_remove( pack->bundle_temp_map, addr_use );
    2917        2130 :   }
    2918             : 
    2919         231 :   FD_PACK_BITSET_COPY( pack->bitset_rw_in_use, bitset_rw_in_use );
    2920         231 :   FD_PACK_BITSET_COPY( pack->bitset_w_in_use,  bitset_w_in_use  );
    2921             : 
    2922         231 :   if( FD_UNLIKELY( is_ib ) ) {
    2923           3 :     pack->initializer_bundle_state = FD_PACK_IB_STATE_PENDING;
    2924           3 :   }
    2925         231 :   pack_memcpy_fini();
    2926         231 :   return retval;
    2927         234 : }
    2928             : 
    2929             : 
    2930             : ulong
    2931             : fd_pack_schedule_next_microblock( fd_pack_t *  pack,
    2932             :                                   ulong        total_cus,
    2933             :                                   ulong        bank_tile,
    2934             :                                   int          schedule_flags,
    2935       15207 :                                   fd_txn_e_t * out ) {
    2936             : 
    2937             :   /* TODO: Decide if these are exactly how we want to handle limits */
    2938       15207 :   total_cus = fd_ulong_min( total_cus, pack->lim->max_cost_per_block - pack->cumulative_block_cost );
    2939             : 
    2940       15207 :   if( FD_UNLIKELY( (pack->microblock_cnt>=pack->lim->max_microblocks_per_block) ) ) {
    2941           0 :     FD_MCNT_INC( PACK, BLOCK_MICROBLOCK_LIMIT_REACHED, 1UL );
    2942           0 :     return 0UL;
    2943           0 :   }
    2944       15207 :   if( FD_UNLIKELY( pack->data_bytes_consumed+MICROBLOCK_DATA_OVERHEAD+FD_TXN_MIN_SERIALIZED_SZ>pack->lim->max_data_bytes_per_block) ) {
    2945           0 :     FD_MCNT_INC( PACK, BLOCK_BYTE_LIMIT_REACHED, 1UL );
    2946           0 :     return 0UL;
    2947           0 :   }
    2948             : 
    2949       15207 :   ulong * use_by_bank_txn = pack->use_by_bank_txn[ bank_tile ];
    2950             : 
    2951       15207 : #if FD_HAS_X86
    2952             :   /* out is a cold dcache chunk.  Its payload is streamed, but the
    2953             :      metadata and TXN() lines are regular stores; start those reads for
    2954             :      ownership under the scheduling work. */
    2955       15207 :   _mm_prefetch( (uchar *)out+FD_TPU_MTU,       _MM_HINT_ET0 );
    2956       15207 :   _mm_prefetch( (uchar *)out+FD_TPU_MTU+ 64UL, _MM_HINT_ET0 );
    2957       15207 :   _mm_prefetch( (uchar *)out+FD_TPU_MTU+128UL, _MM_HINT_ET0 );
    2958       15207 : #endif
    2959             : 
    2960       15207 :   ulong cu_limit    = total_cus;
    2961       15207 :   ulong txn_limit   = pack->lim->max_txn_per_microblock;
    2962       15207 :   ulong scheduled   = 0UL;
    2963       15207 :   ulong byte_limit  = pack->lim->max_data_bytes_per_block - pack->data_bytes_consumed - MICROBLOCK_DATA_OVERHEAD;
    2964       15207 :   ulong alloc_limit = pack->lim->max_allocated_data_per_block - pack->alloc_consumed;
    2965             : 
    2966       15207 :   sched_return_t status = {0};
    2967             : 
    2968       15207 :   if( FD_UNLIKELY( schedule_flags & FD_PACK_SCHEDULE_BUNDLE ) ) {
    2969       15084 :     int bundle_result = fd_pack_try_schedule_bundle( pack, bank_tile, out );
    2970       15084 :     if( FD_UNLIKELY( bundle_result>0                         ) ) return (ulong)bundle_result;
    2971       14853 :     if( FD_UNLIKELY( bundle_result==TRY_BUNDLE_HAS_CONFLICTS ) ) return 0UL;
    2972             :     /* in the NO_READY_BUNDLES or DOES_NOT_FIT case, we schedule like
    2973             :        normal. */
    2974             :     /* We have the early returns here because try_schedule_bundle does
    2975             :        the bookkeeping internally, since the calculations are a bit
    2976             :        different in that case. */
    2977       14853 :   }
    2978             : 
    2979             : 
    2980             :   /* Fill the microblock with transactions, votes included */
    2981       14973 :   if( FD_LIKELY( schedule_flags & FD_PACK_SCHEDULE_TXN ) ) {
    2982       14841 :     status = fd_pack_schedule_impl( pack, pack->pending, cu_limit, txn_limit, byte_limit, alloc_limit, bank_tile,
    2983       14841 :         pack->pending_smallest, use_by_bank_txn, out+scheduled );
    2984             : 
    2985       14841 :     scheduled                   += status.txns_scheduled;
    2986       14841 :     pack->cumulative_block_cost += status.cus_scheduled;
    2987       14841 :     pack->data_bytes_consumed   += status.bytes_scheduled;
    2988       14841 :     pack->alloc_consumed        += status.alloc_scheduled;
    2989       14841 :   }
    2990             : 
    2991       14973 :   ulong nonempty = (ulong)(scheduled>0UL);
    2992       14973 :   pack->microblock_cnt              += nonempty;
    2993       14973 :   pack->outstanding_microblock_mask |= nonempty << bank_tile;
    2994       14973 :   pack->data_bytes_consumed         += nonempty * MICROBLOCK_DATA_OVERHEAD;
    2995             : 
    2996       14973 :   fd_histf_sample( pack->txn_per_microblock, scheduled );
    2997             : 
    2998       14973 :   pack_memcpy_fini();
    2999       14973 :   return scheduled;
    3000       15207 : }
    3001             : 
    3002      274398 : ulong fd_pack_bank_tile_cnt     ( fd_pack_t const * pack ) { return pack->bank_tile_cnt;         }
    3003           0 : ulong fd_pack_current_block_cost( fd_pack_t const * pack ) { return pack->cumulative_block_cost; }
    3004             : 
    3005             : 
    3006             : void
    3007           0 : fd_pack_set_block_limits( fd_pack_t * pack, fd_pack_limits_t const * limits ) {
    3008           0 :   FD_TEST( limits->max_cost_per_block      >= FD_PACK_MAX_COST_PER_BLOCK_LOWER_BOUND      );
    3009           0 :   FD_TEST( limits->max_write_cost_per_acct >= FD_PACK_MAX_WRITE_COST_PER_ACCT_LOWER_BOUND );
    3010             : 
    3011           0 :   pack->lim->max_microblocks_per_block    = limits->max_microblocks_per_block;
    3012           0 :   pack->lim->max_data_bytes_per_block     = limits->max_data_bytes_per_block;
    3013           0 :   pack->lim->max_cost_per_block           = limits->max_cost_per_block;
    3014           0 :   pack->lim->max_write_cost_per_acct      = limits->max_write_cost_per_acct;
    3015           0 :   pack->lim->max_allocated_data_per_block = limits->max_allocated_data_per_block;
    3016           0 : }
    3017             : 
    3018             : void
    3019           0 : fd_pack_get_block_limits( fd_pack_t * pack, fd_pack_limits_usage_t * opt_limits_usage, fd_pack_limits_t * opt_limits ) {
    3020           0 :   if( FD_LIKELY( opt_limits_usage ) ) {
    3021           0 :     opt_limits_usage->block_cost          = pack->cumulative_block_cost;
    3022           0 :     opt_limits_usage->block_data_bytes    = pack->data_bytes_consumed;
    3023           0 :     opt_limits_usage->microblocks         = pack->microblock_cnt;
    3024           0 :     opt_limits_usage->alloc               = pack->alloc_consumed;
    3025           0 :   }
    3026           0 :   if( FD_LIKELY( opt_limits ) ) fd_memcpy( opt_limits, pack->lim, sizeof(fd_pack_limits_t) );
    3027           0 : }
    3028             : 
    3029             : void
    3030           0 : fd_pack_get_top_writers( fd_pack_t const * pack, fd_pack_addr_use_t top_writers[static FD_PACK_TOP_WRITERS_CNT] ) {
    3031           0 :   fd_memcpy( top_writers, pack->top_writers, sizeof(pack->top_writers) );
    3032           0 : }
    3033             : 
    3034             : void
    3035           0 : fd_pack_get_pending_smallest( fd_pack_t * pack, fd_pack_smallest_t * opt_pending_smallest ) {
    3036           0 :   if( FD_LIKELY( opt_pending_smallest ) ) fd_memcpy( opt_pending_smallest, pack->pending_smallest, sizeof(fd_pack_smallest_t) );
    3037           0 : }
    3038             : 
    3039             : void
    3040             : fd_pack_rebate_cus( fd_pack_t              * pack,
    3041           6 :                     fd_pack_rebate_t const * rebate ) {
    3042           6 :   if( FD_UNLIKELY( (rebate->ib_result!=0) & (pack->initializer_bundle_state==FD_PACK_IB_STATE_PENDING ) ) ) {
    3043           0 :     pack->initializer_bundle_state = fd_int_if( rebate->ib_result==1, FD_PACK_IB_STATE_READY, FD_PACK_IB_STATE_FAILED );
    3044           0 :   }
    3045             : 
    3046           6 :   pack->cumulative_block_cost  -= rebate->total_cost_rebate;
    3047           6 :   pack->data_bytes_consumed    -= rebate->data_bytes_rebate;
    3048           6 :   pack->alloc_consumed         -= rebate->alloc_rebate;
    3049           6 :   pack->cumulative_rebated_cus += rebate->total_cost_rebate;
    3050             :   /* For now, we want to ignore the microblock count rebate.  There are
    3051             :      3 places the microblock count is kept (here, in the pack tile, and
    3052             :      in the PoH tile), and they all need to count microblocks that end
    3053             :      up being empty in the same way.  It would be better from a
    3054             :      DoS-resistance perspective for them all not to count empty
    3055             :      microblocks towards the total, but there's a race condition:
    3056             :      suppose pack schedules a microblock containing one transaction that
    3057             :      doesn't land on chain, the slot ends, and then pack informs PoH of
    3058             :      the number of microblocks before the final rebate comes through.
    3059             :      This isn't unsolvable, but it's pretty gross, so it's probably
    3060             :      better to just not apply the rebate for now. */
    3061           6 :   (void)rebate->microblock_cnt_rebate;
    3062             : 
    3063           6 :   wcost_map_t * writer_costs = pack->writer_costs;
    3064          18 :   for( ulong i=0UL; i<rebate->writer_cnt; i++ ) {
    3065          12 :     fd_pack_wcost_ele_t * in_wcost_table = wcost_map_ele_query( writer_costs, &rebate->writer_rebates[i].key, NULL, pack->writers );
    3066          12 :     if( FD_UNLIKELY( !in_wcost_table ) ) FD_LOG_ERR(( "Rebate to unknown written account" ));
    3067          12 :     in_wcost_table->total_cost -= rebate->writer_rebates[i].rebate_cus;
    3068             :     /* If the rebate drops it to zero, return it to the pool */
    3069          12 :     if( FD_UNLIKELY( !in_wcost_table->total_cost ) ) {
    3070           3 :       wcost_map_ele_remove_fast( writer_costs,       in_wcost_table, pack->writers );
    3071           3 :       wcost_dlist_ele_remove   ( pack->written_list, in_wcost_table, pack->writers );
    3072           3 :       wcost_pool_ele_release   ( pack->writers,      in_wcost_table );
    3073           3 :     }
    3074          12 :   }
    3075           6 : }
    3076             : 
    3077             : 
    3078             : ulong
    3079             : fd_pack_expire_before( fd_pack_t * pack,
    3080          24 :                        ulong       expire_before ) {
    3081          24 :   expire_before = fd_ulong_max( expire_before, pack->expire_before );
    3082          24 :   ulong deleted_cnt = 0UL;
    3083          24 :   fd_pack_expq_t * prq = pack->expiration_q;
    3084         345 :   while( (expq_cnt( prq )>0UL) & (prq->expires_at<expire_before) ) {
    3085         321 :     fd_pack_ord_txn_t * expired = prq->txn;
    3086             : 
    3087             :     /* fd_pack_delete_transaction also removes it from the heap */
    3088             :     /* All the transactions in the same bundle have the same expiration
    3089             :        time, so this loop will end up deleting them all, even with
    3090             :        delete_full_bundle set to 0. */
    3091         321 :     ulong _delete_cnt = delete_transaction( pack, expired, 0, 1 );
    3092         321 :     deleted_cnt += _delete_cnt;
    3093         321 :     FD_TEST( _delete_cnt );
    3094         321 :   }
    3095             : 
    3096          24 :   pack->expire_before = expire_before;
    3097          24 :   return deleted_cnt;
    3098          24 : }
    3099             : 
    3100             : void
    3101          12 : fd_pack_end_block( fd_pack_t * pack ) {
    3102             :   /* rounded division */
    3103          12 :   ulong pct_cus_per_block = (pack->cumulative_block_cost*100UL + (pack->lim->max_cost_per_block>>1))/pack->lim->max_cost_per_block;
    3104          12 :   fd_histf_sample( pack->pct_cus_per_block,       pct_cus_per_block                                          );
    3105          12 :   fd_histf_sample( pack->net_cus_per_block,       pack->cumulative_block_cost                                );
    3106          12 :   fd_histf_sample( pack->rebated_cus_per_block,   pack->cumulative_rebated_cus                               );
    3107          12 :   fd_histf_sample( pack->scheduled_cus_per_block, pack->cumulative_rebated_cus + pack->cumulative_block_cost );
    3108             : 
    3109          12 :   pack->microblock_cnt              = 0UL;
    3110          12 :   pack->data_bytes_consumed         = 0UL;
    3111          12 :   pack->cumulative_block_cost       = 0UL;
    3112          12 :   pack->cumulative_rebated_cus      = 0UL;
    3113          12 :   pack->outstanding_microblock_mask = 0UL;
    3114          12 :   pack->alloc_consumed              = 0UL;
    3115             : 
    3116          12 :   pack->initializer_bundle_state = FD_PACK_IB_STATE_NOT_INITIALIZED;
    3117             : 
    3118          12 :   acct_uses_clear( pack->acct_in_use  );
    3119          12 :   memset( pack->top_writers, 0, sizeof(pack->top_writers) );
    3120             : 
    3121          12 :   fd_pack_addr_use_t * last_top_writer = pack->top_writers + FD_PACK_TOP_WRITERS_CNT-1UL;
    3122             : 
    3123        4836 :   while( !wcost_dlist_is_empty( pack->written_list, pack->writers ) ) {
    3124        4824 :     fd_pack_wcost_ele_t * writer = wcost_dlist_ele_pop_head( pack->written_list, pack->writers );
    3125        4824 :     if( FD_UNLIKELY( writer->total_cost>last_top_writer->total_cost ) ) {
    3126          66 :       last_top_writer->key        = writer->key;
    3127          66 :       last_top_writer->total_cost = writer->total_cost;
    3128          66 :       fd_pack_writer_cost_sort_insert( pack->top_writers, FD_PACK_TOP_WRITERS_CNT );
    3129          66 :     }
    3130             :     /* Clearing the cost field here is unnecessary (since it gets
    3131             :        cleared on insert), but makes debugging a bit easier. */
    3132        4824 :     writer->total_cost = 0UL;
    3133        4824 :     wcost_map_ele_remove_fast( pack->writer_costs, writer, pack->writers );
    3134        4824 :     wcost_pool_ele_release( pack->writers, writer );
    3135        4824 :   }
    3136             : 
    3137             :   /* compressed_slot_number is > FD_PACK_SKIP_CNT, which means +1 is the
    3138             :      max unless it overflows. */
    3139          12 :   pack->compressed_slot_number = fd_ushort_max( (ushort)(pack->compressed_slot_number+1), (ushort)(FD_PACK_SKIP_CNT+1) );
    3140             : 
    3141          12 :   FD_PACK_BITSET_CLEAR( pack->bitset_rw_in_use );
    3142          12 :   FD_PACK_BITSET_CLEAR( pack->bitset_w_in_use  );
    3143             : 
    3144          24 :   for( ulong i=0UL; i<pack->bank_tile_cnt; i++ ) pack->use_by_bank_cnt[i] = 0UL;
    3145             : 
    3146             :   /* If our stake is low and we don't become leader often, end_block
    3147             :      might get called on the order of O(1/hr), which feels too
    3148             :      infrequent to do anything related to metrics.  However, we only
    3149             :      update the histograms when we are leader, so this is actually a
    3150             :      good place to copy them. */
    3151          12 :   FD_MHIST_COPY( PACK, TXN_PER_MICROBLOCK, pack->txn_per_microblock );
    3152             : 
    3153          12 :   FD_MGAUGE_SET( PACK, BLOCK_COST,               0UL                           );
    3154          12 :   FD_MHIST_COPY( PACK, COST_SCHEDULED_PER_BLOCK, pack->scheduled_cus_per_block );
    3155          12 :   FD_MHIST_COPY( PACK, CU_REBATED_PER_BLOCK,     pack->rebated_cus_per_block   );
    3156          12 :   FD_MHIST_COPY( PACK, COST_NET_PER_BLOCK,       pack->net_cus_per_block       );
    3157          12 :   FD_MHIST_COPY( PACK, COST_PER_BLOCK_PCT,       pack->pct_cus_per_block       );
    3158          12 : }
    3159             : 
    3160             : static void
    3161             : release_tree( treap_t           * treap,
    3162             :               sig2txn_t         * signature_map,
    3163             :               noncemap_t        * noncemap,
    3164         108 :               fd_pack_ord_txn_t * pool ) {
    3165         108 :   treap_fwd_iter_t next;
    3166         120 :   for( treap_fwd_iter_t it=treap_fwd_iter_init( treap, pool ); !treap_fwd_iter_done( it ); it=next ) {
    3167          12 :     next = treap_fwd_iter_next( it, pool );
    3168          12 :     ulong idx = treap_fwd_iter_idx( it );
    3169          12 :     pool[ idx ].root = FD_ORD_TXN_ROOT_FREE;
    3170          12 :     treap_idx_remove       ( treap,         idx, pool );
    3171          12 :     sig2txn_idx_remove_fast( signature_map, idx, pool );
    3172          12 :     trp_pool_idx_release   ( pool,          idx       );
    3173          12 :     if( pool[ idx ].txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE ) {
    3174           9 :       noncemap_idx_remove_fast( noncemap, idx, pool );
    3175           9 :     }
    3176          12 :   }
    3177         108 : }
    3178             : 
    3179             : void
    3180           6 : fd_pack_clear_all( fd_pack_t * pack ) {
    3181           6 :   pack->pending_txn_cnt        = 0UL;
    3182           6 :   pack->microblock_cnt         = 0UL;
    3183           6 :   pack->cumulative_block_cost  = 0UL;
    3184           6 :   pack->cumulative_rebated_cus = 0UL;
    3185           6 :   pack->data_bytes_consumed    = 0UL;
    3186           6 :   pack->alloc_consumed         = 0UL;
    3187             : 
    3188           6 :   pack->pending_smallest->cus         = ULONG_MAX;
    3189           6 :   pack->pending_smallest->bytes       = ULONG_MAX;
    3190             : 
    3191           6 :   release_tree( pack->pending,         pack->signature_map, pack->noncemap, pack->pool );
    3192           6 :   release_tree( pack->pending_bundles, pack->signature_map, pack->noncemap, pack->pool );
    3193         102 :   for( ulong i=0UL; i<FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY; i++ ) {
    3194          96 :     release_tree( pack->pre_rotation_bundles[ i ].treap, pack->signature_map, pack->noncemap, pack->pool );
    3195          96 :   }
    3196           6 :   pack->pre_rotation_bundle_cnt = 0UL;
    3197             : 
    3198           6 :   ulong const pool_max = trp_pool_max( pack->pool );
    3199        3240 :   for( ulong i=0UL; i<pool_max; i++ ) {
    3200        3234 :     if( FD_UNLIKELY( pack->pool[ i ].root!=FD_ORD_TXN_ROOT_FREE ) ) {
    3201           0 :       fd_pack_ord_txn_t * const del = pack->pool + i;
    3202           0 :       fd_txn_t * txn = TXN( del->txn );
    3203           0 :       fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, del->txn->payload );
    3204           0 :       fd_acct_addr_t const * alt_adj = del->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    3205           0 :       fd_acct_addr_t penalty_acct = *ACCT_IDX_TO_PTR( FD_ORD_TXN_ROOT_PENALTY_ACCT_IDX( del->root ) );
    3206           0 :       fd_pack_penalty_treap_t * penalty_treap = penalty_map_query( pack->penalty_treaps, penalty_acct, NULL );
    3207           0 :       FD_TEST( penalty_treap );
    3208           0 :       release_tree( penalty_treap->penalty_treap, pack->signature_map, pack->noncemap, pack->pool );
    3209           0 :     }
    3210        3234 :   }
    3211             : 
    3212           6 :   pack->compressed_slot_number = (ushort)(FD_PACK_SKIP_CNT+1);
    3213             : 
    3214           6 :   expq_remove_all( pack->expiration_q );
    3215             : 
    3216           6 :   acct_uses_clear( pack->acct_in_use  );
    3217             : 
    3218          21 :   while( !wcost_dlist_is_empty( pack->written_list, pack->writers ) ) {
    3219          15 :     fd_pack_wcost_ele_t * writer = wcost_dlist_ele_pop_head( pack->written_list, pack->writers );
    3220          15 :     writer->total_cost = 0UL;
    3221          15 :     wcost_map_ele_remove_fast( pack->writer_costs, writer, pack->writers );
    3222          15 :     wcost_pool_ele_release( pack->writers, writer );
    3223          15 :   }
    3224             : 
    3225           6 :   penalty_map_clear( pack->penalty_treaps );
    3226             : 
    3227           6 :   FD_PACK_BITSET_CLEAR( pack->bitset_rw_in_use );
    3228           6 :   FD_PACK_BITSET_CLEAR( pack->bitset_w_in_use  );
    3229           6 :   bitset_map_clear( pack->acct_to_bitset );
    3230           6 :   pack->bitset_avail[ 0 ] = FD_PACK_BITSET_SLOWPATH;
    3231        2054 :   for( ulong i=0UL; i<FD_PACK_BITSET_MAX; i++ ) pack->bitset_avail[ i+1UL ] = (ushort)i;
    3232           6 :   pack->bitset_avail_cnt = FD_PACK_BITSET_MAX;
    3233             : 
    3234          12 :   for( ulong i=0UL; i<pack->bank_tile_cnt; i++ ) pack->use_by_bank_cnt[i] = 0UL;
    3235           6 : }
    3236             : 
    3237             : 
    3238             : /* If delete_full_bundle is non-zero and the transaction to delete is
    3239             :    part of a bundle, the rest of the bundle it is part of will be
    3240             :    deleted as well.
    3241             :    If move_from_penalty_treap is non-zero and the transaction to delete
    3242             :    is in the pending treap, move the best transaction in any of the
    3243             :    conflicting penalty treaps to the pending treap (if there is one). */
    3244             : static ulong
    3245             : delete_transaction( fd_pack_t         * pack,
    3246             :                     fd_pack_ord_txn_t * containing,
    3247             :                     int                 delete_full_bundle,
    3248        4116 :                     int                 move_from_penalty_treap ) {
    3249             : 
    3250        4116 :   fd_txn_t * txn = TXN( containing->txn );
    3251        4116 :   fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, containing->txn->payload );
    3252        4116 :   fd_acct_addr_t const * alt_adj = containing->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    3253             : 
    3254        4116 :   treap_t * root = NULL;
    3255        4116 :   int root_idx = containing->root;
    3256        4116 :   fd_pack_penalty_treap_t       * penalty_treap       = NULL;
    3257        4116 :   fd_pack_pre_rotation_bundle_t * pre_rotation_bundle = NULL;
    3258        4116 :   switch( root_idx & FD_ORD_TXN_ROOT_TAG_MASK ) {
    3259           0 :     case FD_ORD_TXN_ROOT_FREE:                FD_LOG_CRIT(( "Double free detected" ));
    3260         921 :     case FD_ORD_TXN_ROOT_PENDING:             root = pack->pending;              break;
    3261         519 :     case FD_ORD_TXN_ROOT_PENDING_BUNDLE:      root = pack->pending_bundles;      break;
    3262          24 :     case FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE( 0 ): {
    3263          24 :       pre_rotation_bundle = pack->pre_rotation_bundles + FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE_IDX( root_idx );
    3264          24 :       root                = pre_rotation_bundle->treap;
    3265          24 :       break;
    3266           0 :     }
    3267        2652 :     case FD_ORD_TXN_ROOT_PENALTY( 0 ): {
    3268        2652 :       fd_acct_addr_t penalty_acct = *ACCT_IDX_TO_PTR( FD_ORD_TXN_ROOT_PENALTY_ACCT_IDX( root_idx ) );
    3269        2652 :       penalty_treap = penalty_map_query( pack->penalty_treaps, penalty_acct, NULL );
    3270        2652 :       FD_TEST( penalty_treap );
    3271        2652 :       root = penalty_treap->penalty_treap;
    3272        2652 :       break;
    3273        2652 :     }
    3274        4116 :   }
    3275             : 
    3276        4116 :   ulong delete_cnt = 0UL;
    3277        4116 :   if( FD_UNLIKELY( delete_full_bundle & ((root==pack->pending_bundles) | (!!pre_rotation_bundle)) ) ) {
    3278             :     /* When we delete, the structure of the treap may move around, but
    3279             :        pointers to inside the pool will remain valid */
    3280         132 :     fd_pack_ord_txn_t * bundle_ptrs[ FD_PACK_MAX_TXN_PER_BUNDLE-1UL ];
    3281         132 :     fd_pack_ord_txn_t * pool       = pack->pool;
    3282         132 :     ulong               cnt        = 0UL;
    3283         132 :     ulong               bundle_idx = RC_TO_REL_BUNDLE_IDX( containing->rewards, containing->compute_est );
    3284             : 
    3285             :     /* Iterate in both directions from the current transaction */
    3286         132 :     for( treap_fwd_iter_t _cur=treap_fwd_iter_next( (treap_fwd_iter_t)treap_idx_fast( containing, pool ), pool );
    3287         438 :         !treap_fwd_iter_done( _cur ); _cur=treap_fwd_iter_next( _cur, pool ) ) {
    3288         306 :       fd_pack_ord_txn_t * cur = treap_fwd_iter_ele( _cur, pool );
    3289         306 :       if( FD_LIKELY( bundle_idx==RC_TO_REL_BUNDLE_IDX( cur->rewards, cur->compute_est ) ) ) {
    3290         306 :         bundle_ptrs[ cnt++ ] = cur;
    3291         306 :       } else {
    3292           0 :         break;
    3293           0 :       }
    3294         306 :       FD_TEST( cnt<FD_PACK_MAX_TXN_PER_BUNDLE );
    3295         306 :     }
    3296             : 
    3297         132 :     for( treap_rev_iter_t _cur=treap_rev_iter_next( (treap_rev_iter_t)treap_idx_fast( containing, pool ), pool );
    3298         228 :         !treap_rev_iter_done( _cur ); _cur=treap_rev_iter_next( _cur, pool ) ) {
    3299          96 :       fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pool );
    3300          96 :       if( FD_LIKELY( bundle_idx==RC_TO_REL_BUNDLE_IDX( cur->rewards, cur->compute_est ) ) ) {
    3301          96 :         bundle_ptrs[ cnt++ ] = cur;
    3302          96 :       } else {
    3303           0 :         break;
    3304           0 :       }
    3305          96 :       FD_TEST( cnt<FD_PACK_MAX_TXN_PER_BUNDLE );
    3306          96 :     }
    3307             : 
    3308             :     /* Delete them each, setting delete_full_bundle to 0 to avoid
    3309             :        infinite recursion. */
    3310         534 :     for( ulong k=0UL; k<cnt; k++ ) delete_cnt += delete_transaction( pack, bundle_ptrs[ k ], 0, 0 );
    3311         132 :   }
    3312             : 
    3313             : 
    3314        4116 :   if( FD_UNLIKELY( move_from_penalty_treap & (root==pack->pending) ) ) {
    3315             : 
    3316         816 :     fd_pack_ord_txn_t       * best         = NULL;
    3317         816 :     fd_pack_penalty_treap_t * best_penalty = NULL;
    3318             : 
    3319         816 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    3320        3498 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    3321        2682 :       fd_pack_penalty_treap_t * p_trp = penalty_map_query( pack->penalty_treaps, *ACCT_ITER_TO_PTR( iter ), NULL );
    3322        2682 :       if( FD_UNLIKELY( p_trp ) ) {
    3323        1340 :         fd_pack_ord_txn_t * best_in_trp = treap_rev_iter_ele( treap_rev_iter_init( p_trp->penalty_treap, pack->pool ), pack->pool );
    3324        1340 :         if( FD_UNLIKELY( !best || COMPARE_WORSE( best, best_in_trp ) ) ) {
    3325         701 :           best         = best_in_trp;
    3326         701 :           best_penalty = p_trp;
    3327         701 :         }
    3328        1340 :       }
    3329        2682 :     }
    3330             : 
    3331         816 :     if( FD_LIKELY( best ) ) {
    3332             :       /* move best to the main treap */
    3333         701 :       treap_ele_remove( best_penalty->penalty_treap, best, pack->pool );
    3334         701 :       best->root = FD_ORD_TXN_ROOT_PENDING;
    3335         701 :       treap_ele_insert( pack->pending,               best, pack->pool );
    3336             : 
    3337         701 :       pack->pending_smallest->cus   = fd_ulong_min( pack->pending_smallest->cus,   best->compute_est             );
    3338         701 :       pack->pending_smallest->bytes = fd_ulong_min( pack->pending_smallest->bytes, best->txn_e->txnp->payload_sz );
    3339             : 
    3340         701 :       if( FD_UNLIKELY( !treap_ele_cnt( best_penalty->penalty_treap ) ) ) {
    3341           9 :         treap_delete( treap_leave( best_penalty->penalty_treap ) );
    3342           9 :         penalty_map_remove( pack->penalty_treaps, best_penalty );
    3343           9 :       }
    3344         701 :     }
    3345         816 :   }
    3346             : 
    3347        4116 :   for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_ALL );
    3348       39585 :       iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    3349       35469 :     if( FD_UNLIKELY( fd_pack_unwritable_contains( ACCT_ITER_TO_PTR( iter ) ) ) ) continue;
    3350             : 
    3351       30624 :     release_result_t ret = release_bit_reference( pack, ACCT_ITER_TO_PTR( iter ) );
    3352       30624 :     FD_PACK_BITSET_CLEARN( pack->bitset_rw_in_use, ret.clear_rw_bit );
    3353       30624 :     FD_PACK_BITSET_CLEARN( pack->bitset_w_in_use,  ret.clear_w_bit  );
    3354       30624 :   }
    3355             : 
    3356        4116 :   if( FD_UNLIKELY( containing->txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE ) ) {
    3357         354 :     noncemap_ele_remove_fast( pack->noncemap, containing, pack->pool );
    3358         354 :   }
    3359        4116 :   expq_remove( pack->expiration_q, containing->expq_idx );
    3360        4116 :   if( FD_UNLIKELY( pre_rotation_bundle ) ) pre_rotation_bundle_remove( pack, pre_rotation_bundle, (ulong)(containing-pack->pool) );
    3361        4092 :   else                                     treap_ele_remove( root, containing, pack->pool );
    3362        4116 :   containing->root = FD_ORD_TXN_ROOT_FREE;
    3363        4116 :   sig2txn_ele_remove_fast( pack->signature_map, containing, pack->pool );
    3364        4116 :   trp_pool_ele_release( pack->pool, containing );
    3365             : 
    3366        4116 :   delete_cnt += 1UL;
    3367        4116 :   pack->pending_txn_cnt--;
    3368             : 
    3369        4116 :   if( FD_UNLIKELY( penalty_treap && treap_ele_cnt( root )==0UL ) ) {
    3370           0 :     penalty_map_remove( pack->penalty_treaps, penalty_treap );
    3371           0 :   }
    3372             : 
    3373        4116 :   return delete_cnt;
    3374        4116 : }
    3375             : 
    3376             : ulong
    3377             : fd_pack_delete_transaction( fd_pack_t              * pack,
    3378         183 :                             fd_ed25519_sig_t const * sig0 ) {
    3379         183 :   ulong cnt = 0;
    3380         183 :   ulong next = ULONG_MAX;
    3381             : 
    3382             :   /* sig2txn reads only the signature offset and signature bytes. */
    3383         183 :   fd_txn_e_t query_e;
    3384         183 :   TXN(query_e.txnp)->signature_off = 0U;
    3385         183 :   fd_memcpy( query_e.txnp[0].payload, sig0, FD_TXN_SIGNATURE_SZ );
    3386         183 :   for( ulong idx = sig2txn_idx_query_const( pack->signature_map, &query_e, ULONG_MAX, pack->pool );
    3387         342 :       idx!=ULONG_MAX; idx=next ) {
    3388             :     /* Iterating while deleting, not just this element, but perhaps the
    3389             :        whole bundle, feels a bit dangerous, but is actually fine because
    3390             :        a bundle can't contain two transactions with the same signature.
    3391             :        That means we know next is not part of the same bundle as idx,
    3392             :        which means that deleting idx will not delete next. */
    3393         159 :     next = sig2txn_idx_next_const( idx, ULONG_MAX, pack->pool );
    3394         159 :     cnt += delete_transaction( pack, pack->pool+idx, 1, 1 );
    3395         159 :   }
    3396             : 
    3397         183 :   return cnt;
    3398         183 : }
    3399             : 
    3400             : 
    3401             : int
    3402             : fd_pack_verify( fd_pack_t * pack,
    3403         627 :                 void      * scratch ) {
    3404             :   /* Invariants:
    3405             :      sig2txn_query has exact same contents as all treaps combined
    3406             :      root matches treap
    3407             :      Keys of acct_to_bitset is exactly union of all accounts in all
    3408             :             transactions in treaps, with ref counted appropriately
    3409             :      bits in bitset_avail is complement of bits allocated in
    3410             :             acct_to_bitset
    3411             :      expires_at consistent between treap, prq
    3412             :      use_by_bank does not contain duplicates
    3413             :      use_by_bank consistent with acct_in_use
    3414             :      elements in pool but not in a treap have root set to free
    3415             :      all penalty treaps have at least one transaction
    3416             :      all elements in penalty treaps are in the one that the root indicates
    3417             :      */
    3418             : 
    3419             :   /* TODO:
    3420             :      bitset_{r}w_in_use = bitset_map_query( everything in acct_in_use that doesn't have FD_PACK_IN_USE_BIT_CLEARED )
    3421             :      bitset_w_in_use & bitset_rw_in_use == bitset_w_in_use
    3422             :      */
    3423      495061 : #define VERIFY_TEST( cond, ... ) do {   \
    3424      495061 :     if( FD_UNLIKELY( !(cond) ) ) {      \
    3425           0 :       FD_LOG_WARNING(( __VA_ARGS__ ));  \
    3426           0 :       return -(__LINE__);               \
    3427           0 :     }                                   \
    3428      495061 :   } while( 0 )
    3429             : 
    3430         627 :   ulong max_acct_in_treap  = pack->pack_depth * FD_TXN_ACCT_ADDR_MAX;
    3431         627 :   int lg_acct_in_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap  ) );
    3432         627 :   void * _bitset_map_copy = scratch;
    3433         627 :   void * _bitset_map_orig = bitset_map_leave( pack->acct_to_bitset );
    3434         627 :   fd_memcpy( _bitset_map_copy, _bitset_map_orig, bitset_map_footprint( lg_acct_in_trp ) );
    3435             : 
    3436         627 :   fd_pack_bitset_acct_mapping_t * bitset_copy = bitset_map_join( _bitset_map_copy );
    3437             : 
    3438             :   /* Check that each bit is in exactly one place */
    3439         627 :   FD_PACK_BITSET_DECLARE( processed ); FD_PACK_BITSET_CLEAR( processed );
    3440         627 :   FD_PACK_BITSET_DECLARE( bit       ); FD_PACK_BITSET_CLEAR( bit       );
    3441         627 :   FD_PACK_BITSET_DECLARE( full      ); FD_PACK_BITSET_CLEAR( full      );
    3442             : 
    3443         627 :   if( FD_UNLIKELY( pack->bitset_avail[0]!=FD_PACK_BITSET_SLOWPATH ) ) return -1;
    3444      213683 :   for( ulong i=1UL; i<=pack->bitset_avail_cnt; i++ ) {
    3445      213056 :     FD_PACK_BITSET_CLEAR( bit );
    3446      213056 :     FD_PACK_BITSET_SETN( bit, pack->bitset_avail[ i ] );
    3447      213056 :     VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, processed, processed ),
    3448      213056 :         "bit %hu in avail set twice", pack->bitset_avail[ i ] );
    3449      213056 :     FD_PACK_BITSET_OR( processed, bit );
    3450      213056 :   }
    3451             : 
    3452         627 :   ulong total_references = 0UL;
    3453    71014515 :   for( ulong i=0UL; i<bitset_map_slot_cnt( bitset_copy ); i++ ) {
    3454    71013888 :     if( !bitset_map_key_inval( bitset_copy[ i ].key ) ) {
    3455        4518 :       VERIFY_TEST( bitset_copy[ i ].ref_cnt>0UL, "account address in table with 0 ref count" );
    3456             : 
    3457        4518 :       total_references += bitset_copy[ i ].ref_cnt;
    3458             : 
    3459        4518 :       FD_PACK_BITSET_CLEAR( bit );
    3460        4518 :       FD_PACK_BITSET_SETN( bit, bitset_copy[ i ].bit );
    3461        4518 :       VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, processed, processed ), "bit %hu used twice", bitset_copy[ i ].bit );
    3462        4518 :       FD_PACK_BITSET_OR( processed, bit );
    3463        4518 :     }
    3464    71013888 :   }
    3465      214643 :   for( ulong i=0UL; i<FD_PACK_BITSET_MAX; i++ ) {
    3466      214016 :     FD_PACK_BITSET_CLEAR( bit );
    3467      214016 :     FD_PACK_BITSET_SETN( bit, i );
    3468      214016 :     VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, processed, processed ), "bit %lu missing", i );
    3469      214016 :     FD_PACK_BITSET_SETN( full, i );
    3470      214016 :   }
    3471             : 
    3472             : 
    3473         627 :   fd_pack_ord_txn_t  * pool = pack->pool;
    3474         627 :   treap_t * treaps[ 2 ] = { pack->pending, pack->pending_bundles };
    3475         627 :   ulong txn_cnt = 0UL;
    3476             : 
    3477         627 :   ulong const pre_rotation_bundle_max = FD_PACK_PRE_ROTATION_BUNDLE_CAPACITY;
    3478         627 :   ulong pre_rotation_bundle_cnt = 0UL;
    3479       10659 :   for( ulong i=0UL; i<pre_rotation_bundle_max; i++ ) {
    3480       10032 :     ulong cnt = treap_ele_cnt( pack->pre_rotation_bundles[ i ].treap );
    3481       10032 :     pre_rotation_bundle_cnt += (ulong)(cnt>0UL);
    3482       10032 :     VERIFY_TEST( cnt<=FD_PACK_MAX_TXN_PER_BUNDLE, "pre-rotation bundle %lu holds %lu transactions", i, cnt );
    3483       10032 :   }
    3484         627 :   VERIFY_TEST( pre_rotation_bundle_cnt==pack->pre_rotation_bundle_cnt, "pre_rotation_bundle_cnt %lu, found %lu bundles", pack->pre_rotation_bundle_cnt, pre_rotation_bundle_cnt );
    3485             : 
    3486     1121505 :   for( ulong k=0UL; k<2UL+pre_rotation_bundle_max+penalty_map_slot_cnt( pack->penalty_treaps ); k++ ) {
    3487     1120878 :     treap_t * treap = NULL;
    3488             : 
    3489     1120878 :     if( k<2UL ) treap = treaps[ k ];
    3490     1119624 :     else if( k<2UL+pre_rotation_bundle_max ) {
    3491       10032 :       treap = pack->pre_rotation_bundles[ k-2UL ].treap;
    3492       10032 :       if( !treap_ele_cnt( treap ) ) continue;
    3493       10032 :     }
    3494     1109592 :     else if( FD_LIKELY( penalty_map_key_inval( pack->penalty_treaps[ k-2UL-pre_rotation_bundle_max ].key ) ) ) continue;
    3495           0 :     else {
    3496           0 :       treap = pack->penalty_treaps[ k-2UL-pre_rotation_bundle_max ].penalty_treap;
    3497           0 :       VERIFY_TEST( treap_ele_cnt( treap )>0UL, "empty penalty treap in map" );
    3498           0 :     }
    3499             : 
    3500        4269 :     for( treap_rev_iter_t _cur=treap_rev_iter_init( treap, pool ); !treap_rev_iter_done( _cur );
    3501        2358 :         _cur=treap_rev_iter_next( _cur, pool ) ) {
    3502        2358 :       txn_cnt++;
    3503        2358 :       fd_pack_ord_txn_t const * cur = treap_rev_iter_ele_const( _cur, pool );
    3504        2358 :       fd_txn_t const * txn = TXN(cur->txn);
    3505        2358 :       fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, cur->txn->payload );
    3506        2358 :       fd_acct_addr_t const * alt_adj = cur->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    3507             : 
    3508        2358 :       fd_pack_ord_txn_t const * in_tbl = sig2txn_ele_query_const( pack->signature_map, &cur->_txn_e, NULL, pool );
    3509        2358 :       VERIFY_TEST( in_tbl, "signature missing from sig2txn" );
    3510             : 
    3511        2358 :       ulong expected_root = (k<2UL) ? k+1UL : ((k<2UL+pre_rotation_bundle_max) ? (ulong)FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE( 0 ) : (ulong)FD_ORD_TXN_ROOT_PENALTY( 0 ));
    3512        2358 :       VERIFY_TEST( (ulong)(cur->root & FD_ORD_TXN_ROOT_TAG_MASK)==expected_root, "treap element had bad root" );
    3513        2358 :       if( FD_UNLIKELY( (cur->root & FD_ORD_TXN_ROOT_TAG_MASK)==FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE( 0 ) ) ) {
    3514         672 :         VERIFY_TEST( (ulong)FD_ORD_TXN_ROOT_PRE_ROTATION_BUNDLE_IDX( cur->root )==k-2UL, "transaction in wrong pre-rotation bundle" );
    3515         672 :       }
    3516        2358 :       if( FD_LIKELY( (cur->root & FD_ORD_TXN_ROOT_TAG_MASK)==FD_ORD_TXN_ROOT_PENALTY(0) ) ) {
    3517           0 :         fd_acct_addr_t const * penalty_acct = ACCT_IDX_TO_PTR( FD_ORD_TXN_ROOT_PENALTY_ACCT_IDX( cur->root ) );
    3518           0 :         VERIFY_TEST( !memcmp( penalty_acct, pack->penalty_treaps[ k-2UL-pre_rotation_bundle_max ].key.b, 32UL ), "transaction in wrong penalty treap" );
    3519           0 :       }
    3520        2358 :       VERIFY_TEST( cur->expires_at>=pack->expire_before, "treap element expired" );
    3521             : 
    3522        2358 :       fd_pack_expq_t const * eq = pack->expiration_q + cur->expq_idx;
    3523        2358 :       VERIFY_TEST( eq->txn==cur, "expq inconsistent" );
    3524        2358 :       VERIFY_TEST( eq->expires_at==cur->expires_at, "expq expires_at inconsistent" );
    3525             : 
    3526        2358 :       FD_PACK_BITSET_DECLARE( complement );
    3527        2358 :       FD_PACK_BITSET_COPY( complement, full );
    3528        2358 :       for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    3529        7929 :           iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    3530        5571 :         fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    3531             : 
    3532        5571 :         fd_pack_bitset_acct_mapping_t * q = bitset_map_query( bitset_copy, acct, NULL );
    3533        5571 :         VERIFY_TEST( q, "account in transaction missing from bitset mapping" );
    3534        5571 :         VERIFY_TEST( q->ref_cnt>0UL, "account in transaction ref_cnt already 0" );
    3535        5571 :         q->ref_cnt--;
    3536        5571 :         total_references--;
    3537             : 
    3538        5571 :         FD_PACK_BITSET_CLEAR( bit );
    3539        5571 :         FD_PACK_BITSET_SETN( bit, q->bit );
    3540        5571 :         if( q->bit<FD_PACK_BITSET_MAX ) {
    3541        2058 :           VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, cur->rw_bitset, cur->rw_bitset ), "missing from rw bitset" );
    3542        2058 :           VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, cur->w_bitset,  cur->w_bitset  ), "missing from w bitset" );
    3543        2058 :         }
    3544        5571 :         FD_PACK_BITSET_CLEARN( complement, q->bit );
    3545        5571 :       }
    3546        2358 :       VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY( complement, complement, cur->w_bitset,  cur->w_bitset ), "extra in w bitset" );
    3547             : 
    3548        2358 :       for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_READONLY );
    3549        7677 :           iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    3550             : 
    3551        5319 :         fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    3552        5319 :         if( FD_UNLIKELY( fd_pack_unwritable_contains( &acct ) ) ) continue;
    3553        2163 :         fd_pack_bitset_acct_mapping_t * q = bitset_map_query( bitset_copy, acct, NULL );
    3554        2163 :         VERIFY_TEST( q, "account in transaction missing from bitset mapping" );
    3555        2163 :         VERIFY_TEST( q->ref_cnt>0UL, "account in transaction ref_cnt already 0" );
    3556        2163 :         q->ref_cnt--;
    3557        2163 :         total_references--;
    3558             : 
    3559        2163 :         FD_PACK_BITSET_CLEAR( bit );
    3560        2163 :         FD_PACK_BITSET_SETN( bit, q->bit );
    3561        2163 :         if( q->bit<FD_PACK_BITSET_MAX ) {
    3562        2118 :           VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, cur->rw_bitset, cur->rw_bitset ), "missing from rw bitset" );
    3563        2118 :         }
    3564        2163 :         FD_PACK_BITSET_CLEARN( complement, q->bit );
    3565        2163 :       }
    3566        2358 :       VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY( complement, complement, cur->rw_bitset,  cur->rw_bitset ), "extra in rw bitset" );
    3567        2358 :     }
    3568        1911 :   }
    3569             : 
    3570         627 :   bitset_map_leave( bitset_copy );
    3571         627 :   VERIFY_TEST( txn_cnt==pack->pending_txn_cnt, "txn_cnt" );
    3572             : 
    3573         627 :   VERIFY_TEST( total_references==0UL, "extra references in bitset mapping" );
    3574         627 :   ulong sig2txn_key_cnt = 0UL;
    3575         627 :   for( sig2txn_iter_t iter = sig2txn_iter_init( pack->signature_map, pool );
    3576        2985 :       !sig2txn_iter_done( iter, pack->signature_map, pool );
    3577        2358 :       iter = sig2txn_iter_next( iter, pack->signature_map, pool ) ) {
    3578        2358 :     sig2txn_key_cnt++;
    3579        2358 :   }
    3580         627 :   VERIFY_TEST( txn_cnt==sig2txn_key_cnt, "extra signatures in sig2txn" );
    3581         627 :   VERIFY_TEST( !sig2txn_verify( pack->signature_map, trp_pool_max( pool ), pool ), "sig2txn corrupt" );
    3582             : 
    3583             :   /* Count noncemap keys */
    3584         627 :   ulong noncemap_key_cnt = 0UL;
    3585         627 :   for( noncemap_iter_t iter = noncemap_iter_init( pack->noncemap, pool );
    3586         684 :       !noncemap_iter_done( iter, pack->noncemap, pool );
    3587         627 :       iter = noncemap_iter_next( iter, pack->noncemap, pool ) ) {
    3588          57 :     noncemap_key_cnt++;
    3589             :     /* Ensure element is in pool */
    3590          57 :     fd_pack_ord_txn_t const * ord = noncemap_iter_ele_const( iter, pack->noncemap, pool );
    3591          57 :     VERIFY_TEST( ord->txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE, "invalid entry in noncemap" );
    3592             : 
    3593             :     /* Although pack allows multiple transactions with the same
    3594             :        signature in sig2txn (MAP_MULTI==1), the noncemap checks prevent
    3595             :        multiple nonce transactions with the same signature. */
    3596          57 :     VERIFY_TEST( ord==sig2txn_ele_query_const( pack->signature_map, &ord->_txn_e, NULL, pool ), "noncemap and sig2txn desynced" );
    3597          57 :   }
    3598         627 :   VERIFY_TEST( txn_cnt>=noncemap_key_cnt, "phantom txns in noncemap" );
    3599         627 :   VERIFY_TEST( !noncemap_verify( pack->noncemap, trp_pool_max( pool ), pool ), "noncemap corrupt" );
    3600             : 
    3601         627 :   ulong slots_found = 0UL;
    3602         627 :   ulong const pool_max = trp_pool_max( pool );
    3603      525456 :   for( ulong i=0UL; i<pool_max; i++ ) {
    3604      524829 :     fd_pack_ord_txn_t * ord = pack->pool + i;
    3605      524829 :     if( ord->root!=FD_ORD_TXN_ROOT_FREE ) slots_found++;
    3606      524829 :   }
    3607         627 :   VERIFY_TEST( slots_found==txn_cnt, "phantom slots in pool" );
    3608             : 
    3609         627 :   bitset_map_join( _bitset_map_orig );
    3610             : 
    3611         627 :   int lg_uses_tbl_sz = acct_uses_lg_slot_cnt( pack->acct_in_use );
    3612             : 
    3613         627 :   void * _acct_in_use_copy = scratch;
    3614         627 :   void * _acct_in_use_orig = acct_uses_leave( pack->acct_in_use );
    3615         627 :   fd_memcpy( _acct_in_use_copy, _acct_in_use_orig, acct_uses_footprint( lg_uses_tbl_sz ) );
    3616             : 
    3617         627 :   fd_pack_addr_use_t * acct_in_use_copy = acct_uses_join( _acct_in_use_copy );
    3618             : 
    3619         627 :   FD_PACK_BITSET_DECLARE(  w_complement );
    3620         627 :   FD_PACK_BITSET_DECLARE( rw_complement );
    3621         627 :   FD_PACK_BITSET_COPY(  w_complement, full );
    3622         627 :   FD_PACK_BITSET_COPY( rw_complement, full );
    3623             : 
    3624         627 :   FD_PACK_BITSET_DECLARE( rw_bitset );  FD_PACK_BITSET_COPY( rw_bitset, pack->bitset_rw_in_use );
    3625         627 :   FD_PACK_BITSET_DECLARE(  w_bitset );  FD_PACK_BITSET_COPY(  w_bitset, pack->bitset_w_in_use  );
    3626             : 
    3627             : 
    3628         627 :   ulong const EMPTY_MASK = ~(FD_PACK_IN_USE_WRITABLE | FD_PACK_IN_USE_BIT_CLEARED);
    3629             : 
    3630       12627 :   for( ulong bank=0UL; bank<pack->bank_tile_cnt; bank++ ) {
    3631             : 
    3632       12000 :     fd_pack_addr_use_t const * base = pack->use_by_bank[ bank ];
    3633       12000 :     ulong bank_mask = 1UL << bank;
    3634             : 
    3635       12861 :     for( ulong i=0UL; i<pack->use_by_bank_cnt[ bank ]; i++ ) {
    3636         861 :       fd_pack_addr_use_t * use = acct_uses_query( acct_in_use_copy, base[i].key, NULL );
    3637         861 :       VERIFY_TEST( use, "acct in use by bank not in acct_in_use, or in uses_by_bank twice" );
    3638             : 
    3639         861 :       VERIFY_TEST( use->in_use_by & bank_mask, "acct in uses_by_bank doesn't have corresponding bit set in acct_in_use, or it was in the list twice" );
    3640             : 
    3641         861 :       fd_pack_bitset_acct_mapping_t * q = bitset_map_query( pack->acct_to_bitset, base[i].key, NULL );
    3642             :       /* The normal case is that the acct->bit mapping is preserved
    3643             :          while in use by other transactions in the pending list.  This
    3644             :          might not always happen though.  It's okay for the mapping to
    3645             :          get deleted while the acct is in use, which is noted with
    3646             :          BIT_CLEARED.  If that is set, the mapping may not exist, or it
    3647             :          may have been re-created, perhaps with a different bit. */
    3648         861 :       if( q==NULL ) VERIFY_TEST( use->in_use_by & FD_PACK_IN_USE_BIT_CLEARED, "acct in use not in acct_to_bitset, but not marked as cleared" );
    3649           0 :       else if( !(use->in_use_by & FD_PACK_IN_USE_BIT_CLEARED) ) {
    3650           0 :         FD_PACK_BITSET_CLEAR( bit );
    3651           0 :         FD_PACK_BITSET_SETN( bit, q->bit );
    3652           0 :         if( q->bit<FD_PACK_BITSET_MAX ) {
    3653           0 :           VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, rw_bitset, rw_bitset ), "missing from rw bitset" );
    3654           0 :           if( use->in_use_by & FD_PACK_IN_USE_WRITABLE ) {
    3655           0 :             VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, w_bitset, w_bitset ), "missing from w bitset" );
    3656           0 :             FD_PACK_BITSET_CLEARN( w_complement, q->bit );
    3657           0 :           }
    3658           0 :         }
    3659           0 :         FD_PACK_BITSET_CLEARN( rw_complement, q->bit );
    3660           0 :       }
    3661         861 :       if( use->in_use_by & FD_PACK_IN_USE_WRITABLE ) VERIFY_TEST( (use->in_use_by & EMPTY_MASK)==bank_mask, "writable, but in use by multiple" );
    3662             : 
    3663         861 :       use->in_use_by &= ~bank_mask;
    3664         861 :       if( !(use->in_use_by & EMPTY_MASK) ) acct_uses_remove( acct_in_use_copy, use );
    3665         861 :     }
    3666       12000 :   }
    3667         627 :   VERIFY_TEST( acct_uses_key_cnt( acct_in_use_copy )==0UL, "stray uses in acct_in_use" );
    3668         627 :   VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY( rw_complement, rw_complement, rw_bitset,  rw_bitset ), "extra in rw bitset" );
    3669         627 :   VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY(  w_complement,  w_complement,  w_bitset,   w_bitset ), "extra in w bitset" );
    3670             : 
    3671         627 :   acct_uses_leave( acct_in_use_copy );
    3672             : 
    3673         627 :   acct_uses_join( _acct_in_use_orig );
    3674         627 :   return 0;
    3675         627 : }
    3676             : 
    3677         243 : void * fd_pack_leave ( fd_pack_t * pack ) { FD_COMPILER_MFENCE(); return (void *)pack; }
    3678         243 : void * fd_pack_delete( void      * mem  ) { FD_COMPILER_MFENCE(); return mem;          }

Generated by: LCOV version 1.14