LCOV - code coverage report
Current view: top level - disco/pack - fd_pack.c (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 1515 1634 92.7 %
Date: 2025-10-19 04:31:17 Functions: 49 55 89.1 %

          Line data    Source code
       1             : #define FD_UNALIGNED_ACCESS_STYLE 0
       2             : #include "fd_pack.h"
       3             : #include "fd_pack_cost.h"
       4             : #include "fd_pack_bitset.h"
       5             : #include "fd_pack_unwritable.h"
       6             : #include "fd_chkdup.h"
       7             : #include "fd_pack_tip_prog_blacklist.h"
       8             : #include <math.h> /* for sqrt */
       9             : #include <stddef.h> /* for offsetof */
      10             : #include "../metrics/fd_metrics.h"
      11             : 
      12             : #define FD_PACK_USE_NON_TEMPORAL_MEMCPY 1
      13             : 
      14             : /* Declare a bunch of helper structs used for pack-internal data
      15             :    structures. */
      16             : typedef struct {
      17             :   fd_ed25519_sig_t sig;
      18             : } wrapped_sig_t;
      19             : 
      20             : /* fd_pack_ord_txn_t: An fd_txn_p_t with information required to order
      21             :    it by priority. */
      22             : struct fd_pack_private_ord_txn {
      23             :   /* It's important that there be no padding here (asserted below)
      24             :      because the code casts back and forth from pointers to this element
      25             :      to pointers to the whole struct. */
      26             :   union {
      27             :     fd_txn_p_t   txn[1];  /* txn is an alias for txn_e->txnp */
      28             :     fd_txn_e_t   txn_e[1];
      29             :     fd_txn_e_t   _txn_e;  /* Non-array type needed for map_chain */
      30             :     struct{ uchar _sig_cnt; wrapped_sig_t sig; };
      31             :   };
      32             : 
      33             :   /* Since this struct can be in one of several trees, it's helpful to
      34             :      store which tree.  This should be one of the FD_ORD_TXN_ROOT_*
      35             :      values. */
      36             :   int root;
      37             : 
      38             :   /* The sig2txn map_chain fields */
      39             :   ushort sigmap_next;
      40             :   ushort sigmap_prev;
      41             : 
      42             :   /* Each transaction is inserted with an expiration "time."  This code
      43             :      doesn't care about the units (blocks, rdtsc tick, ns, etc.), and
      44             :      doesn't require transactions to be inserted in expiration date
      45             :      order. */
      46             :   ulong expires_at;
      47             :   /* expq_idx: When this object is part of one of the treaps, it's
      48             :      also in the expiration priority queue.  This field (which is
      49             :      manipulated behind the scenes by the fd_prq code) stores where so
      50             :      that if we delete this transaction, we can also delete it from the
      51             :      expiration priority queue. */
      52             :   ulong expq_idx;
      53             : 
      54             :   /* The noncemap map_chain fields */
      55             :   ushort noncemap_next;
      56             :   ushort noncemap_prev;
      57             : 
      58             :   /* We want rewards*compute_est to fit in a ulong so that r1/c1 < r2/c2 can be
      59             :      computed as r1*c2 < r2*c1, with the product fitting in a ulong.
      60             :      compute_est has a small natural limit of mid-20 bits. rewards doesn't have
      61             :      a natural limit, so there is some argument to be made for raising the
      62             :      limit for rewards to 40ish bits. The struct has better packing with
      63             :      uint/uint though. */
      64             :   uint                __attribute__((aligned(64))) /* We want the treap fields and the bitsets
      65             :                                                        to be on the same double cache line pair */
      66             :                rewards;     /* in Lamports */
      67             :   uint         compute_est; /* in compute units */
      68             : 
      69             :   /* The treap fields */
      70             :   ushort left;
      71             :   ushort right;
      72             :   ushort parent;
      73             :   ushort prio;
      74             :   ushort prev;
      75             :   ushort next;
      76             : 
      77             :   /* skip: if we skip this transaction more than FD_PACK_SKIP_CNT times
      78             :      for reasons that won't go away until the end of the block, then we
      79             :      want to skip it very quickly.  If skip is in [1, FD_PACK_SKIP_CNT],
      80             :      then that means we have to skip it `skip` more times before taking
      81             :      any action.  If skip>FD_PACK_SKIP_CNT, then it is a compressed slot
      82             :      number during which it should be skipped, and we'll skip it until
      83             :      the compressed slot reaches a new value.  skip is never 0. */
      84             :   ushort skip;
      85             : 
      86             :   FD_PACK_BITSET_DECLARE( rw_bitset ); /* all accts this txn references */
      87             :   FD_PACK_BITSET_DECLARE(  w_bitset ); /* accts this txn write-locks    */
      88             : 
      89             : };
      90             : typedef struct fd_pack_private_ord_txn fd_pack_ord_txn_t;
      91             : 
      92             : /* What we want is that the payload starts at byte 0 of
      93             :    fd_pack_ord_txn_t so that the trick with the signature map works
      94             :    properly.  GCC and Clang seem to disagree on the rules of offsetof.
      95             :    */
      96             : FD_STATIC_ASSERT( offsetof( fd_pack_ord_txn_t, txn          )==0UL, fd_pack_ord_txn_t );
      97             : FD_STATIC_ASSERT( offsetof( fd_pack_ord_txn_t, sig          )==1UL, fd_pack_ord_txn_t );
      98             : #if FD_USING_CLANG
      99             : FD_STATIC_ASSERT( offsetof( fd_txn_p_t,             payload )==0UL, fd_pack_ord_txn_t );
     100             : #else
     101             : FD_STATIC_ASSERT( offsetof( fd_pack_ord_txn_t, txn->payload )==0UL, fd_pack_ord_txn_t );
     102             : FD_STATIC_ASSERT( offsetof( fd_pack_ord_txn_t, txn_e->txnp  )==0UL, fd_pack_ord_txn_t );
     103             : #endif
     104             : 
     105             : /* FD_ORD_TXN_ROOT is essentially a small union packed into an int.  The low
     106             :    byte is the "tag".  The higher 3 bytes depend on the low byte. */
     107     4452279 : #define FD_ORD_TXN_ROOT_TAG_MASK        0xFF
     108    21625520 : #define FD_ORD_TXN_ROOT_FREE            0
     109    18009638 : #define FD_ORD_TXN_ROOT_PENDING         1
     110    13279608 : #define FD_ORD_TXN_ROOT_PENDING_VOTE    2
     111        1116 : #define FD_ORD_TXN_ROOT_PENDING_BUNDLE  3
     112      328987 : #define FD_ORD_TXN_ROOT_PENALTY( idx ) (4 | (idx)<<8)
     113             : 
     114             : /* if root & TAG_MASK == PENALTY, then PENALTY_ACCT_IDX(root) gives the index
     115             :    in the transaction's list of account addresses of which penalty treap the
     116             :    transaction is in. */
     117             : #define FD_ORD_TXN_ROOT_PENALTY_ACCT_IDX( root ) (((root) & 0xFF00)>>8)
     118             : 
     119    28437275 : #define FD_PACK_IN_USE_WRITABLE    (0x8000000000000000UL)
     120    15389587 : #define FD_PACK_IN_USE_BIT_CLEARED (0x4000000000000000UL)
     121             : 
     122             : /* Each non-empty microblock we schedule also has an overhead of 48
     123             :    bytes that counts towards shed limits.  That comes from the 32 byte
     124             :    hash, the hash count (8 bytes) and the transaction count (8 bytes).
     125             :    We don't have to pay this overhead if the microblock is empty, since
     126             :    those microblocks get dropped. */
     127     1508557 : #define MICROBLOCK_DATA_OVERHEAD 48UL
     128             : 
     129             : /* Keep track of accounts that are written to in each block so that we
     130             :    can reset the writer costs to 0.  If the number of accounts that are
     131             :    written to is above or equal to this, we'll just clear the whole
     132             :    writer cost map instead of only removing the elements we increased. */
     133        1491 : #define DEFAULT_WRITTEN_LIST_MAX 16384UL
     134             : 
     135             : /* fd_pack_addr_use_t: Used for three distinct purposes:
     136             :     -  to record that an address is in use and can't be used again until
     137             :          certain microblocks finish execution
     138             :     -  to keep track of the cost of all transactions that write to the
     139             :          specified account.
     140             :     -  to keep track of the write cost for accounts referenced by
     141             :          transactions in a bundle and which transactions use which
     142             :          accounts.
     143             :    Making these separate structs might make it more clear, but then
     144             :    they'd have identical shape and result in several fd_map_dynamic sets
     145             :    of functions with identical code.  It doesn't seem like the compiler
     146             :    is very good at merging code like that, so in order to reduce code
     147             :    bloat, we'll just combine them. */
     148             : struct fd_pack_private_addr_use_record {
     149             :   fd_acct_addr_t key; /* account address */
     150             :   union {
     151             :     ulong          _;
     152             :     ulong          in_use_by;  /* Bitmask indicating which banks */
     153             :     ulong          total_cost; /* In cost units/CUs */
     154             :     struct { uint    carried_cost;   /* In cost units */
     155             :              ushort  ref_cnt;        /* In transactions */
     156             :              ushort  last_use_in; }; /* In transactions */
     157             :   };
     158             : };
     159             : typedef struct fd_pack_private_addr_use_record fd_pack_addr_use_t;
     160             : 
     161             : 
     162             : /* fd_pack_expq_t: An element of an fd_prq to sort the transactions by
     163             :    timeout.  This structure has several invariants for entries
     164             :    corresponding to pending transactions:
     165             :      expires_at == txn->expires_at
     166             :      txn->exp_prq_idx is the index of this structure
     167             :    Notice that prq is an array-based heap, which means the indexes of
     168             :    elements change.  The PRQ_TMP_ST macro is hijacked to keep that
     169             :    invariant up to date.
     170             : 
     171             :    Note: this could be easier if fd_heap supported deleting from the
     172             :    middle, but that's not possible with the current design of fd_heap,
     173             :    which omits a parent pointer for improved performance. */
     174             : struct fd_pack_expq {
     175             :   ulong               expires_at;
     176             :   fd_pack_ord_txn_t * txn;
     177             : };
     178             : typedef struct fd_pack_expq fd_pack_expq_t;
     179             : 
     180             : 
     181             : /* fd_pack_bitset_acct_mapping_t: An element of an fd_map_dynamic that
     182             :    maps an account address to the number of transactions that are
     183             :    referencing it and the bit that is reserved to indicate it in the
     184             :    bitset, if any. */
     185             : struct fd_pack_bitset_acct_mapping {
     186             :   fd_acct_addr_t key; /* account address */
     187             :   ulong          ref_cnt;
     188             : 
     189             :   /* first_instance and first_instance_was_write are only valid when
     190             :      bit==FD_PACK_BITSET_FIRST_INSTANCE, which is set when ref_cnt
     191             :      transitions from 0 to 1.  These just exist to implement the
     192             :      optimization that accounts referenced a single time aren't
     193             :      allocated a bit, but this seems to be an important optimization. */
     194             :   fd_pack_ord_txn_t * first_instance;
     195             :   int                 first_instance_was_write;
     196             : 
     197             :   /* bit is in [0, FD_PACK_BITSET_MAX) U
     198             :      { FD_PACK_BITSET_FIRST_INSTANCE, FD_PACK_BITSET_SLOWPATH }. */
     199             :   ushort              bit;
     200             : };
     201             : typedef struct fd_pack_bitset_acct_mapping fd_pack_bitset_acct_mapping_t;
     202             : 
     203             : 
     204             : 
     205             : /* pack maintains a small state machine related to initializer bundles.
     206             :    See the header file for more details about it, but it's
     207             :    also summarized here:
     208             :    * NOT_INITIALIZED: The starting state for each block
     209             :    * PENDING: an initializer bundle has been scheduled, but pack has
     210             :      not observed its result yet, so we don't know if it was successful
     211             :      or not.
     212             :    * FAILED: the most recently scheduled initializer bundle failed
     213             :      for reasons other than already being executed.  Most commonly, this
     214             :      could be because of a bug in the code that generated the
     215             :      initializer bundle, a lack of fee payer balance, or an expired
     216             :      blockhash.
     217             :    * READY: the most recently scheduled initialization bundle succeeded
     218             :      and normal bundles can be scheduled in this slot. */
     219        2657 : #define FD_PACK_IB_STATE_NOT_INITIALIZED 0
     220           9 : #define FD_PACK_IB_STATE_PENDING         1
     221           9 : #define FD_PACK_IB_STATE_FAILED          2
     222          27 : #define FD_PACK_IB_STATE_READY           3
     223             : 
     224             : 
     225             : /* Returns 1 if x.rewards/x.compute < y.rewards/y.compute. Not robust. */
     226    84606091 : #define COMPARE_WORSE(x,y) ( ((ulong)((x)->rewards)*(ulong)((y)->compute_est)) < ((ulong)((y)->rewards)*(ulong)((x)->compute_est)) )
     227             : 
     228             : /* Declare all the data structures */
     229             : 
     230             : 
     231             : /* Define the big max-"heap" that we pull transactions off to schedule.
     232             :    The priority is given by reward/compute.  We may want to add in some
     233             :    additional terms at a later point.  In order to cheaply remove nodes,
     234             :    we actually use a treap.  */
     235             : #define POOL_NAME       trp_pool
     236        1674 : #define POOL_T          fd_pack_ord_txn_t
     237             : #define POOL_IDX_T      ushort
     238    31566842 : #define POOL_NEXT       parent
     239             : #include "../../util/tmpl/fd_pool.c"
     240             : 
     241             : #define TREAP_T         fd_pack_ord_txn_t
     242             : #define TREAP_NAME      treap
     243             : #define TREAP_QUERY_T   void *                                         /* We don't use query ... */
     244             : #define TREAP_CMP(a,b)  (__extension__({ (void)(a); (void)(b); -1; })) /* which means we don't need to give a real
     245             :                                                                           implementation to cmp either */
     246   180662462 : #define TREAP_IDX_T     ushort
     247             : #define TREAP_OPTIMIZE_ITERATION 1
     248    84606091 : #define TREAP_LT        COMPARE_WORSE
     249             : #include "../../util/tmpl/fd_treap.c"
     250             : 
     251             : 
     252             : #define MAP_NAME              sig2txn
     253             : #define MAP_OPTIMIZE_RANDOM_ACCESS_REMOVAL 1
     254             : #define MAP_MULTI              1
     255    13582964 : #define MAP_ELE_T              fd_pack_ord_txn_t
     256    36586251 : #define MAP_PREV               sigmap_prev
     257    35019007 : #define MAP_NEXT               sigmap_next
     258    13588243 : #define MAP_IDX_T              ushort
     259             : #define MAP_KEY_T              wrapped_sig_t
     260    26657457 : #define MAP_KEY                sig
     261        1088 : #define MAP_KEY_EQ(k0,k1)      (!memcmp( (k0),(k1), FD_TXN_SIGNATURE_SZ) )
     262    26658531 : #define MAP_KEY_HASH(key,seed) fd_hash( (seed), (key), 64UL )
     263             : #include "../../util/tmpl/fd_map_chain.c"
     264             : 
     265             : 
     266             : /* noncemap: A map from (nonce account, nonce authority, recent
     267             :    blockhash) to a durable nonce transaction containing it.  We only
     268             :    want to allow one transaction in the pool at a time with a given
     269             :    (nonce account, recent blockhash) tuple value.  The question is: can
     270             :    adding this limitation cause us to throw out potentially valuable
     271             :    transaction?  The answer is yes, but only very rarely, and the
     272             :    savings are worth it.  Suppose we have durable nonce transactions t1
     273             :    and t2 that advance the same nonce account and have the same value
     274             :    for the recent blockhash.
     275             : 
     276             :    - If t1 lands on chain, then it will advance the nonce account, and
     277             :    t2 will certainly not land on chain.
     278             :    - If t1 fails with AlreadyExecuted, that means the nonce account was
     279             :    advanced when t1 landed in a previous block, so t2 will certainly not
     280             :    land on chain.
     281             :    - If t1 fails with BlockhashNotFound, then the nonce account was
     282             :    advanced in some previous transaction, so again, t2 will certainly
     283             :    not land on chain.
     284             :    - If t1 does not land on chain because of an issue with the fee
     285             :    payer, it's possible that t2 could land on chain if it used a
     286             :    different fee payer, but historical data shows this is unlikely.
     287             :    - If t1 does not land on chain because it is part of a bundle that
     288             :    fails for an unrelated reason, it's possible that t2 could land on
     289             :    chain, but again, historical data says this is rare.
     290             : 
     291             :    We need to include the nonce authority in the hash to prevent one
     292             :    user from being able to DoS another user. */
     293             : 
     294             : typedef struct {
     295             :   uchar const * recent_blockhash;
     296             :   fd_acct_addr_t const * nonce_acct;
     297             :   fd_acct_addr_t const * nonce_auth;
     298             : } noncemap_extract_t;
     299             : 
     300             : /* k must be a valid, durable nonce transaction.  No error checking is
     301             :    done. */
     302             : static inline void
     303             : noncemap_extract( fd_txn_e_t const   * k,
     304        3378 :                   noncemap_extract_t * out ) {
     305        3378 :   fd_txn_t const * txn = TXN(k->txnp);
     306        3378 :   out->recent_blockhash = fd_txn_get_recent_blockhash( txn, k->txnp->payload );
     307             : 
     308        3378 :   ulong nonce_idx = k->txnp->payload[ txn->instr[ 0 ].acct_off+0 ];
     309        3378 :   ulong autho_idx = k->txnp->payload[ txn->instr[ 0 ].acct_off+2 ];
     310             : 
     311        3378 :   ulong imm_cnt = fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
     312        3378 :   fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, k->txnp->payload );
     313        3378 :   fd_acct_addr_t const * alt_adj = k->alt_accts - imm_cnt;
     314        3378 :   out->nonce_acct = fd_ptr_if( nonce_idx<imm_cnt, accts, alt_adj )+nonce_idx;
     315             :   /* The nonce authority must be a signer, so it must be an immediate
     316             :      account. */
     317        3378 :   out->nonce_auth = accts+autho_idx;
     318        3378 : }
     319             : 
     320             : static inline int
     321             : noncemap_key_eq_internal( fd_txn_e_t const * k0,
     322         171 :                           fd_txn_e_t const * k1 ) {
     323         171 :   noncemap_extract_t e0[1], e1[1];
     324         171 :   noncemap_extract( k0, e0 );
     325         171 :   noncemap_extract( k1, e1 );
     326             : 
     327         171 :   if( FD_UNLIKELY( memcmp( e0->recent_blockhash, e1->recent_blockhash, 32UL ) ) ) return 0;
     328          63 :   if( FD_UNLIKELY( memcmp( e0->nonce_acct,       e1->nonce_acct,       32UL ) ) ) return 0;
     329          63 :   if( FD_UNLIKELY( memcmp( e0->nonce_auth,       e1->nonce_auth,       32UL ) ) ) return 0;
     330          63 :   return 1;
     331          63 : }
     332             : 
     333             : static inline ulong
     334             : noncemap_key_hash_internal( ulong              seed,
     335        3036 :                             fd_txn_e_t const * k ) {
     336             :   /* TODO: This takes >100 cycles! */
     337        3036 :   noncemap_extract_t e[1];
     338        3036 :   noncemap_extract( k, e );
     339        3036 :   return fd_hash( seed,              e->recent_blockhash, 32UL ) ^
     340        3036 :          fd_hash( seed+ 864394383UL, e->nonce_acct,       32UL ) ^
     341        3036 :          fd_hash( seed+3818662446UL, e->nonce_auth,       32UL );
     342        3036 : }
     343             : 
     344             : #define MAP_NAME               noncemap
     345             : #define MAP_OPTIMIZE_RANDOM_ACCESS_REMOVAL 1
     346             : #define MAP_MULTI              0
     347         375 : #define MAP_ELE_T              fd_pack_ord_txn_t
     348         558 : #define MAP_PREV               noncemap_prev
     349        1073 : #define MAP_NEXT               noncemap_next
     350        4221 : #define MAP_IDX_T              ushort
     351             : #define MAP_KEY_T              fd_txn_e_t
     352         756 : #define MAP_KEY                _txn_e
     353         171 : #define MAP_KEY_EQ(k0,k1)      noncemap_key_eq_internal( (k0), (k1) )
     354        3036 : #define MAP_KEY_HASH(key,seed) noncemap_key_hash_internal( (seed), (key) )
     355             : #include "../../util/tmpl/fd_map_chain.c"
     356             : 
     357             : 
     358             : static const fd_acct_addr_t null_addr = { 0 };
     359             : 
     360             : #define MAP_NAME              acct_uses
     361    94476834 : #define MAP_T                 fd_pack_addr_use_t
     362   111477110 : #define MAP_KEY_T             fd_acct_addr_t
     363   347648788 : #define MAP_KEY_NULL          null_addr
     364             : #if FD_HAS_AVX
     365   111477110 : # define MAP_KEY_INVAL(k)     _mm256_testz_si256( wb_ldu( (k).b ), wb_ldu( (k).b ) )
     366             : #else
     367             : # define MAP_KEY_INVAL(k)     MAP_KEY_EQUAL(k, null_addr)
     368             : #endif
     369    77454797 : #define MAP_KEY_EQUAL(k0,k1)  (!memcmp((k0).b,(k1).b, FD_TXN_ACCT_ADDR_SZ))
     370             : #define MAP_KEY_EQUAL_IS_SLOW 1
     371             : #define MAP_MEMOIZE           0
     372    94482921 : #define MAP_KEY_HASH(key)     ((uint)fd_ulong_hash( fd_ulong_load_8( (key).b ) ))
     373             : #include "../../util/tmpl/fd_map_dynamic.c"
     374             : 
     375             : 
     376             : #define MAP_NAME              bitset_map
     377    52428653 : #define MAP_T                 fd_pack_bitset_acct_mapping_t
     378    65768304 : #define MAP_KEY_T             fd_acct_addr_t
     379  1377300677 : #define MAP_KEY_NULL          null_addr
     380             : #if FD_HAS_AVX
     381  1655049072 : # define MAP_KEY_INVAL(k)     _mm256_testz_si256( wb_ldu( (k).b ), wb_ldu( (k).b ) )
     382             : #else
     383             : # define MAP_KEY_INVAL(k)     MAP_KEY_EQUAL(k, null_addr)
     384             : #endif
     385    39125616 : #define MAP_KEY_EQUAL(k0,k1)  (!memcmp((k0).b,(k1).b, FD_TXN_ACCT_ADDR_SZ))
     386             : #define MAP_KEY_EQUAL_IS_SLOW 1
     387             : #define MAP_MEMOIZE           0
     388    52455703 : #define MAP_KEY_HASH(key)     ((uint)fd_ulong_hash( fd_ulong_load_8( (key).b ) ))
     389             : #include "../../util/tmpl/fd_map_dynamic.c"
     390             : 
     391             : 
     392             : /* Since transactions can also expire, we also maintain a parallel
     393             :    priority queue.  This means elements are simultaneously part of the
     394             :    treap (ordered by priority) and the expiration queue (ordered by
     395             :    expiration).  It's tempting to use the priority field of the treap
     396             :    for this purpose, but that can result in degenerate treaps in some
     397             :    cases. */
     398             : #define PRQ_NAME             expq
     399    32839608 : #define PRQ_T                fd_pack_expq_t
     400    27154257 : #define PRQ_TIMEOUT_T        ulong
     401    27154257 : #define PRQ_TIMEOUT          expires_at
     402    15896012 : #define PRQ_TMP_ST(p,t)      do {                                   \
     403    15896012 :                                (p)[0] = (t);                        \
     404    15896012 :                                t.txn->expq_idx = (ulong)((p)-heap); \
     405    15896012 :                              } while( 0 )
     406             : #include "../../util/tmpl/fd_prq.c"
     407             : 
     408             : /* fd_pack_smallest: We want to keep track of the smallest transaction
     409             :    in each treap.  That way, if we know the amount of space left in the
     410             :    block is less than the smallest transaction in the heap, we can just
     411             :    skip the heap.  Since transactions can be deleted, etc. maintaining
     412             :    this precisely is hard, but we can maintain a conservative value
     413             :    fairly cheaply.  Since the CU limit or the byte limit can be the one
     414             :    that matters, we keep track of the smallest by both. */
     415             : struct fd_pack_smallest {
     416             :   ulong cus;
     417             :   ulong bytes;
     418             : };
     419             : typedef struct fd_pack_smallest fd_pack_smallest_t;
     420             : 
     421             : 
     422             : /* With realistic traffic patterns, we often see many, many transactions
     423             :    competing for the same writable account.  Since only one of these can
     424             :    execute at a time, we sometimes waste lots of scheduling time going
     425             :    through them one at a time.  To combat that, when a transaction
     426             :    writes to an account with more than PENALTY_TREAP_THRESHOLD
     427             :    references (readers or writers), instead of inserting it into the
     428             :    main treap, we insert it into a penalty treap for that specific hot
     429             :    account address.  These transactions are not immediately available
     430             :    for scheduling.  Then, when a transaction that writes to the hot
     431             :    address completes, we move the most lucrative transaction from the
     432             :    penalty treap to the main treap, making it available for scheduling.
     433             :    This policy may slightly violate the price-time priority scheduling
     434             :    approach pack normally uses: if the most lucrative transaction
     435             :    competing for hot state arrives after PENALTY_TREAP_THRESHOLD has
     436             :    been hit, it may be scheduled second instead of first.  However, if
     437             :    the account is in use at the time the new transaction arrives, it
     438             :    will be scheduled next, as desired.  This minor difference seems
     439             :    reasonable to reduce complexity.
     440             : 
     441             :    fd_pack_penalty_treap is one account-specific penalty treap.  All the
     442             :    transactions in the penalty_treap treap write to key.
     443             : 
     444             :    penalty_map is the fd_map_dynamic that maps accounts to their
     445             :    respective penalty treaps. */
     446             : struct fd_pack_penalty_treap {
     447             :   fd_acct_addr_t key;
     448             :   treap_t penalty_treap[1];
     449             : };
     450             : typedef struct fd_pack_penalty_treap fd_pack_penalty_treap_t;
     451             : 
     452             : #define MAP_NAME              penalty_map
     453     4239529 : #define MAP_T                 fd_pack_penalty_treap_t
     454     4241313 : #define MAP_KEY_T             fd_acct_addr_t
     455    21315285 : #define MAP_KEY_NULL          null_addr
     456             : #if FD_HAS_AVX
     457    29073825 : # define MAP_KEY_INVAL(k)     _mm256_testz_si256( wb_ldu( (k).b ), wb_ldu( (k).b ) )
     458             : #else
     459             : # define MAP_KEY_INVAL(k)     MAP_KEY_EQUAL(k, null_addr)
     460             : #endif
     461     4235511 : #define MAP_KEY_EQUAL(k0,k1)  (!memcmp((k0).b,(k1).b, FD_TXN_ACCT_ADDR_SZ))
     462             : #define MAP_KEY_EQUAL_IS_SLOW 1
     463             : #define MAP_MEMOIZE           0
     464     4238410 : #define MAP_KEY_HASH(key)     ((uint)fd_ulong_hash( fd_ulong_load_8( (key).b ) ))
     465             : #include "../../util/tmpl/fd_map_dynamic.c"
     466             : 
     467             : /* PENALTY_TREAP_THRESHOLD: How many references to an account do we
     468             :    allow before subsequent transactions that write to the account go to
     469             :    the penalty treap. */
     470    29535405 : #define PENALTY_TREAP_THRESHOLD 64UL
     471             : 
     472             : 
     473             : /* FD_PACK_SKIP_CNT: How many times we'll skip a transaction (for
     474             :    reasons other than account conflicts) before we won't consider it
     475             :    until the next slot.  For performance reasons, this doesn't reset at
     476             :    the end of a slot, so e.g. we might skip twice in slot 1, then three
     477             :    times in slot 2, which would be enough to prevent considering it
     478             :    until slot 3.  The main reason this is not 1 is that some skips that
     479             :    seem permanent until the end of the slot can actually go away based
     480             :    on rebates. */
     481    13587788 : #define FD_PACK_SKIP_CNT 50UL
     482             : 
     483             : /* Finally, we can now declare the main pack data structure */
     484             : struct fd_pack_private {
     485             :   ulong      pack_depth;
     486             :   ulong      bundle_meta_sz; /* if 0, bundles are disabled */
     487             :   ulong      bank_tile_cnt;
     488             : 
     489             :   fd_pack_limits_t lim[1];
     490             : 
     491             :   ulong      pending_txn_cnt; /* Summed across all treaps */
     492             :   ulong      microblock_cnt; /* How many microblocks have we
     493             :                                 generated in this block? */
     494             :   ulong      data_bytes_consumed; /* How much data is in this block so
     495             :                                      far ? */
     496             :   fd_rng_t * rng;
     497             : 
     498             :   ulong      cumulative_block_cost;
     499             :   ulong      cumulative_vote_cost;
     500             : 
     501             :   /* expire_before: Any transactions with expires_at strictly less than
     502             :      the current expire_before are removed from the available pending
     503             :      transaction.  Here, "expire" is used as a verb: cause all
     504             :      transactions before this time to expire. */
     505             :   ulong      expire_before;
     506             : 
     507             :   /* outstanding_microblock_mask: a bitmask indicating which banking
     508             :      tiles have outstanding microblocks, i.e. fd_pack has generated a
     509             :      microblock for that banking tile and the banking tile has not yet
     510             :      notified fd_pack that it has completed it. */
     511             :   ulong      outstanding_microblock_mask;
     512             : 
     513             :   /* The actual footprint for the pool and maps is allocated
     514             :      in the same order in which they are declared immediately following
     515             :      the struct.  I.e. these pointers point to memory not far after the
     516             :      struct.  The trees are just pointers into the pool so don't take up
     517             :      more space. */
     518             : 
     519             :   fd_pack_ord_txn_t * pool;
     520             : 
     521             :   /* Treaps (sorted by priority) of pending transactions.  We store the
     522             :      pending simple votes and transactions that come from bundles
     523             :      separately. */
     524             :   treap_t pending[1];
     525             :   treap_t pending_votes[1];
     526             :   treap_t pending_bundles[1];
     527             : 
     528             :   /* penalty_treaps: an fd_map_dynamic mapping hotly contended account
     529             :      addresses to treaps of transactions that write to them.  We try not
     530             :      to allow more than roughly PENALTY_TREAP_THRESHOLD transactions in
     531             :      the main treap that write to each account, though this is not
     532             :      exact. */
     533             :   fd_pack_penalty_treap_t * penalty_treaps;
     534             : 
     535             :   /* initializer_bundle_state: The current state of the initialization
     536             :      bundle state machine.  One of the FD_PACK_IB_STATE_* values.  See
     537             :      the long comment in the header and the comments attached to the
     538             :      respective values for a discussion of what each state means and the
     539             :      transitions between them. */
     540             :   int   initializer_bundle_state;
     541             : 
     542             :   /* relative_bundle_idx: the number of bundles that have been inserted
     543             :      since the last time pending_bundles was empty.  See the long
     544             :      comment about encoding this index in the rewards field of each
     545             :      transaction in the bundle, and why it is important that this reset
     546             :      to 0 as frequently as possible. */
     547             :   ulong relative_bundle_idx;
     548             : 
     549             :   /* pending{_votes}_smallest: keep a conservative estimate of the
     550             :      smallest transaction (by cost units and by bytes) in each heap.
     551             :      Both CUs and bytes should be set to ULONG_MAX is the treap is
     552             :      empty. */
     553             :   fd_pack_smallest_t pending_smallest[1];
     554             :   fd_pack_smallest_t pending_votes_smallest[1];
     555             : 
     556             :   /* expiration_q: At the same time that a transaction is in exactly one
     557             :      of the above treaps, it is also in the expiration queue, sorted by
     558             :      its expiration time.  This enables deleting all transactions that
     559             :      have expired, regardless of which treap they are in. */
     560             :   fd_pack_expq_t * expiration_q;
     561             : 
     562             :   /* acct_in_use: Map from account address to bitmask indicating which
     563             :      bank tiles are using the account and whether that use is read or
     564             :      write (msb). */
     565             :   fd_pack_addr_use_t   * acct_in_use;
     566             : 
     567             :   /* bitset_{w, rw}_in_use stores a subset of the information in
     568             :      acct_in_use using the compressed set format explained at the top of
     569             :      this file.  rw_in_use stores accounts in use for read or write
     570             :      while w_in_use stores only those in use for write. */
     571             :   FD_PACK_BITSET_DECLARE( bitset_rw_in_use );
     572             :   FD_PACK_BITSET_DECLARE( bitset_w_in_use  );
     573             : 
     574             :   /* writer_costs: Map from account addresses to the sum of costs of
     575             :      transactions that write to the account.  Used for enforcing limits
     576             :      on the max write cost per account per block. */
     577             :   fd_pack_addr_use_t   * writer_costs;
     578             : 
     579             :   /* At the end of every slot, we have to clear out writer_costs.  The
     580             :      map is large, but typically very sparsely populated.  As an
     581             :      optimization, we keep track of the elements of the map that we've
     582             :      actually used, up to a maximum.  If we use more than the maximum,
     583             :      we revert to the old way of just clearing the whole map.
     584             : 
     585             :      written_list indexed [0, written_list_cnt).
     586             :      written_list_cnt in  [0, written_list_max).
     587             : 
     588             :      written_list_cnt==written_list_max-1 means that the list may be
     589             :      incomplete and should be ignored. */
     590             :   fd_pack_addr_use_t * * written_list;
     591             :   ulong                  written_list_cnt;
     592             :   ulong                  written_list_max;
     593             : 
     594             :   /* Noncemap is a map_chain that maps from tuples (nonce account,
     595             :      recent blockhash value, nonce authority) to a transaction.  This
     596             :      map stores exactly the transactions in pool that have the nonce
     597             :      flag set. */
     598             :   noncemap_t * noncemap;
     599             : 
     600             :   sig2txn_t * signature_map; /* Stores pointers into pool for deleting by signature */
     601             : 
     602             :   /* bundle_temp_map: A fd_map_dynamic (although it could be an fd_map)
     603             :      used during fd_pack_try_schedule_bundle to store information about
     604             :      what accounts are used by transactions in the bundle.  It's empty
     605             :      (in a map sense) outside of calls to try_schedule_bundle, and each
     606             :      call to try_schedule_bundle clears it after use.  If bundles are
     607             :      disabled, this is a valid fd_map_dynamic, but it's as small as
     608             :      convenient and remains empty. */
     609             :   fd_pack_addr_use_t * bundle_temp_map;
     610             : 
     611             : 
     612             :   /* use_by_bank: An array of size (max_txn_per_microblock *
     613             :      FD_TXN_ACCT_ADDR_MAX) for each banking tile.  Only the MSB of
     614             :      in_use_by is relevant.  Addressed use_by_bank[i][j] where i is in
     615             :      [0, bank_tile_cnt) and j is in [0, use_by_bank_cnt[i]).  Used
     616             :      mostly for clearing the proper bits of acct_in_use when a
     617             :      microblock finishes.
     618             : 
     619             :      use_by_bank_txn: indexed [i][j], where i is in [0, bank_tile_cnt)
     620             :      and j is in [0, max_txn_per_microblock).  Transaction j in the
     621             :      microblock currently scheduled to bank i uses account addresses in
     622             :      use_by_bank[i][k] where k is in [0, use_by_bank[i][j]).  For
     623             :      example, if use_by_bank[i][0] = 2 and use_by_bank[i][1] = 3, then
     624             :      all the accounts that the first transaction in the outstanding
     625             :      microblock for bank 0 uses are contained in the set
     626             :                { use_by_bank[i][0], use_by_bank[i][1] },
     627             :      and all the accounts in the second transaction in the microblock
     628             :      are in the set
     629             :         { use_by_bank[i][0], use_by_bank[i][1], use_by_bank[i][2] }.
     630             :      Each transaction writes to at least one account (the fee payer)
     631             :      that no other transaction scheduled to the bank uses, which means
     632             :      that use_by_bank_txn[i][j] - use_by_bank_txn[i][j-1] >= 1 (with 0
     633             :      for use_by_bank_txn[i][-1]).  This means we can stop iterating when
     634             :      use_by_bank_txn[i][j] == use_by_bank_cnt[i].  */
     635             :   fd_pack_addr_use_t * use_by_bank    [ FD_PACK_MAX_BANK_TILES ];
     636             :   ulong                use_by_bank_cnt[ FD_PACK_MAX_BANK_TILES ];
     637             :   ulong *              use_by_bank_txn[ FD_PACK_MAX_BANK_TILES ];
     638             : 
     639             :   fd_histf_t txn_per_microblock [ 1 ];
     640             :   fd_histf_t vote_per_microblock[ 1 ];
     641             : 
     642             :   fd_histf_t scheduled_cus_per_block[ 1 ];
     643             :   fd_histf_t rebated_cus_per_block  [ 1 ];
     644             :   fd_histf_t net_cus_per_block      [ 1 ];
     645             :   fd_histf_t pct_cus_per_block      [ 1 ];
     646             :   ulong      cumulative_rebated_cus;
     647             : 
     648             : 
     649             :   /* compressed_slot_number: a number in (FD_PACK_SKIP_CNT, USHORT_MAX]
     650             :      that advances each time we start packing for a new slot. */
     651             :   ushort     compressed_slot_number;
     652             : 
     653             :   /* bitset_avail: a stack of which bits are not currently reserved and
     654             :      can be used to represent an account address.
     655             :      Indexed [0, bitset_avail_cnt].  Element 0 is fixed at
     656             :      FD_PACK_BITSET_SLOWPATH. */
     657             :   ushort bitset_avail[ 1UL+FD_PACK_BITSET_MAX ];
     658             :   ulong  bitset_avail_cnt;
     659             : 
     660             :   /* acct_to_bitset: an fd_map_dynamic that maps acct addresses to the
     661             :      reference count, which bit, etc. */
     662             :   fd_pack_bitset_acct_mapping_t * acct_to_bitset;
     663             : 
     664             :   /* chdkup: scratch memory chkdup needs for its internal processing */
     665             :   fd_chkdup_t chkdup[ 1 ];
     666             : 
     667             :   /* bundle_meta: an array, parallel to the pool, with each element
     668             :      having size bundle_meta_sz.  I.e. if pool[i] has an associated
     669             :      bundle meta, it's located at bundle_meta[j] for j in
     670             :      [i*bundle_meta_sz, (i+1)*bundle_meta_sz). */
     671             :   void * bundle_meta;
     672             : };
     673             : 
     674             : typedef struct fd_pack_private fd_pack_t;
     675             : 
     676             : FD_STATIC_ASSERT( offsetof(fd_pack_t, pending_txn_cnt)==FD_PACK_PENDING_TXN_CNT_OFF, txn_cnt_off );
     677             : 
     678             : /* Forward-declare some helper functions */
     679             : static ulong delete_transaction( fd_pack_t * pack, fd_pack_ord_txn_t * txn, int delete_full_bundle, int move_from_penalty_treap );
     680             : 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 );
     681             : 
     682             : FD_FN_PURE ulong
     683             : fd_pack_footprint( ulong                    pack_depth,
     684             :                    ulong                    bundle_meta_sz,
     685             :                    ulong                    bank_tile_cnt,
     686         375 :                    fd_pack_limits_t const * limits         ) {
     687         375 :   if( FD_UNLIKELY( (bank_tile_cnt==0) | (bank_tile_cnt>FD_PACK_MAX_BANK_TILES) ) ) return 0UL;
     688         375 :   if( FD_UNLIKELY( pack_depth<4UL ) ) return 0UL;
     689             : 
     690         375 :   int enable_bundles = !!bundle_meta_sz;
     691         375 :   ulong l;
     692         375 :   ulong extra_depth        = fd_ulong_if( enable_bundles, 1UL+2UL*FD_PACK_MAX_TXN_PER_BUNDLE, 1UL ); /* space for use between init and fini */
     693         375 :   ulong max_acct_in_treap  = pack_depth * FD_TXN_ACCT_ADDR_MAX;
     694         375 :   ulong max_txn_per_mblk   = fd_ulong_max( limits->max_txn_per_microblock,
     695         375 :                                            fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE, 0UL ) );
     696         375 :   ulong max_acct_in_flight = bank_tile_cnt * (FD_TXN_ACCT_ADDR_MAX * max_txn_per_mblk + 1UL);
     697         375 :   ulong max_txn_in_flight  = bank_tile_cnt * max_txn_per_mblk;
     698             : 
     699         375 :   ulong max_w_per_block    = fd_ulong_min( limits->max_cost_per_block / FD_PACK_COST_PER_WRITABLE_ACCT,
     700         375 :                                            max_txn_per_mblk * limits->max_microblocks_per_block * FD_TXN_ACCT_ADDR_MAX );
     701         375 :   ulong written_list_max   = fd_ulong_min( max_w_per_block>>1, DEFAULT_WRITTEN_LIST_MAX );
     702         375 :   ulong bundle_temp_accts  = fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE*FD_TXN_ACCT_ADDR_MAX, 1UL );
     703         375 :   ulong sig_chain_cnt      = sig2txn_chain_cnt_est( pack_depth );
     704         375 :   ulong nonce_chain_cnt    = noncemap_chain_cnt_est( pack_depth );
     705             : 
     706             :   /* log base 2, but with a 2* so that the hash table stays sparse */
     707         375 :   int lg_uses_tbl_sz = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_flight                        ) );
     708         375 :   int lg_max_writers = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_w_per_block                           ) );
     709         375 :   int lg_acct_in_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap                         ) );
     710         375 :   int lg_penalty_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap/PENALTY_TREAP_THRESHOLD ) );
     711         375 :   int lg_bundle_temp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*bundle_temp_accts                         ) );
     712             : 
     713         375 :   l = FD_LAYOUT_INIT;
     714         375 :   l = FD_LAYOUT_APPEND( l, FD_PACK_ALIGN,       sizeof(fd_pack_t)                               );
     715         375 :   l = FD_LAYOUT_APPEND( l, trp_pool_align (),   trp_pool_footprint ( pack_depth+extra_depth   ) ); /* pool           */
     716         375 :   l = FD_LAYOUT_APPEND( l, penalty_map_align(), penalty_map_footprint( lg_penalty_trp         ) ); /* penalty_treaps */
     717         375 :   l = FD_LAYOUT_APPEND( l, expq_align     (),   expq_footprint     ( pack_depth               ) ); /* expiration prq */
     718         375 :   l = FD_LAYOUT_APPEND( l, acct_uses_align(),   acct_uses_footprint( lg_uses_tbl_sz           ) ); /* acct_in_use    */
     719         375 :   l = FD_LAYOUT_APPEND( l, acct_uses_align(),   acct_uses_footprint( lg_max_writers           ) ); /* writer_costs   */
     720         375 :   l = FD_LAYOUT_APPEND( l, 32UL,                sizeof(fd_pack_addr_use_t*)*written_list_max    ); /* written_list   */
     721         375 :   l = FD_LAYOUT_APPEND( l, noncemap_align (),   noncemap_footprint ( nonce_chain_cnt          ) ); /* noncemap       */
     722         375 :   l = FD_LAYOUT_APPEND( l, sig2txn_align  (),   sig2txn_footprint  ( sig_chain_cnt            ) ); /* signature_map  */
     723         375 :   l = FD_LAYOUT_APPEND( l, acct_uses_align(),   acct_uses_footprint( lg_bundle_temp           ) ); /* bundle_temp_map*/
     724         375 :   l = FD_LAYOUT_APPEND( l, 32UL,                sizeof(fd_pack_addr_use_t)*max_acct_in_flight   ); /* use_by_bank    */
     725         375 :   l = FD_LAYOUT_APPEND( l, 32UL,                sizeof(ulong)*max_txn_in_flight                 ); /* use_by_bank_txn*/
     726         375 :   l = FD_LAYOUT_APPEND( l, bitset_map_align(),  bitset_map_footprint( lg_acct_in_trp          ) ); /* acct_to_bitset */
     727         375 :   l = FD_LAYOUT_APPEND( l, 64UL,                (pack_depth+extra_depth)*bundle_meta_sz         ); /* bundle_meta */
     728         375 :   return FD_LAYOUT_FINI( l, FD_PACK_ALIGN );
     729         375 : }
     730             : 
     731             : void *
     732             : fd_pack_new( void                   * mem,
     733             :              ulong                    pack_depth,
     734             :              ulong                    bundle_meta_sz,
     735             :              ulong                    bank_tile_cnt,
     736             :              fd_pack_limits_t const * limits,
     737         558 :              fd_rng_t               * rng           ) {
     738             : 
     739         558 :   int enable_bundles = !!bundle_meta_sz;
     740         558 :   ulong extra_depth        = fd_ulong_if( enable_bundles, 1UL+2UL*FD_PACK_MAX_TXN_PER_BUNDLE, 1UL );
     741         558 :   ulong max_acct_in_treap  = pack_depth * FD_TXN_ACCT_ADDR_MAX;
     742         558 :   ulong max_txn_per_mblk   = fd_ulong_max( limits->max_txn_per_microblock,
     743         558 :                                            fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE, 0UL ) );
     744         558 :   ulong max_acct_in_flight = bank_tile_cnt * (FD_TXN_ACCT_ADDR_MAX * max_txn_per_mblk + 1UL);
     745         558 :   ulong max_txn_in_flight  = bank_tile_cnt * max_txn_per_mblk;
     746             : 
     747         558 :   ulong max_w_per_block    = fd_ulong_min( limits->max_cost_per_block / FD_PACK_COST_PER_WRITABLE_ACCT,
     748         558 :                                            max_txn_per_mblk * limits->max_microblocks_per_block * FD_TXN_ACCT_ADDR_MAX );
     749         558 :   ulong written_list_max   = fd_ulong_min( max_w_per_block>>1, DEFAULT_WRITTEN_LIST_MAX );
     750         558 :   ulong bundle_temp_accts  = fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE*FD_TXN_ACCT_ADDR_MAX, 1UL );
     751         558 :   ulong sig_chain_cnt      = sig2txn_chain_cnt_est( pack_depth );
     752         558 :   ulong nonce_chain_cnt    = noncemap_chain_cnt_est( pack_depth );
     753             : 
     754             :   /* log base 2, but with a 2* so that the hash table stays sparse */
     755         558 :   int lg_uses_tbl_sz = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_flight                        ) );
     756         558 :   int lg_max_writers = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_w_per_block                           ) );
     757         558 :   int lg_acct_in_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap                         ) );
     758         558 :   int lg_penalty_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap/PENALTY_TREAP_THRESHOLD ) );
     759         558 :   int lg_bundle_temp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*bundle_temp_accts                         ) );
     760             : 
     761         558 :   FD_SCRATCH_ALLOC_INIT( l, mem );
     762         558 :   fd_pack_t * pack    = FD_SCRATCH_ALLOC_APPEND( l,  FD_PACK_ALIGN,       sizeof(fd_pack_t)                             );
     763             :   /* The pool has one extra element that is used between insert_init and
     764             :      cancel/fini. */
     765         558 :   void * _pool        = FD_SCRATCH_ALLOC_APPEND( l,  trp_pool_align(),    trp_pool_footprint ( pack_depth+extra_depth ) );
     766         558 :   void * _penalty_map = FD_SCRATCH_ALLOC_APPEND( l,  penalty_map_align(), penalty_map_footprint( lg_penalty_trp       ) );
     767         558 :   void * _expq        = FD_SCRATCH_ALLOC_APPEND( l,  expq_align(),        expq_footprint     ( pack_depth             ) );
     768         558 :   void * _uses        = FD_SCRATCH_ALLOC_APPEND( l,  acct_uses_align(),   acct_uses_footprint( lg_uses_tbl_sz         ) );
     769         558 :   void * _writer_cost = FD_SCRATCH_ALLOC_APPEND( l,  acct_uses_align(),   acct_uses_footprint( lg_max_writers         ) );
     770         558 :   void * _written_lst = FD_SCRATCH_ALLOC_APPEND( l,  32UL,                sizeof(fd_pack_addr_use_t*)*written_list_max  );
     771         558 :   void * _noncemap    = FD_SCRATCH_ALLOC_APPEND( l,  noncemap_align(),    noncemap_footprint ( nonce_chain_cnt        ) );
     772         558 :   void * _sig_map     = FD_SCRATCH_ALLOC_APPEND( l,  sig2txn_align(),     sig2txn_footprint  ( sig_chain_cnt          ) );
     773         558 :   void * _bundle_temp = FD_SCRATCH_ALLOC_APPEND( l,  acct_uses_align(),   acct_uses_footprint( lg_bundle_temp         ) );
     774         558 :   void * _use_by_bank = FD_SCRATCH_ALLOC_APPEND( l,  32UL,                sizeof(fd_pack_addr_use_t)*max_acct_in_flight );
     775         558 :   void * _use_by_txn  = FD_SCRATCH_ALLOC_APPEND( l,  32UL,                sizeof(ulong)*max_txn_in_flight               );
     776         558 :   void * _acct_bitset = FD_SCRATCH_ALLOC_APPEND( l,  bitset_map_align(),  bitset_map_footprint( lg_acct_in_trp        ) );
     777         558 :   void * bundle_meta  = FD_SCRATCH_ALLOC_APPEND( l,  64UL,                (pack_depth+extra_depth)*bundle_meta_sz       );
     778             : 
     779           0 :   pack->pack_depth                  = pack_depth;
     780         558 :   pack->bundle_meta_sz              = bundle_meta_sz;
     781         558 :   pack->bank_tile_cnt               = bank_tile_cnt;
     782         558 :   pack->lim[0]                      = *limits;
     783         558 :   pack->pending_txn_cnt             = 0UL;
     784         558 :   pack->microblock_cnt              = 0UL;
     785         558 :   pack->data_bytes_consumed         = 0UL;
     786         558 :   pack->rng                         = rng;
     787         558 :   pack->cumulative_block_cost       = 0UL;
     788         558 :   pack->cumulative_vote_cost        = 0UL;
     789         558 :   pack->expire_before               = 0UL;
     790         558 :   pack->outstanding_microblock_mask = 0UL;
     791         558 :   pack->cumulative_rebated_cus      = 0UL;
     792             : 
     793             : 
     794         558 :   trp_pool_new(  _pool,        pack_depth+extra_depth );
     795             : 
     796         558 :   fd_pack_ord_txn_t * pool = trp_pool_join( _pool );
     797         558 :   treap_seed( pool, pack_depth+extra_depth, fd_rng_ulong( rng ) );
     798     4152228 :   for( ulong i=0UL; i<pack_depth+extra_depth; i++ ) pool[i].root = FD_ORD_TXN_ROOT_FREE;
     799             : 
     800         558 :   (void)trp_pool_leave( pool );
     801             : 
     802         558 :   penalty_map_new( _penalty_map, lg_penalty_trp );
     803             : 
     804             :   /* These treaps can have at most pack_depth elements at any moment,
     805             :      but they come from a pool of size pack_depth+extra_depth. */
     806         558 :   treap_new( (void*)pack->pending,         pack_depth+extra_depth );
     807         558 :   treap_new( (void*)pack->pending_votes,   pack_depth+extra_depth );
     808         558 :   treap_new( (void*)pack->pending_bundles, pack_depth+extra_depth );
     809             : 
     810         558 :   pack->pending_smallest->cus         = ULONG_MAX;
     811         558 :   pack->pending_smallest->bytes       = ULONG_MAX;
     812         558 :   pack->pending_votes_smallest->cus   = ULONG_MAX;
     813         558 :   pack->pending_votes_smallest->bytes = ULONG_MAX;
     814             : 
     815         558 :   expq_new( _expq, pack_depth );
     816             : 
     817         558 :   FD_PACK_BITSET_CLEAR( pack->bitset_rw_in_use );
     818         558 :   FD_PACK_BITSET_CLEAR( pack->bitset_w_in_use  );
     819             : 
     820         558 :   acct_uses_new( _uses,        lg_uses_tbl_sz );
     821         558 :   acct_uses_new( _writer_cost, lg_max_writers );
     822         558 :   acct_uses_new( _bundle_temp, lg_bundle_temp );
     823             : 
     824         558 :   pack->written_list     = _written_lst;
     825         558 :   pack->written_list_cnt = 0UL;
     826         558 :   pack->written_list_max = written_list_max;
     827             : 
     828         558 :   noncemap_new( _noncemap, nonce_chain_cnt, fd_rng_ulong( rng ) );
     829             : 
     830         558 :   sig2txn_new( _sig_map, sig_chain_cnt, fd_rng_ulong( rng ) );
     831             : 
     832         558 :   fd_pack_addr_use_t * use_by_bank     = (fd_pack_addr_use_t *)_use_by_bank;
     833         558 :   ulong *              use_by_bank_txn = (ulong *)_use_by_txn;
     834        6843 :   for( ulong i=0UL; i<bank_tile_cnt; i++ ) {
     835        6285 :     pack->use_by_bank    [i] = use_by_bank + i*(FD_TXN_ACCT_ADDR_MAX*max_txn_per_mblk+1UL);
     836        6285 :     pack->use_by_bank_cnt[i] = 0UL;
     837        6285 :     pack->use_by_bank_txn[i] = use_by_bank_txn + i*max_txn_per_mblk;
     838        6285 :     pack->use_by_bank_txn[i][0] = 0UL;
     839        6285 :   }
     840       28869 :   for( ulong i=bank_tile_cnt; i<FD_PACK_MAX_BANK_TILES; i++ ) {
     841       28311 :     pack->use_by_bank    [i] = NULL;
     842       28311 :     pack->use_by_bank_cnt[i] = 0UL;
     843       28311 :     pack->use_by_bank_txn[i] = NULL;
     844       28311 :   }
     845             : 
     846         558 :   fd_histf_new( pack->txn_per_microblock,  FD_MHIST_MIN( PACK, TOTAL_TRANSACTIONS_PER_MICROBLOCK_COUNT ),
     847         558 :                                            FD_MHIST_MAX( PACK, TOTAL_TRANSACTIONS_PER_MICROBLOCK_COUNT ) );
     848         558 :   fd_histf_new( pack->vote_per_microblock, FD_MHIST_MIN( PACK, VOTES_PER_MICROBLOCK_COUNT ),
     849         558 :                                            FD_MHIST_MAX( PACK, VOTES_PER_MICROBLOCK_COUNT ) );
     850             : 
     851         558 :   fd_histf_new( pack->scheduled_cus_per_block, FD_MHIST_MIN( PACK, CUS_SCHEDULED ),
     852         558 :                                                FD_MHIST_MAX( PACK, CUS_SCHEDULED ) );
     853         558 :   fd_histf_new( pack->rebated_cus_per_block,   FD_MHIST_MIN( PACK, CUS_REBATED   ),
     854         558 :                                                FD_MHIST_MAX( PACK, CUS_REBATED   ) );
     855         558 :   fd_histf_new( pack->net_cus_per_block,       FD_MHIST_MIN( PACK, CUS_NET       ),
     856         558 :                                                FD_MHIST_MAX( PACK, CUS_NET       ) );
     857         558 :   fd_histf_new( pack->pct_cus_per_block,       FD_MHIST_MIN( PACK, CUS_PCT       ),
     858         558 :                                                FD_MHIST_MAX( PACK, CUS_PCT       ) );
     859             : 
     860         558 :   pack->compressed_slot_number = (ushort)(FD_PACK_SKIP_CNT+1);
     861             : 
     862         558 :   pack->bitset_avail[ 0 ] = FD_PACK_BITSET_SLOWPATH;
     863      191022 :   for( ulong i=0UL; i<FD_PACK_BITSET_MAX; i++ ) pack->bitset_avail[ i+1UL ] = (ushort)i;
     864         558 :   pack->bitset_avail_cnt = FD_PACK_BITSET_MAX;
     865             : 
     866         558 :   bitset_map_new( _acct_bitset, lg_acct_in_trp );
     867             : 
     868         558 :   fd_chkdup_new( pack->chkdup, rng );
     869             : 
     870         558 :   pack->bundle_meta = bundle_meta;
     871             : 
     872         558 :   return mem;
     873         558 : }
     874             : 
     875             : fd_pack_t *
     876         558 : fd_pack_join( void * mem ) {
     877         558 :   FD_SCRATCH_ALLOC_INIT( l, mem );
     878         558 :   fd_pack_t * pack  = FD_SCRATCH_ALLOC_APPEND( l, FD_PACK_ALIGN, sizeof(fd_pack_t) );
     879             : 
     880           0 :   int enable_bundles = !!pack->bundle_meta_sz;
     881         558 :   ulong pack_depth             = pack->pack_depth;
     882         558 :   ulong extra_depth            = fd_ulong_if( enable_bundles, 1UL+2UL*FD_PACK_MAX_TXN_PER_BUNDLE, 1UL );
     883         558 :   ulong bank_tile_cnt          = pack->bank_tile_cnt;
     884         558 :   ulong max_txn_per_microblock = fd_ulong_max( pack->lim->max_txn_per_microblock,
     885         558 :                                                fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE, 0UL ) );
     886             : 
     887         558 :   ulong max_acct_in_treap  = pack_depth * FD_TXN_ACCT_ADDR_MAX;
     888         558 :   ulong max_acct_in_flight = bank_tile_cnt * (FD_TXN_ACCT_ADDR_MAX * max_txn_per_microblock + 1UL);
     889         558 :   ulong max_txn_in_flight  = bank_tile_cnt * max_txn_per_microblock;
     890         558 :   ulong max_w_per_block    = fd_ulong_min( pack->lim->max_cost_per_block / FD_PACK_COST_PER_WRITABLE_ACCT,
     891         558 :                                            max_txn_per_microblock * pack->lim->max_microblocks_per_block * FD_TXN_ACCT_ADDR_MAX );
     892         558 :   ulong written_list_max   = fd_ulong_min( max_w_per_block>>1, DEFAULT_WRITTEN_LIST_MAX );
     893         558 :   ulong bundle_temp_accts  = fd_ulong_if( enable_bundles, FD_PACK_MAX_TXN_PER_BUNDLE*FD_TXN_ACCT_ADDR_MAX, 1UL );
     894         558 :   ulong sig_chain_cnt      = sig2txn_chain_cnt_est( pack_depth );
     895         558 :   ulong nonce_chain_cnt    = noncemap_chain_cnt_est( pack_depth );
     896             : 
     897         558 :   int lg_uses_tbl_sz = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_flight                        ) );
     898         558 :   int lg_max_writers = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_w_per_block                           ) );
     899         558 :   int lg_acct_in_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap                         ) );
     900         558 :   int lg_penalty_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap/PENALTY_TREAP_THRESHOLD ) );
     901         558 :   int lg_bundle_temp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*bundle_temp_accts                         ) );
     902             : 
     903             : 
     904         558 :   pack->pool          = trp_pool_join(   FD_SCRATCH_ALLOC_APPEND( l, trp_pool_align(),   trp_pool_footprint   ( pack_depth+extra_depth  ) ) );
     905         558 :   pack->penalty_treaps= penalty_map_join(FD_SCRATCH_ALLOC_APPEND( l, penalty_map_align(),penalty_map_footprint( lg_penalty_trp          ) ) );
     906         558 :   pack->expiration_q  = expq_join    (   FD_SCRATCH_ALLOC_APPEND( l, expq_align(),       expq_footprint       ( pack_depth              ) ) );
     907         558 :   pack->acct_in_use   = acct_uses_join(  FD_SCRATCH_ALLOC_APPEND( l, acct_uses_align(),  acct_uses_footprint  ( lg_uses_tbl_sz          ) ) );
     908         558 :   pack->writer_costs  = acct_uses_join(  FD_SCRATCH_ALLOC_APPEND( l, acct_uses_align(),  acct_uses_footprint  ( lg_max_writers          ) ) );
     909         558 :   /* */                                  FD_SCRATCH_ALLOC_APPEND( l, 32UL,               sizeof(fd_pack_addr_use_t*)*written_list_max       );
     910         558 :   pack->noncemap      = noncemap_join(   FD_SCRATCH_ALLOC_APPEND( l, noncemap_align(),   noncemap_footprint   ( nonce_chain_cnt         ) ) );
     911         558 :   pack->signature_map = sig2txn_join(    FD_SCRATCH_ALLOC_APPEND( l, sig2txn_align(),    sig2txn_footprint    ( sig_chain_cnt           ) ) );
     912         558 :   pack->bundle_temp_map=acct_uses_join(  FD_SCRATCH_ALLOC_APPEND( l, acct_uses_align(),  acct_uses_footprint  ( lg_bundle_temp          ) ) );
     913         558 :   /* */                                  FD_SCRATCH_ALLOC_APPEND( l, 32UL,               sizeof(fd_pack_addr_use_t)*max_acct_in_flight      );
     914         558 :   /* */                                  FD_SCRATCH_ALLOC_APPEND( l, 32UL,               sizeof(ulong)*max_txn_in_flight                    );
     915         558 :   pack->acct_to_bitset= bitset_map_join( FD_SCRATCH_ALLOC_APPEND( l, bitset_map_align(), bitset_map_footprint( lg_acct_in_trp           ) ) );
     916         558 :   /* */                                  FD_SCRATCH_ALLOC_APPEND( l, 64UL,               (pack_depth+extra_depth)*pack->bundle_meta_sz      );
     917             : 
     918         558 :   FD_MGAUGE_SET( PACK, PENDING_TRANSACTIONS_HEAP_SIZE, pack->pack_depth );
     919         558 :   return pack;
     920         558 : }
     921             : 
     922             : 
     923             : /* Returns 0 on failure, 1 on success for a vote, 2 on success for a
     924             :    non-vote. */
     925             : static int
     926             : fd_pack_estimate_rewards_and_compute( fd_txn_e_t        * txne,
     927    13586322 :                                       fd_pack_ord_txn_t * out ) {
     928    13586322 :   fd_txn_t * txn = TXN(txne->txnp);
     929    13586322 :   ulong sig_rewards = FD_PACK_FEE_PER_SIGNATURE * txn->signature_cnt; /* Easily in [5000, 635000] */
     930             : 
     931    13586322 :   ulong requested_execution_cus;
     932    13586322 :   ulong priority_rewards;
     933    13586322 :   ulong precompile_sigs;
     934    13586322 :   ulong requested_loaded_accounts_data_cost;
     935    13586322 :   ulong cost_estimate = fd_pack_compute_cost( txn, txne->txnp->payload, &txne->txnp->flags, &requested_execution_cus, &priority_rewards, &precompile_sigs, &requested_loaded_accounts_data_cost );
     936             : 
     937    13586322 :   if( FD_UNLIKELY( !cost_estimate ) ) return 0;
     938             : 
     939             :   /* precompile_sigs <= 16320, so after the addition,
     940             :      sig_rewards < 83,000,000 */
     941    13586319 :   sig_rewards += FD_PACK_FEE_PER_SIGNATURE * precompile_sigs;
     942    13586319 :   sig_rewards = sig_rewards * FD_PACK_TXN_FEE_BURN_PCT / 100UL;
     943             : 
     944             :   /* No fancy CU estimation in this version of pack
     945             :   for( ulong i=0UL; i<(ulong)txn->instr_cnt; i++ ) {
     946             :     uchar prog_id_idx = txn->instr[ i ].program_id;
     947             :     fd_acct_addr_t const * acct_addr = fd_txn_get_acct_addrs( txn, txnp->payload ) + (ulong)prog_id_idx;
     948             :   }
     949             :   */
     950    13586319 :   out->rewards                              = (priority_rewards < (UINT_MAX - sig_rewards)) ? (uint)(sig_rewards + priority_rewards) : UINT_MAX;
     951    13586319 :   out->compute_est                          = (uint)cost_estimate;
     952    13586319 :   out->txn->pack_cu.requested_exec_plus_acct_data_cus = (uint)(requested_execution_cus + requested_loaded_accounts_data_cost);
     953    13586319 :   out->txn->pack_cu.non_execution_cus       = (uint)(cost_estimate - requested_execution_cus - requested_loaded_accounts_data_cost);
     954             : 
     955    13586319 :   return fd_int_if( txne->txnp->flags & FD_TXN_P_FLAGS_IS_SIMPLE_VOTE, 1, 2 );
     956    13586322 : }
     957             : 
     958             : /* Returns 0 on failure, 1 if not a durable nonce transaction, and 2 if
     959             :    it is.  FIXME: These return codes are set to harmonize with
     960             :    estimate_rewards_and_compute but -1/0/1 makes a lot more sense to me.
     961             :    */
     962             : static int
     963    13586319 : fd_pack_validate_durable_nonce( fd_txn_e_t * txne ) {
     964    13586319 :   fd_txn_t const * txn = TXN(txne->txnp);
     965             : 
     966             :   /* First instruction invokes system program with 4 bytes of
     967             :      instruction data with the little-endian value 4.  It also has 3
     968             :      accounts: the nonce account, recent blockhashes sysvar, and the
     969             :      nonce authority.  It seems like technically the nonce authority may
     970             :      not need to be passed in, but we disallow that.  We also allow
     971             :      trailing data and trailing accounts.  We want to organize the
     972             :      checks somewhat to minimize cache misses. */
     973    13586319 :   if( FD_UNLIKELY( txn->instr_cnt==0            ) ) return 1;
     974     1421199 :   if( FD_UNLIKELY( txn->instr[ 0 ].data_sz<4UL  ) ) return 1;
     975     1421199 :   if( FD_UNLIKELY( txn->instr[ 0 ].acct_cnt<3UL ) ) return 1; /* It seems like technically 2 is allowed, but never used */
     976       39300 :   if( FD_LIKELY  ( fd_uint_load_4( txne->txnp->payload + txn->instr[ 0 ].data_off )!=4U ) ) return 1;
     977             :   /* The program has to be a static account */
     978        1155 :   fd_acct_addr_t const * accts = fd_txn_get_acct_addrs( txn, txne->txnp->payload );
     979        1155 :   if( FD_UNLIKELY( !fd_memeq( accts[ txn->instr[ 0 ].program_id ].b, null_addr.b, 32UL       ) ) ) return 1;
     980        1155 :   if( FD_UNLIKELY( !fd_txn_is_signer( txn, txne->txnp->payload[ txn->instr[ 0 ].acct_off+2 ] ) ) ) return 0;
     981             :   /* We could check recent blockhash, but it's not necessary */
     982        1152 :   return 2;
     983        1155 : }
     984             : 
     985             : /* Can the fee payer afford to pay a transaction with the specified
     986             :    price?  Returns 1 if so, 0 otherwise.  This is just a stub that
     987             :    always returns 1 for now, and the real check is deferred to the bank
     988             :    tile.  In general, this function can't be totally accurate, because
     989             :    the transactions immediately prior to this one can affect the balance
     990             :    of this fee payer, but a simple check here may be helpful for
     991             :    reducing spam. */
     992             : static int
     993             : fd_pack_can_fee_payer_afford( fd_acct_addr_t const * acct_addr,
     994    13586313 :                               ulong                  price /* in lamports */) {
     995    13586313 :   (void)acct_addr;
     996    13586313 :   (void)price;
     997    13586313 :   return 1;
     998    13586313 : }
     999             : 
    1000             : 
    1001             : 
    1002             : 
    1003             : 
    1004    13707096 : fd_txn_e_t * fd_pack_insert_txn_init(   fd_pack_t * pack                   ) { return trp_pool_ele_acquire( pack->pool )->txn_e; }
    1005      122406 : 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 ); }
    1006             : 
    1007          24 : #define REJECT( reason ) do {                                       \
    1008          24 :                            trp_pool_ele_release( pack->pool, ord ); \
    1009          24 :                            return FD_PACK_INSERT_REJECT_ ## reason; \
    1010          24 :                          } while( 0 )
    1011             : 
    1012             : /* These require txn, accts, and alt_adj to be defined as per usual */
    1013      328987 : #define ACCT_IDX_TO_PTR( idx ) (__extension__( {                                               \
    1014      328987 :       ulong __idx = (idx);                                                                     \
    1015      328987 :       fd_ptr_if( __idx<fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM ), accts, alt_adj )+__idx; \
    1016      328987 :       }))
    1017    71690770 : #define ACCT_ITER_TO_PTR( iter ) (__extension__( {                                             \
    1018    71690770 :       ulong __idx = fd_txn_acct_iter_idx( iter );                                              \
    1019    71690770 :       fd_ptr_if( __idx<fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM ), accts, alt_adj )+__idx; \
    1020    71690770 :       }))
    1021             : 
    1022             : 
    1023             : /* Tries to find the worst transaction in any treap in pack.  If that
    1024             :    transaction's score is worse than or equal to threshold_score, it
    1025             :    initiates a delete and returns the number of deleted transactions
    1026             :    (potentially more than 1 for a bundle).  If it's higher than
    1027             :    threshold_score, it returns 0.  To force this function to delete the
    1028             :    worst transaction if there are any eligible ones, pass FLT_MAX as
    1029             :    threshold_score. */
    1030             : static inline ulong
    1031             : delete_worst( fd_pack_t * pack,
    1032             :               float       threshold_score,
    1033      494601 :               int         is_vote ) {
    1034             :   /* If the tree is full, we want to see if this is better than the
    1035             :      worst element in the pool before inserting.  If the new transaction
    1036             :      is better than that one, we'll delete it and insert the new
    1037             :      transaction. Otherwise, we'll throw away this transaction.
    1038             : 
    1039             :      We want to bias the definition of "worst" here to provide better
    1040             :      quality of service.  For example, if the pool is filled with
    1041             :      transactions that all write to the same account or are all votes,
    1042             :      we want to bias towards treating one of those transactions as the
    1043             :      worst, even if they pay slightly higher fees per computer unit,
    1044             :      since we know we won't actually be able to schedule them all.
    1045             : 
    1046             :      This is a tricky task, however.  All our notions of priority and
    1047             :      better/worse are based on static information about the transaction,
    1048             :      and there's not an easy way to take into account global
    1049             :      information, for example, how many other transactions contend with
    1050             :      this one.  One idea is to build a heap (not a treap, since we only
    1051             :      need pop-min, insert, and delete) with one element for each element
    1052             :      in the pool, with a "delete me" score that's related but not
    1053             :      identical to the normal score.  This would allow building in some
    1054             :      global information.  The downside is that the global information
    1055             :      that gets integrated is static.  E.g. if you bias a transaction's
    1056             :      "delete me" score to make it more likely to be deleted because
    1057             :      there are many conflicting transactions in the pool, the score
    1058             :      stays biased, even if the global conditions change (unless you come
    1059             :      up with some complicated re-scoring scheme).  This can work, since
    1060             :      when the pool is full, the global bias factors are unlikely to
    1061             :      change significantly at the relevant timescales.
    1062             : 
    1063             :      However, rather than this, we implement a simpler probabilistic
    1064             :      scheme.  We'll sample M transactions, find the worst transaction in
    1065             :      each of the M treaps, compute a "delete me" score for those <= M
    1066             :      transactions, and delete the worst.  If one penalty treap is
    1067             :      starting to get big, then it becomes very likely that the random
    1068             :      sample will find it and choose to delete a transaction from it.
    1069             : 
    1070             :      The exact formula for the "delete me" score should be the matter of
    1071             :      some more intense quantitative research.  For now, we'll just use
    1072             :      this:
    1073             : 
    1074             :      Treap with N transactions        Scale Factor
    1075             :      Pending                      1.0 unless inserting a vote and votes < 25%
    1076             :      Pending votes                1.0 until 75% of depth, then 0
    1077             :      Penalty treap                1.0 at <= 100 transactions, then sqrt(100/N)
    1078             :      Pending bundles              inf (since the rewards value is fudged)
    1079             : 
    1080             :      We'll also use M=8. */
    1081             : 
    1082      494601 :   float worst_score = FLT_MAX;
    1083      494601 :   fd_pack_ord_txn_t * worst = NULL;
    1084     4451409 :   for( ulong i=0UL; i<8UL; i++ ) {
    1085     3956808 :     uint  pool_max = (uint)trp_pool_max( pack->pool );
    1086     3956808 :     ulong sample_i = fd_rng_uint_roll( pack->rng, pool_max );
    1087             : 
    1088     3956808 :     fd_pack_ord_txn_t * sample = &pack->pool[ sample_i ];
    1089             :     /* Presumably if we're calling this, the pool is almost entirely
    1090             :        full, so the probability of choosing a free one is small.  If
    1091             :        it does happen, find the first one that isn't free. */
    1092     3959093 :     while( FD_UNLIKELY( sample->root==FD_ORD_TXN_ROOT_FREE ) ) sample = &pack->pool[ (++sample_i)%pool_max ];
    1093             : 
    1094     3956808 :     int       root_idx   = sample->root;
    1095     3956808 :     float     multiplier = 0.0f; /* The smaller this is, the more biased we'll be to deleting it */
    1096     3956808 :     treap_t * treap;
    1097     3956808 :     switch( root_idx & FD_ORD_TXN_ROOT_TAG_MASK ) {
    1098           0 :       default:
    1099           0 :       case FD_ORD_TXN_ROOT_FREE: {
    1100           0 :         FD_LOG_CRIT(( "Double free detected" ));
    1101           0 :         return ULONG_MAX; /* Can't be hit */
    1102           0 :       }
    1103     3935441 :       case FD_ORD_TXN_ROOT_PENDING: {
    1104     3935441 :         treap = pack->pending;
    1105     3935441 :         ulong vote_cnt = treap_ele_cnt( pack->pending_votes );
    1106     3935441 :         if( FD_LIKELY( !is_vote || (vote_cnt>=pack->pack_depth/4UL ) ) ) multiplier = 1.0f;
    1107     3935441 :         break;
    1108           0 :       }
    1109           0 :       case FD_ORD_TXN_ROOT_PENDING_VOTE: {
    1110           0 :         treap = pack->pending_votes;
    1111           0 :         ulong vote_cnt = treap_ele_cnt( pack->pending_votes );
    1112           0 :         if( FD_LIKELY( is_vote || (vote_cnt<=3UL*pack->pack_depth/4UL ) ) ) multiplier = 1.0f;
    1113           0 :         break;
    1114           0 :       }
    1115           0 :       case FD_ORD_TXN_ROOT_PENDING_BUNDLE: {
    1116             :         /* We don't have a way to tell how much these actually pay in
    1117             :            rewards, so we just assume they are very high. */
    1118           0 :         treap = pack->pending_bundles;
    1119             :         /* We cap rewards at UINT_MAX lamports for estimation, and min
    1120             :            CUs is about 1000, which means rewards/compute < 5e6.
    1121             :            FLT_MAX is around 3e38. That means, 1e20*rewards/compute is
    1122             :            much less than FLT_MAX, so we won't have any issues with
    1123             :            overflow.  On the other hand, if rewards==1 lamport and
    1124             :            compute is 2 million CUs, 1e20*1/2e6 is still higher than any
    1125             :            normal transaction. */
    1126           0 :         multiplier = 1e20f;
    1127           0 :         break;
    1128           0 :       }
    1129       21367 :       case FD_ORD_TXN_ROOT_PENALTY( 0 ): {
    1130       21367 :         fd_txn_t * txn = TXN( sample->txn );
    1131       21367 :         fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, sample->txn->payload );
    1132       21367 :         fd_acct_addr_t const * alt_adj = sample->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1133       21367 :         fd_acct_addr_t penalty_acct = *ACCT_IDX_TO_PTR( FD_ORD_TXN_ROOT_PENALTY_ACCT_IDX( root_idx ) );
    1134       21367 :         fd_pack_penalty_treap_t * q = penalty_map_query( pack->penalty_treaps, penalty_acct, NULL );
    1135       21367 :         FD_TEST( q );
    1136       21367 :         ulong cnt = treap_ele_cnt( q->penalty_treap );
    1137       21367 :         treap = q->penalty_treap;
    1138             : 
    1139       21367 :         multiplier = sqrtf( 100.0f / (float)fd_ulong_max( 100UL, cnt ) );
    1140       21367 :         break;
    1141       21367 :       }
    1142     3956808 :     }
    1143             :     /* Get the worst from the sampled treap */
    1144     3956808 :     treap_fwd_iter_t _cur=treap_fwd_iter_init( treap, pack->pool );
    1145     3956808 :     FD_TEST( !treap_fwd_iter_done( _cur ) ); /* It can't be empty because we just sampled an element from it. */
    1146     3956808 :     sample = treap_fwd_iter_ele( _cur, pack->pool );
    1147             : 
    1148     3956808 :     float score = multiplier * (float)sample->rewards / (float)sample->compute_est;
    1149     3956808 :     worst = fd_ptr_if( score<worst_score, sample, worst );
    1150     3956808 :     worst_score = fd_float_if( worst_score<score, worst_score, score );
    1151     3956808 :   }
    1152             : 
    1153      494601 :   if( FD_UNLIKELY( !worst                      ) ) return 0;
    1154      494601 :   if( FD_UNLIKELY( threshold_score<worst_score ) ) return 0;
    1155             : 
    1156      494601 :   return delete_transaction( pack, worst, 1, 1 );
    1157      494601 : }
    1158             : 
    1159             : static inline int
    1160             : validate_transaction( fd_pack_t               * pack,
    1161             :                       fd_pack_ord_txn_t const * ord,
    1162             :                       fd_txn_t          const * txn,
    1163             :                       fd_acct_addr_t    const * accts,
    1164             :                       fd_acct_addr_t    const * alt_adj,
    1165    13586313 :                       int                       check_bundle_blacklist ) {
    1166    13586313 :   int writes_to_sysvar = 0;
    1167    13586313 :   for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    1168    28357920 :       iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    1169    14771607 :     writes_to_sysvar |= fd_pack_unwritable_contains( ACCT_ITER_TO_PTR( iter ) );
    1170    14771607 :   }
    1171             : 
    1172    13586313 :   int bundle_blacklist = 0;
    1173    13586313 :   if( FD_UNLIKELY( check_bundle_blacklist ) ) {
    1174       70974 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_ALL );
    1175      463503 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    1176      392529 :       bundle_blacklist |= (3==fd_pack_tip_prog_check_blacklist( ACCT_ITER_TO_PTR( iter ) ));
    1177      392529 :     }
    1178       70974 :   }
    1179             : 
    1180    13586313 :   fd_acct_addr_t const * alt     = ord->txn_e->alt_accts;
    1181    13586313 :   fd_chkdup_t * chkdup = pack->chkdup;
    1182    13586313 :   ulong imm_cnt = fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1183    13586313 :   ulong alt_cnt = fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_ALT );
    1184             : 
    1185             :   /* Throw out transactions ... */
    1186             :   /*           ... that are unfunded */
    1187    13586313 :   if( FD_UNLIKELY( !fd_pack_can_fee_payer_afford( accts, ord->rewards    ) ) ) return FD_PACK_INSERT_REJECT_UNAFFORDABLE;
    1188             :   /*           ... that are so big they'll never run */
    1189    13586313 :   if( FD_UNLIKELY( ord->compute_est >= pack->lim->max_cost_per_block       ) ) return FD_PACK_INSERT_REJECT_TOO_LARGE;
    1190             :   /*           ... that load too many accounts (ignoring 9LZdXeKGeBV6hRLdxS1rHbHoEUsKqesCC2ZAPTPKJAbK) */
    1191    13586313 :   if( FD_UNLIKELY( fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_ALL )>64UL     ) ) return FD_PACK_INSERT_REJECT_ACCOUNT_CNT;
    1192             :   /*           ... that duplicate an account address */
    1193    13586310 :   if( FD_UNLIKELY( fd_chkdup_check( chkdup, accts, imm_cnt, alt, alt_cnt ) ) ) return FD_PACK_INSERT_REJECT_DUPLICATE_ACCT;
    1194             :   /*           ... that try to write to a sysvar */
    1195    13586307 :   if( FD_UNLIKELY( writes_to_sysvar                                        ) ) return FD_PACK_INSERT_REJECT_WRITES_SYSVAR;
    1196             :   /*           ... that use an account that violates bundle rules */
    1197    13586214 :   if( FD_UNLIKELY( bundle_blacklist & 1                                    ) ) return FD_PACK_INSERT_REJECT_BUNDLE_BLACKLIST;
    1198             : 
    1199    13586214 :   return 0;
    1200    13586214 : }
    1201             : 
    1202             : 
    1203             : 
    1204             : /* returns cumulative penalty "points", i.e. the sum of the populated
    1205             :    section of penalties (which also tells the caller how much of the
    1206             :    array is populated. */
    1207             : static inline ulong
    1208             : populate_bitsets( fd_pack_t         * pack,
    1209             :                   fd_pack_ord_txn_t * ord,
    1210             :                   ushort              penalties  [ static FD_TXN_ACCT_ADDR_MAX ],
    1211    13585164 :                   uchar               penalty_idx[ static FD_TXN_ACCT_ADDR_MAX ] ) {
    1212    13585164 :   FD_PACK_BITSET_CLEAR( ord->rw_bitset );
    1213    13585164 :   FD_PACK_BITSET_CLEAR( ord->w_bitset  );
    1214             : 
    1215    13585164 :   fd_txn_t * txn   = TXN(ord->txn);
    1216    13585164 :   uchar * payload  = ord->txn->payload;
    1217             : 
    1218    13585164 :   fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, payload );
    1219             :   /* alt_adj is the pointer to the ALT expansion, adjusted so that if
    1220             :      account address n is the first that comes from the ALT, it can be
    1221             :      accessed with adj_lut[n]. */
    1222    13585164 :   fd_acct_addr_t const * alt_adj = ord->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1223             : 
    1224    13585164 :   ulong  cumulative_penalty = 0UL;
    1225    13585164 :   ulong  penalty_i          = 0UL;
    1226             : 
    1227    13585164 :   for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    1228    28352121 :       iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    1229    14766957 :     fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    1230    14766957 :     fd_pack_bitset_acct_mapping_t * q = bitset_map_query( pack->acct_to_bitset, acct, NULL );
    1231    14766957 :     if( FD_UNLIKELY( q==NULL ) ) {
    1232    13277342 :       q = bitset_map_insert( pack->acct_to_bitset, acct );
    1233    13277342 :       q->ref_cnt                  = 0UL;
    1234    13277342 :       q->first_instance           = ord;
    1235    13277342 :       q->first_instance_was_write = 1;
    1236    13277342 :       q->bit                      = FD_PACK_BITSET_FIRST_INSTANCE;
    1237    13277342 :     } else if( FD_UNLIKELY( q->bit == FD_PACK_BITSET_FIRST_INSTANCE ) ) {
    1238        7399 :       q->bit = pack->bitset_avail[ pack->bitset_avail_cnt ];
    1239        7399 :       pack->bitset_avail_cnt = fd_ulong_if( !!pack->bitset_avail_cnt, pack->bitset_avail_cnt-1UL, 0UL );
    1240             : 
    1241        7399 :       FD_PACK_BITSET_SETN( q->first_instance->rw_bitset, q->bit );
    1242        7399 :       if( q->first_instance_was_write ) FD_PACK_BITSET_SETN( q->first_instance->w_bitset, q->bit );
    1243        7399 :     }
    1244    14766957 :     ulong penalty = fd_ulong_max( q->ref_cnt, PENALTY_TREAP_THRESHOLD )-PENALTY_TREAP_THRESHOLD;
    1245    14766957 :     if( FD_UNLIKELY( penalty ) ) {
    1246     1212867 :       penalties  [ penalty_i ] = (ushort)penalty;
    1247     1212867 :       penalty_idx[ penalty_i ] = (uchar )fd_txn_acct_iter_idx( iter );
    1248     1212867 :       penalty_i++;
    1249     1212867 :       cumulative_penalty += penalty;
    1250     1212867 :     }
    1251             : 
    1252    14766957 :     q->ref_cnt++;
    1253    14766957 :     FD_PACK_BITSET_SETN( ord->rw_bitset, q->bit );
    1254    14766957 :     FD_PACK_BITSET_SETN( ord->w_bitset , q->bit );
    1255    14766957 :   }
    1256             : 
    1257    13585164 :   for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_READONLY );
    1258    18170178 :       iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    1259             : 
    1260     4585014 :     fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    1261     4585014 :     if( FD_UNLIKELY( fd_pack_unwritable_contains( &acct ) ) ) continue;
    1262             : 
    1263     3088449 :     fd_pack_bitset_acct_mapping_t * q = bitset_map_query( pack->acct_to_bitset, acct, NULL );
    1264     3088449 :     if( FD_UNLIKELY( q==NULL ) ) {
    1265       30096 :       q = bitset_map_insert( pack->acct_to_bitset, acct );
    1266       30096 :       q->ref_cnt                  = 0UL;
    1267       30096 :       q->first_instance           = ord;
    1268       30096 :       q->first_instance_was_write = 0;
    1269       30096 :       q->bit                      = FD_PACK_BITSET_FIRST_INSTANCE;
    1270     3058353 :     } else if( FD_UNLIKELY( q->bit == FD_PACK_BITSET_FIRST_INSTANCE ) ) {
    1271       11130 :       q->bit = pack->bitset_avail[ pack->bitset_avail_cnt ];
    1272       11130 :       pack->bitset_avail_cnt = fd_ulong_if( !!pack->bitset_avail_cnt, pack->bitset_avail_cnt-1UL, 0UL );
    1273             : 
    1274       11130 :       FD_PACK_BITSET_SETN( q->first_instance->rw_bitset, q->bit );
    1275       11130 :       if( q->first_instance_was_write ) FD_PACK_BITSET_SETN( q->first_instance->w_bitset, q->bit );
    1276       11130 :     }
    1277             : 
    1278     3088449 :     q->ref_cnt++;
    1279     3088449 :     FD_PACK_BITSET_SETN( ord->rw_bitset, q->bit );
    1280     3088449 :   }
    1281    13585164 :   return cumulative_penalty;
    1282    13585164 : }
    1283             : 
    1284             : int
    1285             : fd_pack_insert_txn_fini( fd_pack_t  * pack,
    1286             :                          fd_txn_e_t * txne,
    1287             :                          ulong        expires_at,
    1288    13584690 :                          ulong      * delete_cnt ) {
    1289             : 
    1290    13584690 :   fd_pack_ord_txn_t * ord = (fd_pack_ord_txn_t *)txne;
    1291             : 
    1292    13584690 :   fd_txn_t * txn   = TXN(txne->txnp);
    1293    13584690 :   uchar * payload  = txne->txnp->payload;
    1294             : 
    1295    13584690 :   fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, payload );
    1296             :   /* alt_adj is the pointer to the ALT expansion, adjusted so that if
    1297             :      account address n is the first that comes from the ALT, it can be
    1298             :      accessed with adj_lut[n]. */
    1299    13584690 :   fd_acct_addr_t const * alt_adj = ord->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1300             : 
    1301    13584690 :   ord->expires_at = expires_at;
    1302             : 
    1303    13584690 :   int est_result = fd_pack_estimate_rewards_and_compute( txne, ord );
    1304    13584690 :   if( FD_UNLIKELY( !est_result ) ) REJECT( ESTIMATION_FAIL );
    1305    13584687 :   int is_vote          = est_result==1;
    1306             : 
    1307    13584687 :   int nonce_result = fd_pack_validate_durable_nonce( txne );
    1308    13584687 :   if( FD_UNLIKELY( !nonce_result ) ) REJECT( INVALID_NONCE );
    1309    13584684 :   int is_durable_nonce = nonce_result==2;
    1310    13584684 :   ord->txn->flags &= ~FD_TXN_P_FLAGS_DURABLE_NONCE;
    1311    13584684 :   ord->txn->flags |= fd_uint_if( is_durable_nonce, FD_TXN_P_FLAGS_DURABLE_NONCE, 0U );
    1312             : 
    1313    13584684 :   int validation_result = validate_transaction( pack, ord, txn, accts, alt_adj, !!pack->bundle_meta_sz );
    1314    13584684 :   if( FD_UNLIKELY( validation_result ) ) {
    1315          99 :     trp_pool_ele_release( pack->pool, ord );
    1316          99 :     return validation_result;
    1317          99 :   }
    1318             : 
    1319             :   /* Reject any transactions that have already expired */
    1320    13584585 :   if( FD_UNLIKELY( expires_at<pack->expire_before                          ) ) REJECT( EXPIRED          );
    1321             : 
    1322    13584573 :   int replaces = 0;
    1323    13584573 :   *delete_cnt = 0UL;
    1324             :   /* If it's a durable nonce and we already have one, delete one or the
    1325             :      other. */
    1326    13584573 :   if( FD_UNLIKELY( is_durable_nonce ) ) {
    1327         120 :     fd_pack_ord_txn_t * same_nonce = noncemap_ele_query( pack->noncemap, txne, NULL, pack->pool );
    1328         120 :     if( FD_LIKELY( same_nonce ) ) { /* Seems like most nonce transactions are effectively duplicates */
    1329           9 :       if( FD_LIKELY( same_nonce->root == FD_ORD_TXN_ROOT_PENDING_BUNDLE || COMPARE_WORSE( ord, same_nonce ) ) ) REJECT( NONCE_PRIORITY );
    1330           3 :       ulong _delete_cnt = delete_transaction( pack, same_nonce, 0, 0 ); /* Not a bundle, so delete_full_bundle is 0 */
    1331           3 :       *delete_cnt += _delete_cnt;
    1332           3 :       replaces = 1;
    1333           3 :     }
    1334         120 :   }
    1335             : 
    1336    13584567 :   if( FD_UNLIKELY( pack->pending_txn_cnt == pack->pack_depth ) ) {
    1337      494592 :     float threshold_score = (float)ord->rewards/(float)ord->compute_est;
    1338      494592 :     ulong _delete_cnt = delete_worst( pack, threshold_score, is_vote );
    1339      494592 :     *delete_cnt += _delete_cnt;
    1340      494592 :     if( FD_UNLIKELY( !_delete_cnt ) ) REJECT( PRIORITY );
    1341      494592 :     replaces = 1;
    1342      494592 :   }
    1343             : 
    1344    13584567 :   ord->txn->flags &= ~(FD_TXN_P_FLAGS_BUNDLE | FD_TXN_P_FLAGS_INITIALIZER_BUNDLE);
    1345    13584567 :   ord->skip = FD_PACK_SKIP_CNT;
    1346             : 
    1347             :   /* At this point, we know we have space to insert the transaction and
    1348             :      we've committed to insert it. */
    1349             : 
    1350             :   /* Since the pool uses ushorts, the size of the pool is < USHORT_MAX.
    1351             :      Each transaction can reference an account at most once, which means
    1352             :      that the total number of references for an account is < USHORT_MAX.
    1353             :      If these were ulongs, the array would be 512B, which is kind of a
    1354             :      lot to zero out.*/
    1355    13584567 :   ushort penalties[ FD_TXN_ACCT_ADDR_MAX ] = {0};
    1356    13584567 :   uchar  penalty_idx[ FD_TXN_ACCT_ADDR_MAX ];
    1357    13584567 :   ulong cumulative_penalty = populate_bitsets( pack, ord, penalties, penalty_idx );
    1358             : 
    1359    13584567 :   treap_t * insert_into = pack->pending;
    1360             : 
    1361    13584567 :   if( FD_UNLIKELY( cumulative_penalty && !is_vote ) ) { /* Optimize for high parallelism case */
    1362             :     /* Compute a weighted random choice */
    1363      304959 :     ulong roll = (ulong)fd_rng_uint_roll( pack->rng, (uint)cumulative_penalty ); /* cumulative_penalty < USHORT_MAX*64 < UINT_MAX */
    1364      304959 :     ulong i = 0UL;
    1365             :     /* Find the right one.  This can be done in O(log N), but I imagine
    1366             :        N is normally so small that doesn't matter. */
    1367      758568 :     while( roll>=penalties[i] ) roll -= (ulong)penalties[i++];
    1368             : 
    1369      304959 :     fd_acct_addr_t penalty_acct = *ACCT_IDX_TO_PTR( penalty_idx[i] );
    1370      304959 :     fd_pack_penalty_treap_t * q = penalty_map_query( pack->penalty_treaps, penalty_acct, NULL );
    1371      304959 :     if( FD_UNLIKELY( q==NULL ) ) {
    1372        2901 :       q = penalty_map_insert( pack->penalty_treaps, penalty_acct );
    1373        2901 :       treap_new( q->penalty_treap, pack->pack_depth );
    1374        2901 :     }
    1375      304959 :     insert_into = q->penalty_treap;
    1376      304959 :     ord->root = FD_ORD_TXN_ROOT_PENALTY( penalty_idx[i] );
    1377    13279608 :   } else {
    1378    13279608 :     ord->root = fd_int_if( is_vote, FD_ORD_TXN_ROOT_PENDING_VOTE, FD_ORD_TXN_ROOT_PENDING );
    1379             : 
    1380    13279608 :     fd_pack_smallest_t * smallest = fd_ptr_if( is_vote, &pack->pending_votes_smallest[0], pack->pending_smallest );
    1381    13279608 :     smallest->cus   = fd_ulong_min( smallest->cus,   ord->compute_est       );
    1382    13279608 :     smallest->bytes = fd_ulong_min( smallest->bytes, txne->txnp->payload_sz );
    1383    13279608 :   }
    1384             : 
    1385    13584567 :   pack->pending_txn_cnt++;
    1386             : 
    1387    13584567 :   sig2txn_ele_insert( pack->signature_map, ord, pack->pool );
    1388             : 
    1389    13584567 :   if( FD_UNLIKELY( is_durable_nonce ) ) noncemap_ele_insert( pack->noncemap, ord, pack->pool );
    1390             : 
    1391    13584567 :   fd_pack_expq_t temp[ 1 ] = {{ .expires_at = expires_at, .txn = ord }};
    1392    13584567 :   expq_insert( pack->expiration_q, temp );
    1393             : 
    1394    13584567 :   if( FD_LIKELY( is_vote ) ) insert_into = pack->pending_votes;
    1395             : 
    1396    13584567 :   treap_ele_insert( insert_into, ord, pack->pool );
    1397    13584567 :   return (is_vote) | (replaces<<1) | (is_durable_nonce<<2);
    1398    13584567 : }
    1399             : #undef REJECT
    1400             : 
    1401             : fd_txn_e_t * const *
    1402             : fd_pack_insert_bundle_init( fd_pack_t          * pack,
    1403             :                             fd_txn_e_t *       * bundle,
    1404         408 :                             ulong                txn_cnt ) {
    1405         408 :   FD_TEST( txn_cnt<=FD_PACK_MAX_TXN_PER_BUNDLE  );
    1406         408 :   FD_TEST( trp_pool_free( pack->pool )>=txn_cnt );
    1407        2076 :   for( ulong i=0UL; i<txn_cnt; i++ ) bundle[ i ] = trp_pool_ele_acquire( pack->pool )->txn_e;
    1408         408 :   return bundle;
    1409         408 : }
    1410             : 
    1411             : void
    1412             : fd_pack_insert_bundle_cancel( fd_pack_t          * pack,
    1413             :                               fd_txn_e_t * const * bundle,
    1414         258 :                               ulong                txn_cnt ) {
    1415             :   /* There's no real reason these have to be released in reverse, but it
    1416             :      seems fitting to release them in the opposite order they were
    1417             :      acquired. */
    1418        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 ] );
    1419         258 : }
    1420             : 
    1421             : /* Explained below */
    1422             : #define BUNDLE_L_PRIME 37896771UL
    1423             : #define BUNDLE_N       312671UL
    1424         207 : #define RC_TO_REL_BUNDLE_IDX( r, c ) (BUNDLE_N - ((ulong)(r) * 1UL<<32)/((ulong)(c) * BUNDLE_L_PRIME))
    1425             : 
    1426             : int
    1427             : fd_pack_insert_bundle_fini( fd_pack_t          * pack,
    1428             :                             fd_txn_e_t * const * bundle,
    1429             :                             ulong                txn_cnt,
    1430             :                             ulong                expires_at,
    1431             :                             int                  initializer_bundle,
    1432             :                             void         const * bundle_meta,
    1433         396 :                             ulong              * delete_cnt ) {
    1434             : 
    1435         396 :   int err = 0;
    1436         396 :   *delete_cnt = 0UL;
    1437             : 
    1438         396 :   ulong pending_b_txn_cnt = treap_ele_cnt( pack->pending_bundles );
    1439             :     /* We want to prevent bundles from consuming the whole treap, but in
    1440             :        general, we assume bundles are lucrative.  We'll set the policy
    1441             :        on capping bundles at half of the pack depth.  We assume that the
    1442             :        bundles are coming in a pre-prioritized order, so it doesn't make
    1443             :        sense to drop an earlier bundle for this one.  That means that
    1444             :        really, the best thing to do is drop this one. */
    1445         396 :   if( FD_UNLIKELY( (!initializer_bundle)&(pending_b_txn_cnt+txn_cnt>pack->pack_depth/2UL) ) ) err = FD_PACK_INSERT_REJECT_PRIORITY;
    1446             : 
    1447         396 :   if( FD_UNLIKELY( expires_at<pack->expire_before                                         ) ) err = FD_PACK_INSERT_REJECT_EXPIRED;
    1448             : 
    1449             : 
    1450         396 :   int   replaces      = 0;
    1451         396 :   ulong nonce_txn_cnt = 0UL;
    1452             : 
    1453             :   /* Collect nonce hashes to detect duplicate nonces.
    1454             :      Use a constant-time duplicate-detection algorithm -- Vacant entries
    1455             :      have the MSB set, occupied entries are the noncemap hash, with the
    1456             :      MSB set to 0. */
    1457         396 :   ulong nonce_hash63[ FD_PACK_MAX_TXN_PER_BUNDLE ];
    1458        2376 :   for( ulong i=0UL; i<FD_PACK_MAX_TXN_PER_BUNDLE; i++ ) {
    1459        1980 :     nonce_hash63[ i ] = ULONG_MAX-i;
    1460        1980 :   }
    1461             : 
    1462        2025 :   for( ulong i=0UL; (i<txn_cnt) && !err; i++ ) {
    1463        1632 :     fd_pack_ord_txn_t * ord = (fd_pack_ord_txn_t *)bundle[ i ];
    1464             : 
    1465        1632 :     fd_txn_t const * txn     = TXN(bundle[ i ]->txnp);
    1466        1632 :     uchar    const * payload = bundle[ i ]->txnp->payload;
    1467             : 
    1468        1632 :     fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, payload );
    1469        1632 :     fd_acct_addr_t const * alt_adj = ord->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1470             : 
    1471        1632 :     int est_result = fd_pack_estimate_rewards_and_compute( bundle[ i ], ord );
    1472        1632 :     if( FD_UNLIKELY( !est_result   ) ) { err = FD_PACK_INSERT_REJECT_ESTIMATION_FAIL; break; }
    1473        1632 :     int nonce_result = fd_pack_validate_durable_nonce( ord->txn_e );
    1474        1632 :     if( FD_UNLIKELY( !nonce_result ) ) { err = FD_PACK_INSERT_REJECT_INVALID_NONCE;   break; }
    1475        1632 :     int is_durable_nonce = nonce_result==2;
    1476        1632 :     nonce_txn_cnt += !!is_durable_nonce;
    1477             : 
    1478        1632 :     bundle[ i ]->txnp->flags |= FD_TXN_P_FLAGS_BUNDLE;
    1479        1632 :     bundle[ i ]->txnp->flags &= ~(FD_TXN_P_FLAGS_INITIALIZER_BUNDLE | FD_TXN_P_FLAGS_DURABLE_NONCE);
    1480        1632 :     bundle[ i ]->txnp->flags |= fd_uint_if( initializer_bundle, FD_TXN_P_FLAGS_INITIALIZER_BUNDLE, 0U );
    1481        1632 :     bundle[ i ]->txnp->flags |= fd_uint_if( is_durable_nonce,   FD_TXN_P_FLAGS_DURABLE_NONCE,      0U );
    1482        1632 :     ord->expires_at = expires_at;
    1483             : 
    1484        1632 :     if( FD_UNLIKELY( is_durable_nonce ) ) {
    1485        1032 :       nonce_hash63[ i ] = noncemap_key_hash( ord->txn_e, pack->noncemap->seed ) & 0x7FFFFFFFFFFFFFFFUL;
    1486        1032 :       fd_pack_ord_txn_t * same_nonce = noncemap_ele_query( pack->noncemap, ord->txn_e, NULL, pack->pool );
    1487        1032 :       if( FD_LIKELY( same_nonce ) ) {
    1488             :         /* bundles take priority over non-bundles, and earlier bundles
    1489             :            take priority over later bundles. */
    1490           6 :         if( FD_UNLIKELY( same_nonce->txn->flags & FD_TXN_P_FLAGS_BUNDLE ) ) {
    1491           3 :           err = FD_PACK_INSERT_REJECT_NONCE_PRIORITY;
    1492           3 :           break;
    1493           3 :         } else {
    1494           3 :           ulong _delete_cnt = delete_transaction( pack, same_nonce, 0, 0 );
    1495           3 :           *delete_cnt += _delete_cnt;
    1496           3 :           replaces = 1;
    1497           3 :         }
    1498           6 :       }
    1499        1032 :     }
    1500             : 
    1501        1629 :     int validation_result = validate_transaction( pack, ord, txn, accts, alt_adj, !initializer_bundle );
    1502        1629 :     if( FD_UNLIKELY( validation_result ) ) { err = validation_result; break; }
    1503        1629 :   }
    1504             : 
    1505         396 :   if( FD_UNLIKELY( err ) ) {
    1506           3 :     fd_pack_insert_bundle_cancel( pack, bundle, txn_cnt );
    1507           3 :     return err;
    1508           3 :   }
    1509             : 
    1510         393 :   if( FD_UNLIKELY( initializer_bundle && pending_b_txn_cnt>0UL ) ) {
    1511           9 :     treap_rev_iter_t _cur=treap_rev_iter_init( pack->pending_bundles, pack->pool );
    1512           9 :     FD_TEST( !treap_rev_iter_done( _cur ) );
    1513           9 :     fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pack->pool );
    1514           9 :     int is_ib = !!(cur->txn->flags & FD_TXN_P_FLAGS_INITIALIZER_BUNDLE);
    1515             : 
    1516             :     /* Delete the previous IB if there is one */
    1517           9 :     if( FD_UNLIKELY( is_ib && 0UL==RC_TO_REL_BUNDLE_IDX( cur->rewards, cur->compute_est ) ) ) {
    1518           0 :       ulong _delete_cnt = delete_transaction( pack, cur, 1, 0 );
    1519           0 :       *delete_cnt += _delete_cnt;
    1520           0 :     }
    1521           9 :   }
    1522             : 
    1523         402 :   while( FD_UNLIKELY( pack->pending_txn_cnt+txn_cnt > pack->pack_depth ) ) {
    1524           9 :     ulong _delete_cnt = delete_worst( pack, FLT_MAX, 0 );
    1525           9 :     *delete_cnt += _delete_cnt;
    1526           9 :     if( FD_UNLIKELY( !_delete_cnt ) ) {
    1527           0 :       fd_pack_insert_bundle_cancel( pack, bundle, txn_cnt );
    1528           0 :       return FD_PACK_INSERT_REJECT_PRIORITY;
    1529           0 :     }
    1530           9 :     replaces = 1;
    1531           9 :   }
    1532             : 
    1533         393 :   if( FD_UNLIKELY( !pending_b_txn_cnt ) ) {
    1534         384 :     pack->relative_bundle_idx = 1UL;
    1535         384 :   }
    1536             : 
    1537         393 :   if( FD_LIKELY( bundle_meta ) ) {
    1538           9 :     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 );
    1539           9 :   }
    1540             : 
    1541         393 :   if( FD_UNLIKELY( nonce_txn_cnt>1UL ) ) {
    1542             :     /* Do a ILP-friendly duplicate detect, naive O(n^2) algo.  With max
    1543             :        5 txns per bundle, this requires 10 comparisons.  ~ 25 cycle.  */
    1544         375 :     uint conflict_detected = 0u;
    1545        1875 :     for( ulong i=0UL; i<FD_PACK_MAX_TXN_PER_BUNDLE-1; i++ ) {
    1546        5250 :       for( ulong j=i+1; j<FD_PACK_MAX_TXN_PER_BUNDLE; j++ ) {
    1547        3750 :         ulong const ele_i = nonce_hash63[ i ];
    1548        3750 :         ulong const ele_j = nonce_hash63[ j ];
    1549        3750 :         conflict_detected |= (ele_i==ele_j);
    1550        3750 :       }
    1551        1500 :     }
    1552         375 :     if( FD_UNLIKELY( conflict_detected ) ) {
    1553         243 :       fd_pack_insert_bundle_cancel( pack, bundle, txn_cnt );
    1554         243 :       return FD_PACK_INSERT_REJECT_NONCE_CONFLICT;
    1555         243 :     }
    1556         375 :   }
    1557             : 
    1558             :   /* We put bundles in a treap just like all the other transactions, but
    1559             :      we actually want to sort them in a very specific order; the order
    1560             :      within the bundle is determined at bundle creation time, and the
    1561             :      order among the bundles is FIFO.  However, it's going to be a pain
    1562             :      to use a different sorting function for this treap, since it's
    1563             :      fixed as part of the treap creation for performance.  Don't fear
    1564             :      though; we can pull a cool math trick out of the bag to shoehorn
    1565             :      the order we'd like into the sort function we need, and to get even
    1566             :      more.
    1567             : 
    1568             :      Recall that the sort function is r_i/c_i, smallest to largest,
    1569             :      where r_i is the rewards and c_i is the cost units.  r_i and c_i
    1570             :      are both uints, and the comparison is done by cross-multiplication
    1571             :      as ulongs.  We actually use the c_i value for testing if
    1572             :      transactions fit, etc.  so let's assume that's fixed, and we know
    1573             :      it's in the range [1020, 1,556,782].
    1574             : 
    1575             :      This means, if c_0, c_1, ... c_4 are the CU costs of the
    1576             :      transactions in the first bundle, we require r_0/c_0 > r_1/c_1 >
    1577             :      ... > r_4/c_4.  Then, if c_5, ... c_9 are the CU costs of the
    1578             :      transactions in the second bundle, we also require that r_4/c_4 >
    1579             :      r_5/c_5.  For convenience, we'll impose a slightly stronger
    1580             :      constraint: we want the kth bundle to obey L*(N-k) <= r_i/c_i <
    1581             :      L*(N+1-k), for fixed constants L and N, real and integer,
    1582             :      respectively, that we'll determine. For example, this means r_4/c_4
    1583             :      >= L*N > r_5/c_5.  This enables us to group the transactions in the
    1584             :      same bundle more easily.
    1585             : 
    1586             :      For convenience in the math below, we'll set j=N-k and relabel the
    1587             :      transactions from the jth bundle c_0, ... c_4.
    1588             :      From above, we know that Lj <= r_4/c_4.  We'd like to make it as
    1589             :      close as possible given that r_4 is an integers.  Thus, put
    1590             :      r_4 = ceil( c_4 * Lj ).  r_4 is clearly an integer, and it satisfies
    1591             :      the required inequality because:
    1592             :             r_4/c_4 = ceil( c_4 * Lj)/c_4 >= c_4*Lj / c_4 >= Lj.
    1593             : 
    1594             :      Following in the same spirit, put r_3 = ceil( c_3 * (r_4+1)/c_4 ).
    1595             :      Again, r_3 is clearly an integer, and
    1596             :                 r_3/c_3  = ceil(c_3*(r_4+1)/c_4)/c_3
    1597             :                         >= (c_3*(r_4+1))/(c_3 * c_4)
    1598             :                         >= r_4/c_4 + 1/c_4
    1599             :                         >  r_4/c_4.
    1600             :      Following the pattern, we put
    1601             :                 r_2 = ceil( c_2 * (r_3+1)/c_3 )
    1602             :                 r_1 = ceil( c_1 * (r_2+1)/c_2 )
    1603             :                 r_0 = ceil( c_0 * (r_1+1)/c_1 )
    1604             :      which work for the same reason that as r_3.
    1605             : 
    1606             :      We now need for r_0 to satisfy the final inequality with L, and
    1607             :      we'll use this to guide our choice of L.  Theoretically, r_0 can be
    1608             :      expressed in terms of L, j, and c_0, ... c_4, but that's a truly
    1609             :      inscrutible expression.  Instead, we need some bounds so we can get
    1610             :      rid of all the ceil using the property that x <= ceil(x) < x+1.
    1611             :                      c_4 * Lj <= r_4 < c_4 * Lj + 1
    1612             :      The lower bound on r_3 is easy:
    1613             :          r_3 >= c_3 * (c_4 * Lj + 1)/c_4 = c_3 * Lj + c_3/c_4
    1614             :      For the upper bound,
    1615             :          r_3 < 1 + c_3*(r_4+1)/c_4 < 1 + c_3*(c_4*Lj+1 + 1)/c_4
    1616             :                                    = 1 + c_3 * Lj + 2*c_3/c_4
    1617             :      Continuing similarly gives
    1618             :        c_2*Lj +                     c_2/c_3 + c_2/c_4 <= r_2
    1619             :        c_1*Lj +           c_1/c_2 + c_1/c_c + c_1/c_4 <= r_1
    1620             :        c_0*Lj + c_0/c_1 + c_0/c_2 + c_0/c_3 + c_0/c_4 <= r_0
    1621             :      and
    1622             :        r_2 < 1 + c_2*Lj +                       2c_2/c_3 + 2c_2/c_4
    1623             :        r_1 < 1 + c_1*Lj +            2c_1/c_2 + 2c_1/c_3 + 2c_1/c_4
    1624             :        r_0 < 1 + c_0*Lj + 2c_0/c_1 + 2c_0/c_2 + 2c_0/c_3 + 2c_0/c_4.
    1625             : 
    1626             :      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
    1627             :      is then sufficient to ensure the whole sequence of 5 fits between Lj
    1628             :      and L(j+1).  Simplifying gives
    1629             :               L<= 1/c_0 + 2/c_1 + 2/c_2 + 2/c_3 + 2/c_4
    1630             :      but L must be a constant and not depend on individual values of c_i,
    1631             :      so, given that c_i >= 1020, we set L = 9/1020.
    1632             : 
    1633             :      Now all that remains is to determine N.  It's a bit unfortunate
    1634             :      that we require N, since it limits our capacity, but it's necessary
    1635             :      in any system that tries to compute priorities to enforce a FIFO
    1636             :      order.  If we've inserted more than N bundles without ever having
    1637             :      the bundle treap go empty, we'll briefly break the FIFO ordering as
    1638             :      we underflow.
    1639             : 
    1640             :      Thus, we'd like to make N as big as possible, avoiding overflow.
    1641             :      r_0, ..., r_4 are all uints, and taking the bounds from above,
    1642             :      given that for any i, i' c_i/c_{i'} < 1527, we have
    1643             :                r_i < 1 + 1556782 * Lj + 8*1527.
    1644             :      To avoid overflow, we assert the right-hand side is < 2^32, which
    1645             :      implies N <= 312671.
    1646             : 
    1647             :      We want to use a fixed point representation for L so that the
    1648             :      entire computation can be done with integer arithmetic.  We can do
    1649             :      the arithmetic as ulongs, which means defining L' >= L * 2^s, and
    1650             :      we compute ceil( c_4*Lj ) as floor( (c_4 * L' * j + 2^s - 1)/2^s ),
    1651             :      so c_4 * L' * j + 2^s should fit in a ulong.  With j<=N, this gives
    1652             :      s<=32, so we set s=32, which means L' = 37896771 >= 9/1020 * 2^32.
    1653             :      Note that 1 + 1556782 * L' * N + 8*1527 + 2^32 is approximately
    1654             :      2^63.999993.
    1655             : 
    1656             :      Note that this is all checked by a proof of the code translated
    1657             :      into Z3.  Unfortunately CBMC was too slow to prove this code
    1658             :      directly. */
    1659         357 : #define BUNDLE_L_PRIME 37896771UL
    1660         357 : #define BUNDLE_N       312671UL
    1661             : 
    1662         150 :   if( FD_UNLIKELY( pack->relative_bundle_idx>BUNDLE_N ) ) {
    1663           0 :     FD_LOG_WARNING(( "Too many bundles inserted without allowing pending bundles to go empty. "
    1664           0 :                      "Ordering of bundles may be incorrect." ));
    1665           0 :     pack->relative_bundle_idx = 1UL;
    1666           0 :   }
    1667         150 :   ulong bundle_idx = fd_ulong_if( initializer_bundle, 0UL, pack->relative_bundle_idx );
    1668         150 :   insert_bundle_impl( pack, bundle_idx, txn_cnt, (fd_pack_ord_txn_t * *)bundle, expires_at );
    1669             :   /* if IB this is max( 1, x ), which is x.  Otherwise, this is max(x,
    1670             :      x+1) which is x++ */
    1671         150 :   pack->relative_bundle_idx = fd_ulong_max( bundle_idx+1UL, pack->relative_bundle_idx );
    1672             : 
    1673         150 :   return (0) | (replaces<<1) | ((!!nonce_txn_cnt)<<2);
    1674         393 : }
    1675             : static inline void
    1676             : insert_bundle_impl( fd_pack_t           * pack,
    1677             :                     ulong                 bundle_idx,
    1678             :                     ulong                 txn_cnt,
    1679             :                     fd_pack_ord_txn_t * * bundle,
    1680         150 :                     ulong                 expires_at ) {
    1681         150 :   ulong prev_reward = ((BUNDLE_L_PRIME * (BUNDLE_N - bundle_idx))) - 1UL;
    1682         150 :   ulong prev_cost = 1UL<<32;
    1683             : 
    1684             :   /* Assign last to first */
    1685         747 :   for( ulong i=0UL; i<txn_cnt; i++ ) {
    1686         597 :     fd_pack_ord_txn_t * ord = bundle[ txn_cnt-1UL - i ];
    1687         597 :     ord->rewards = (uint)(((ulong)ord->compute_est * (prev_reward + 1UL) + prev_cost-1UL)/prev_cost);
    1688         597 :     ord->root    = FD_ORD_TXN_ROOT_PENDING_BUNDLE;
    1689         597 :     prev_reward = ord->rewards;
    1690         597 :     prev_cost   = ord->compute_est;
    1691             : 
    1692             :     /* The penalty information isn't used for bundles. */
    1693         597 :     ushort penalties  [ FD_TXN_ACCT_ADDR_MAX ];
    1694         597 :     uchar  penalty_idx[ FD_TXN_ACCT_ADDR_MAX ];
    1695         597 :     populate_bitsets( pack, ord, penalties, penalty_idx );
    1696             : 
    1697         597 :     treap_ele_insert( pack->pending_bundles, ord, pack->pool );
    1698         597 :     pack->pending_txn_cnt++;
    1699             : 
    1700         597 :     if( FD_UNLIKELY( ord->txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE ) ) noncemap_ele_insert( pack->noncemap, ord, pack->pool );
    1701         597 :     sig2txn_ele_insert( pack->signature_map, ord, pack->pool );
    1702             : 
    1703         597 :     fd_pack_expq_t temp[ 1 ] = {{ .expires_at = expires_at, .txn = ord }};
    1704         597 :     expq_insert( pack->expiration_q, temp );
    1705         597 :   }
    1706             : 
    1707         150 : }
    1708             : 
    1709             : void const *
    1710        1322 : fd_pack_peek_bundle_meta( fd_pack_t const * pack ) {
    1711        1322 :   int ib_state = pack->initializer_bundle_state;
    1712        1322 :   if( FD_UNLIKELY( (ib_state==FD_PACK_IB_STATE_PENDING) | (ib_state==FD_PACK_IB_STATE_FAILED) ) ) return NULL;
    1713             : 
    1714        1322 :   treap_rev_iter_t _cur=treap_rev_iter_init( pack->pending_bundles, pack->pool );
    1715        1322 :   if( FD_UNLIKELY( treap_rev_iter_done( _cur ) ) ) return NULL; /* empty */
    1716             : 
    1717          15 :   fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pack->pool );
    1718          15 :   int is_ib = !!(cur->txn->flags & FD_TXN_P_FLAGS_INITIALIZER_BUNDLE);
    1719          15 :   if( FD_UNLIKELY( is_ib ) ) return NULL;
    1720             : 
    1721          15 :   return (void const *)((uchar const *)pack->bundle_meta + (ulong)_cur * pack->bundle_meta_sz);
    1722          15 : }
    1723             : 
    1724             : void
    1725           9 : fd_pack_set_initializer_bundles_ready( fd_pack_t * pack ) {
    1726           9 :   pack->initializer_bundle_state = FD_PACK_IB_STATE_READY;
    1727           9 : }
    1728             : 
    1729             : void
    1730      754214 : fd_pack_metrics_write( fd_pack_t const * pack ) {
    1731      754214 :   ulong pending_regular = treap_ele_cnt( pack->pending        );
    1732      754214 :   ulong pending_votes  = treap_ele_cnt( pack->pending_votes   );
    1733      754214 :   ulong pending_bundle = treap_ele_cnt( pack->pending_bundles );
    1734      754214 :   ulong conflicting    = pack->pending_txn_cnt - pending_votes - pending_bundle - treap_ele_cnt( pack->pending );
    1735      754214 :   FD_MGAUGE_SET( PACK, AVAILABLE_TRANSACTIONS_ALL,         pack->pending_txn_cnt       );
    1736      754214 :   FD_MGAUGE_SET( PACK, AVAILABLE_TRANSACTIONS_REGULAR,     pending_regular             );
    1737      754214 :   FD_MGAUGE_SET( PACK, AVAILABLE_TRANSACTIONS_VOTES,       pending_votes               );
    1738      754214 :   FD_MGAUGE_SET( PACK, AVAILABLE_TRANSACTIONS_CONFLICTING, conflicting                 );
    1739      754214 :   FD_MGAUGE_SET( PACK, AVAILABLE_TRANSACTIONS_BUNDLES,     pending_bundle              );
    1740      754214 :   FD_MGAUGE_SET( PACK, SMALLEST_PENDING_TRANSACTION,       pack->pending_smallest->cus );
    1741      754214 : }
    1742             : 
    1743             : typedef struct {
    1744             :   ushort clear_rw_bit;
    1745             :   ushort clear_w_bit;
    1746             : } release_result_t;
    1747             : 
    1748             : static inline release_result_t
    1749             : release_bit_reference( fd_pack_t            * pack,
    1750    17848668 :                        fd_acct_addr_t const * acct ) {
    1751             : 
    1752    17848668 :   fd_pack_bitset_acct_mapping_t * q = bitset_map_query( pack->acct_to_bitset, *acct, NULL );
    1753    17848668 :   FD_TEST( q ); /* q==NULL not be possible */
    1754             : 
    1755    17848668 :   q->ref_cnt--;
    1756             : 
    1757    17848668 :   if( FD_UNLIKELY( q->ref_cnt==0UL ) ) {
    1758    13306205 :     ushort bit = q->bit;
    1759    13306205 :     bitset_map_remove( pack->acct_to_bitset, q );
    1760    13306205 :     if( FD_LIKELY( bit<FD_PACK_BITSET_MAX ) ) pack->bitset_avail[ ++(pack->bitset_avail_cnt) ] = bit;
    1761             : 
    1762    13306205 :     fd_pack_addr_use_t * use = acct_uses_query( pack->acct_in_use,  *acct, NULL );
    1763    13306205 :     if( FD_LIKELY( use ) ) {
    1764    12810141 :       use->in_use_by |= FD_PACK_IN_USE_BIT_CLEARED;
    1765    12810141 :       release_result_t ret = { .clear_rw_bit = bit,
    1766    12810141 :                                .clear_w_bit = fd_ushort_if( !!(use->in_use_by & FD_PACK_IN_USE_WRITABLE), bit, FD_PACK_BITSET_MAX ) };
    1767    12810141 :       return ret;
    1768    12810141 :     }
    1769    13306205 :   }
    1770     5038527 :   release_result_t ret = { .clear_rw_bit = FD_PACK_BITSET_MAX, .clear_w_bit = FD_PACK_BITSET_MAX };
    1771     5038527 :   return ret;
    1772    17848668 : }
    1773             : 
    1774             : typedef struct {
    1775             :   ulong cus_scheduled;
    1776             :   ulong txns_scheduled;
    1777             :   ulong bytes_scheduled;
    1778             : } sched_return_t;
    1779             : 
    1780             : static inline sched_return_t
    1781             : fd_pack_schedule_impl( fd_pack_t          * pack,
    1782             :                        treap_t            * sched_from,
    1783             :                        ulong                cu_limit,
    1784             :                        ulong                txn_limit,
    1785             :                        ulong                byte_limit,
    1786             :                        ulong                bank_tile,
    1787             :                        fd_pack_smallest_t * smallest_in_treap,
    1788             :                        ulong              * use_by_bank_txn,
    1789     1508350 :                        fd_txn_p_t         * out ) {
    1790             : 
    1791     1508350 :   fd_pack_ord_txn_t  * pool         = pack->pool;
    1792     1508350 :   fd_pack_addr_use_t * acct_in_use  = pack->acct_in_use;
    1793     1508350 :   fd_pack_addr_use_t * writer_costs = pack->writer_costs;
    1794             : 
    1795     1508350 :   fd_pack_addr_use_t ** written_list     = pack->written_list;
    1796     1508350 :   ulong                 written_list_cnt = pack->written_list_cnt;
    1797     1508350 :   ulong                 written_list_max = pack->written_list_max;
    1798             : 
    1799     1508350 :   FD_PACK_BITSET_DECLARE( bitset_rw_in_use );
    1800     1508350 :   FD_PACK_BITSET_DECLARE( bitset_w_in_use  );
    1801     1508350 :   FD_PACK_BITSET_COPY( bitset_rw_in_use, pack->bitset_rw_in_use );
    1802     1508350 :   FD_PACK_BITSET_COPY( bitset_w_in_use,  pack->bitset_w_in_use  );
    1803             : 
    1804     1508350 :   fd_pack_addr_use_t * use_by_bank     = pack->use_by_bank    [bank_tile];
    1805     1508350 :   ulong                use_by_bank_cnt = pack->use_by_bank_cnt[bank_tile];
    1806             : 
    1807     1508350 :   ulong max_write_cost_per_acct = pack->lim->max_write_cost_per_acct;
    1808             : 
    1809     1508350 :   ushort compressed_slot_number = pack->compressed_slot_number;
    1810             : 
    1811     1508350 :   ulong txns_scheduled  = 0UL;
    1812     1508350 :   ulong cus_scheduled   = 0UL;
    1813     1508350 :   ulong bytes_scheduled = 0UL;
    1814             : 
    1815     1508350 :   ulong bank_tile_mask = 1UL << bank_tile;
    1816             : 
    1817     1508350 :   ulong fast_path     = 0UL;
    1818     1508350 :   ulong slow_path     = 0UL;
    1819     1508350 :   ulong cu_limit_c    = 0UL;
    1820     1508350 :   ulong byte_limit_c  = 0UL;
    1821     1508350 :   ulong write_limit_c = 0UL;
    1822     1508350 :   ulong skip_c        = 0UL;
    1823             : 
    1824     1508350 :   ulong min_cus   = ULONG_MAX;
    1825     1508350 :   ulong min_bytes = ULONG_MAX;
    1826             : 
    1827     1508350 :   if( FD_UNLIKELY( (cu_limit<smallest_in_treap->cus) | (txn_limit==0UL) | (byte_limit<smallest_in_treap->bytes) ) ) {
    1828      815498 :     sched_return_t to_return = { .cus_scheduled = 0UL, .txns_scheduled = 0UL, .bytes_scheduled = 0UL };
    1829      815498 :     return to_return;
    1830      815498 :   }
    1831             : 
    1832      692852 :   treap_rev_iter_t prev = treap_idx_null();
    1833    23925446 :   for( treap_rev_iter_t _cur=treap_rev_iter_init( sched_from, pool ); !treap_rev_iter_done( _cur ); _cur=prev ) {
    1834             :     /* Capture next so that we can delete while we iterate. */
    1835    23840111 :     prev = treap_rev_iter_next( _cur, pool );
    1836             : 
    1837    23840111 : #   if FD_HAS_X86
    1838    23840111 :     _mm_prefetch( &(pool[ prev ].prev),      _MM_HINT_T0 );
    1839    23840111 : #   endif
    1840             : 
    1841    23840111 :     fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pool );
    1842             : 
    1843    23840111 :     min_cus   = fd_ulong_min( min_cus,   cur->compute_est     );
    1844    23840111 :     min_bytes = fd_ulong_min( min_bytes, cur->txn->payload_sz );
    1845             : 
    1846    23840111 :     ulong conflicts = 0UL;
    1847             : 
    1848    23840111 :     if( FD_UNLIKELY( cur->compute_est>cu_limit ) ) {
    1849             :       /* Too big to be scheduled at the moment, but might be okay for
    1850             :          the next microblock, so we don't want to delay it. */
    1851           0 :       cu_limit_c++;
    1852           0 :       continue;
    1853           0 :     }
    1854             : 
    1855             :     /* Likely? Unlikely? */
    1856    23840111 :     if( FD_LIKELY( !FD_PACK_BITSET_INTERSECT4_EMPTY( bitset_rw_in_use, bitset_w_in_use, cur->w_bitset, cur->rw_bitset ) ) ) {
    1857    10752822 :       fast_path++;
    1858    10752822 :       continue;
    1859    10752822 :     }
    1860             : 
    1861    13087289 :     if( FD_UNLIKELY( cur->skip==compressed_slot_number ) ) {
    1862           0 :       skip_c++;
    1863           0 :       continue;
    1864           0 :     }
    1865             : 
    1866             :     /* If skip>FD_PACK_MAX_SKIP but not compressed_slot_number, it means
    1867             :        it's the compressed slot number of a previous slot.  We don't
    1868             :        care unless we're going to update the value though, so we don't
    1869             :        need to eagerly reset it to FD_PACK_MAX_SKIP.
    1870             :        compressed_slot_number is a ushort, so it's possible for it to
    1871             :        roll over, but the transaction lifetime is much shorter than
    1872             :        that, so it won't be a problem. */
    1873             : 
    1874    13087289 :     if( FD_UNLIKELY( cur->txn->payload_sz>byte_limit ) ) {
    1875           6 :       byte_limit_c++;
    1876           6 :       continue;
    1877           6 :     }
    1878             : 
    1879             : 
    1880    13087283 :     fd_txn_t const * txn = TXN(cur->txn);
    1881    13087283 :     fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, cur->txn->payload );
    1882    13087283 :     fd_acct_addr_t const * alt_adj = cur->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    1883             :     /* Check conflicts between this transaction's writable accounts and
    1884             :        current readers */
    1885    13087283 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    1886    27344743 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    1887             : 
    1888    14257463 :       fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    1889             : 
    1890    14257463 :       fd_pack_addr_use_t * in_wcost_table = acct_uses_query( writer_costs, acct, NULL );
    1891    14257463 :       if( FD_UNLIKELY( in_wcost_table && in_wcost_table->total_cost+cur->compute_est > max_write_cost_per_acct ) ) {
    1892             :         /* Can't be scheduled until the next block */
    1893           3 :         conflicts = ULONG_MAX;
    1894           3 :         break;
    1895           3 :       }
    1896             : 
    1897    14257460 :       fd_pack_addr_use_t * use = acct_uses_query( acct_in_use, acct, NULL );
    1898    14257460 :       if( FD_UNLIKELY( use ) ) conflicts |= use->in_use_by; /* break? */
    1899    14257460 :     }
    1900             : 
    1901    13087283 :     if( FD_UNLIKELY( conflicts==ULONG_MAX ) ) {
    1902             :       /* The logic for how to adjust skip is a bit complicated, and we
    1903             :          want to do it branchlessly. Let psc=FD_PACK_SKIP_CNT,
    1904             :            Before                   After
    1905             :              1               compressed_slot_number
    1906             :            x in [2, psc]             x-1
    1907             :            x where x>psc            psc-1
    1908             : 
    1909             :          Set A=min(x, 5), B=min(A-2, compressed_slot_number-1), and
    1910             :          note that compressed_slot_number is in [psc+1, USHORT_MAX].
    1911             :          Then:
    1912             :              x                A     A-2          B      B+1
    1913             :              1                1  USHORT_MAX    csn-1    csn
    1914             :            x in [2, psc]      x     x-2         x-2     x-1
    1915             :            x where x>psc     psc   psc-2       psc-2   psc-1
    1916             :          So B+1 is the desired value. */
    1917           3 :       cur->skip = (ushort)(1+fd_ushort_min( (ushort)(compressed_slot_number-1),
    1918           3 :                                             (ushort)(fd_ushort_min( cur->skip, FD_PACK_SKIP_CNT )-2) ) );
    1919           3 :       write_limit_c++;
    1920           3 :       continue;
    1921           3 :     }
    1922             : 
    1923    13087280 :     if( FD_UNLIKELY( conflicts ) ) {
    1924           6 :       slow_path++;
    1925           6 :       continue;
    1926           6 :     }
    1927             : 
    1928             :     /* Check conflicts between this transaction's readonly accounts and
    1929             :        current writers */
    1930    13087274 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_READONLY );
    1931    16662599 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    1932             : 
    1933     3575325 :       fd_acct_addr_t const * acct = ACCT_ITER_TO_PTR( iter );
    1934     3575325 :       if( fd_pack_unwritable_contains( acct ) ) continue; /* No need to track sysvars because they can't be writable */
    1935             : 
    1936     2578729 :       fd_pack_addr_use_t * use = acct_uses_query( acct_in_use,  *acct, NULL );
    1937     2578729 :       if( use ) conflicts |= (use->in_use_by & FD_PACK_IN_USE_WRITABLE) ? use->in_use_by : 0UL;
    1938     2578729 :     }
    1939             : 
    1940    13087274 :     if( FD_UNLIKELY( conflicts ) ) {
    1941           0 :       slow_path++;
    1942           0 :       continue;
    1943           0 :     }
    1944             : 
    1945             :     /* Include this transaction in the microblock! */
    1946    13087274 :     FD_PACK_BITSET_OR( bitset_rw_in_use, cur->rw_bitset );
    1947    13087274 :     FD_PACK_BITSET_OR( bitset_w_in_use,  cur->w_bitset  );
    1948             : 
    1949    13087274 :     if(
    1950     4362425 : #if FD_HAS_AVX512 && FD_PACK_USE_NON_TEMPORAL_MEMCPY
    1951     4362425 :         FD_LIKELY( cur->txn->payload_sz>=1024UL )
    1952             : #else
    1953     8724849 :         0
    1954     8724849 : #endif
    1955    13087274 :       ) {
    1956        4224 : #if FD_HAS_AVX512 && FD_PACK_USE_NON_TEMPORAL_MEMCPY
    1957        4224 :       _mm512_stream_si512( (void*)(out->payload+   0UL), _mm512_load_epi64( cur->txn->payload+   0UL ) );
    1958        4224 :       _mm512_stream_si512( (void*)(out->payload+  64UL), _mm512_load_epi64( cur->txn->payload+  64UL ) );
    1959        4224 :       _mm512_stream_si512( (void*)(out->payload+ 128UL), _mm512_load_epi64( cur->txn->payload+ 128UL ) );
    1960        4224 :       _mm512_stream_si512( (void*)(out->payload+ 192UL), _mm512_load_epi64( cur->txn->payload+ 192UL ) );
    1961        4224 :       _mm512_stream_si512( (void*)(out->payload+ 256UL), _mm512_load_epi64( cur->txn->payload+ 256UL ) );
    1962        4224 :       _mm512_stream_si512( (void*)(out->payload+ 320UL), _mm512_load_epi64( cur->txn->payload+ 320UL ) );
    1963        4224 :       _mm512_stream_si512( (void*)(out->payload+ 384UL), _mm512_load_epi64( cur->txn->payload+ 384UL ) );
    1964        4224 :       _mm512_stream_si512( (void*)(out->payload+ 448UL), _mm512_load_epi64( cur->txn->payload+ 448UL ) );
    1965        4224 :       _mm512_stream_si512( (void*)(out->payload+ 512UL), _mm512_load_epi64( cur->txn->payload+ 512UL ) );
    1966        4224 :       _mm512_stream_si512( (void*)(out->payload+ 576UL), _mm512_load_epi64( cur->txn->payload+ 576UL ) );
    1967        4224 :       _mm512_stream_si512( (void*)(out->payload+ 640UL), _mm512_load_epi64( cur->txn->payload+ 640UL ) );
    1968        4224 :       _mm512_stream_si512( (void*)(out->payload+ 704UL), _mm512_load_epi64( cur->txn->payload+ 704UL ) );
    1969        4224 :       _mm512_stream_si512( (void*)(out->payload+ 768UL), _mm512_load_epi64( cur->txn->payload+ 768UL ) );
    1970        4224 :       _mm512_stream_si512( (void*)(out->payload+ 832UL), _mm512_load_epi64( cur->txn->payload+ 832UL ) );
    1971        4224 :       _mm512_stream_si512( (void*)(out->payload+ 896UL), _mm512_load_epi64( cur->txn->payload+ 896UL ) );
    1972        4224 :       _mm512_stream_si512( (void*)(out->payload+ 960UL), _mm512_load_epi64( cur->txn->payload+ 960UL ) );
    1973        4224 :       _mm512_stream_si512( (void*)(out->payload+1024UL), _mm512_load_epi64( cur->txn->payload+1024UL ) );
    1974        4224 :       _mm512_stream_si512( (void*)(out->payload+1088UL), _mm512_load_epi64( cur->txn->payload+1088UL ) );
    1975        4224 :       _mm512_stream_si512( (void*)(out->payload+1152UL), _mm512_load_epi64( cur->txn->payload+1152UL ) );
    1976        4224 :       _mm512_stream_si512( (void*)(out->payload+1216UL), _mm512_load_epi64( cur->txn->payload+1216UL ) );
    1977             :       /* Copied out to 1280 bytes, which copies some other fields we needed to
    1978             :          copy anyway. */
    1979        4224 :       FD_STATIC_ASSERT( offsetof(fd_txn_p_t, payload_sz     )+sizeof(((fd_txn_p_t*)NULL)->payload_sz    )<=1280UL, nt_memcpy );
    1980        4224 :       FD_STATIC_ASSERT( offsetof(fd_txn_p_t, blockhash_slot )+sizeof(((fd_txn_p_t*)NULL)->blockhash_slot)<=1280UL, nt_memcpy );
    1981        4224 :       FD_STATIC_ASSERT( offsetof(fd_txn_p_t, scheduler_arrival_time_nanos )+sizeof(((fd_txn_p_t*)NULL)->scheduler_arrival_time_nanos )<=1280UL, nt_memcpy );
    1982        4224 :       FD_STATIC_ASSERT( offsetof(fd_txn_p_t, source_tpu     )+sizeof(((fd_txn_p_t*)NULL)->source_tpu    )<=1280UL, nt_memcpy );
    1983        4224 :       FD_STATIC_ASSERT( offsetof(fd_txn_p_t, source_ipv4    )+sizeof(((fd_txn_p_t*)NULL)->source_ipv4   )<=1280UL, nt_memcpy );
    1984        4224 :       FD_STATIC_ASSERT( offsetof(fd_txn_p_t, flags          )+sizeof(((fd_txn_p_t*)NULL)->flags         )<=1280UL, nt_memcpy );
    1985        4224 :       FD_STATIC_ASSERT( offsetof(fd_txn_p_t, _              )                                            <=1280UL, nt_memcpy );
    1986        4224 :       const ulong offset_into_txn = 1280UL - offsetof(fd_txn_p_t, _ );
    1987        4224 :       fd_memcpy( offset_into_txn+(uchar *)TXN(out), offset_into_txn+(uchar const *)txn,
    1988        4224 :           fd_ulong_max( offset_into_txn, fd_txn_footprint( txn->instr_cnt, txn->addr_table_lookup_cnt ) )-offset_into_txn );
    1989        4224 : #endif
    1990    13083050 :     } else {
    1991    13083050 :       fd_memcpy( out->payload, cur->txn->payload, cur->txn->payload_sz                                           );
    1992    13083050 :       fd_memcpy( TXN(out),     txn,               fd_txn_footprint( txn->instr_cnt, txn->addr_table_lookup_cnt ) );
    1993    13083050 :       out->payload_sz                      = cur->txn->payload_sz;
    1994    13083050 :       out->pack_cu.requested_exec_plus_acct_data_cus = cur->txn->pack_cu.requested_exec_plus_acct_data_cus;
    1995    13083050 :       out->pack_cu.non_execution_cus       = cur->txn->pack_cu.non_execution_cus;
    1996    13083050 :       out->scheduler_arrival_time_nanos    = cur->txn->scheduler_arrival_time_nanos;
    1997    13083050 :       out->source_tpu                      = cur->txn->source_tpu;
    1998    13083050 :       out->source_ipv4                     = cur->txn->source_ipv4;
    1999    13083050 :       out->flags                           = cur->txn->flags;
    2000    13083050 :     }
    2001    13087274 :     out++;
    2002             : 
    2003    13087274 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    2004    27344719 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2005    14257445 :       fd_acct_addr_t acct_addr = *ACCT_ITER_TO_PTR( iter );
    2006             : 
    2007    14257445 :       fd_pack_addr_use_t * in_wcost_table = acct_uses_query( writer_costs, acct_addr, NULL );
    2008    14257445 :       if( !in_wcost_table ) {
    2009      794124 :         in_wcost_table = acct_uses_insert( writer_costs, acct_addr );
    2010      794124 :         in_wcost_table->total_cost = 0UL;
    2011      794124 :         written_list[ written_list_cnt ] = in_wcost_table;
    2012      794124 :         written_list_cnt = fd_ulong_min( written_list_cnt+1UL, written_list_max-1UL );
    2013      794124 :       }
    2014    14257445 :       in_wcost_table->total_cost += cur->compute_est;
    2015             : 
    2016    14257445 :       fd_pack_addr_use_t * use = acct_uses_insert( acct_in_use, acct_addr );
    2017    14257445 :       use->in_use_by = bank_tile_mask | FD_PACK_IN_USE_WRITABLE;
    2018             : 
    2019    14257445 :       use_by_bank[use_by_bank_cnt++] = *use;
    2020             : 
    2021             :       /* If there aren't any more references to this account in the
    2022             :          heap, it can't cause any conflicts.  That means we actually
    2023             :          don't need to record that we are using it, which is good
    2024             :          because we want to release the bit. */
    2025    14257445 :       release_result_t ret = release_bit_reference( pack, &acct_addr );
    2026    14257445 :       FD_PACK_BITSET_CLEARN( bitset_rw_in_use, ret.clear_rw_bit );
    2027    14257445 :       FD_PACK_BITSET_CLEARN( bitset_w_in_use,  ret.clear_w_bit  );
    2028    14257445 :     }
    2029    13087274 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_READONLY );
    2030    16662599 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2031             : 
    2032     3575325 :       fd_acct_addr_t acct_addr = *ACCT_ITER_TO_PTR( iter );
    2033             : 
    2034     3575325 :       if( fd_pack_unwritable_contains( &acct_addr ) ) continue; /* No need to track sysvars because they can't be writable */
    2035             : 
    2036     2578729 :       fd_pack_addr_use_t * use = acct_uses_query( acct_in_use,  acct_addr, NULL );
    2037     2578729 :       if( !use ) { use = acct_uses_insert( acct_in_use, acct_addr ); use->in_use_by = 0UL; }
    2038             : 
    2039     2578729 :       if( !(use->in_use_by & bank_tile_mask) ) use_by_bank[use_by_bank_cnt++] = *use;
    2040     2578729 :       use->in_use_by |= bank_tile_mask;
    2041     2578729 :       use->in_use_by &= ~FD_PACK_IN_USE_BIT_CLEARED;
    2042             : 
    2043             : 
    2044     2578729 :       release_result_t ret = release_bit_reference( pack, &acct_addr );
    2045     2578729 :       FD_PACK_BITSET_CLEARN( bitset_rw_in_use, ret.clear_rw_bit );
    2046     2578729 :       FD_PACK_BITSET_CLEARN( bitset_w_in_use,  ret.clear_w_bit  );
    2047     2578729 :     }
    2048             : 
    2049    13087274 :     txns_scheduled  += 1UL;                      txn_limit       -= 1UL;
    2050    13087274 :     cus_scheduled   += cur->compute_est;         cu_limit        -= cur->compute_est;
    2051    13087274 :     bytes_scheduled += cur->txn->payload_sz;     byte_limit      -= cur->txn->payload_sz;
    2052             : 
    2053    13087274 :     *(use_by_bank_txn++) = use_by_bank_cnt;
    2054             : 
    2055    13087274 :     if( FD_UNLIKELY( cur->txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE ) ) noncemap_ele_remove_fast( pack->noncemap, cur, pack->pool );
    2056    13087274 :     sig2txn_ele_remove_fast( pack->signature_map, cur, pool );
    2057             : 
    2058    13087274 :     cur->root = FD_ORD_TXN_ROOT_FREE;
    2059    13087274 :     expq_remove( pack->expiration_q, cur->expq_idx );
    2060    13087274 :     treap_idx_remove( sched_from, _cur, pool );
    2061    13087274 :     trp_pool_idx_release( pool, _cur );
    2062    13087274 :     pack->pending_txn_cnt--;
    2063             : 
    2064    13087274 :     if( FD_UNLIKELY( (cu_limit<smallest_in_treap->cus) | (txn_limit==0UL) | (byte_limit<smallest_in_treap->bytes) ) ) break;
    2065    13087274 :   }
    2066             : 
    2067      692852 :   FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_TAKEN,      txns_scheduled );
    2068      692852 :   FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_CU_LIMIT,   cu_limit_c     );
    2069      692852 :   FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_FAST_PATH,  fast_path      );
    2070      692852 :   FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_BYTE_LIMIT, byte_limit_c   );
    2071      692852 :   FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_WRITE_COST, write_limit_c  );
    2072      692852 :   FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_SLOW_PATH,  slow_path      );
    2073      692852 :   FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_DEFER_SKIP, skip_c         );
    2074             : 
    2075             :   /* If we scanned the whole treap and didn't break early, we now have a
    2076             :      better estimate of the smallest. */
    2077      692852 :   if( FD_UNLIKELY( treap_rev_iter_done( prev ) ) ) {
    2078       88392 :     smallest_in_treap->cus   = min_cus;
    2079       88392 :     smallest_in_treap->bytes = min_bytes;
    2080       88392 :   }
    2081             : 
    2082      692852 :   pack->use_by_bank_cnt[bank_tile] = use_by_bank_cnt;
    2083      692852 :   FD_PACK_BITSET_COPY( pack->bitset_rw_in_use, bitset_rw_in_use );
    2084      692852 :   FD_PACK_BITSET_COPY( pack->bitset_w_in_use,  bitset_w_in_use  );
    2085             : 
    2086      692852 :   pack->written_list_cnt = written_list_cnt;
    2087             : 
    2088      692852 :   sched_return_t to_return = { .cus_scheduled=cus_scheduled, .txns_scheduled=txns_scheduled, .bytes_scheduled=bytes_scheduled };
    2089      692852 :   return to_return;
    2090     1508350 : }
    2091             : 
    2092             : int
    2093             : fd_pack_microblock_complete( fd_pack_t * pack,
    2094      754221 :                              ulong       bank_tile ) {
    2095             :   /* If the account is in use writably, and it's in use by this banking
    2096             :      tile, then this banking tile must be the sole writer to it, so it's
    2097             :      always okay to clear the writable bit. */
    2098      754221 :   ulong clear_mask = ~((1UL<<bank_tile) | FD_PACK_IN_USE_WRITABLE);
    2099             : 
    2100             :   /* If nothing outstanding, bail quickly */
    2101      754221 :   if( FD_UNLIKELY( !(pack->outstanding_microblock_mask & (1UL<<bank_tile)) ) ) return 0;
    2102             : 
    2103      686883 :   FD_PACK_BITSET_DECLARE( bitset_rw_in_use );
    2104      686883 :   FD_PACK_BITSET_DECLARE( bitset_w_in_use  );
    2105      686883 :   FD_PACK_BITSET_COPY( bitset_rw_in_use, pack->bitset_rw_in_use );
    2106      686883 :   FD_PACK_BITSET_COPY( bitset_w_in_use,  pack->bitset_w_in_use  );
    2107             : 
    2108      686883 :   fd_pack_addr_use_t * base = pack->use_by_bank[bank_tile];
    2109             : 
    2110      686883 :   fd_pack_ord_txn_t       * best         = NULL;
    2111      686883 :   fd_pack_penalty_treap_t * best_penalty = NULL;
    2112      686883 :   ulong                     txn_cnt      = 0UL;
    2113             : 
    2114    16901280 :   for( ulong i=0UL; i<pack->use_by_bank_cnt[bank_tile]; i++ ) {
    2115    16214397 :     fd_pack_addr_use_t * use = acct_uses_query( pack->acct_in_use, base[i].key, NULL );
    2116    16214397 :     FD_TEST( use );
    2117    16214397 :     use->in_use_by &= clear_mask;
    2118             : 
    2119             :     /* In order to properly bound the size of bitset_map, we need to
    2120             :        release the "reference" to the account when we schedule it.
    2121             :        However, that poses a bit of a problem here, because by the time
    2122             :        we complete the microblock, that account could have been assigned
    2123             :        a different bit in the bitset.  The scheduling step tells us if
    2124             :        that is the case, and if so, we know that the bits in
    2125             :        bitset_w_in_use and bitset_rw_in_use were already cleared as
    2126             :        necessary.
    2127             : 
    2128             :        Note that it's possible for BIT_CLEARED to be set and then unset
    2129             :        by later uses, but then the account would be in use on other
    2130             :        banks, so we wouldn't try to observe the old value.  For example:
    2131             :        Suppose bit 0->account A, bit 1->account B, and we have two
    2132             :        transactions that read A, B.  We schedule a microblock to bank 0,
    2133             :        taking both transactions, which sets the counts for A, B to 0,
    2134             :        and releases the bits, clearing bits 0 and 1, and setting
    2135             :        BIT_CLEARED.  Then we get two more transactions that read
    2136             :        accounts C, D, A, B, and they get assigned 0->C, 1->D, 2->A,
    2137             :        3->B.  We try to schedule a microblock to bank 1 that takes one
    2138             :        of those transactions.  This unsets BIT_CLEARED for A, B.
    2139             :        Finally, the first microblock completes.  Even though the bitset
    2140             :        map has the new bits for A and B which are "wrong" compared to
    2141             :        when the transaction was initially scheduled, those bits have
    2142             :        already been cleared and reset properly in the bitset as needed.
    2143             :        A and B will still be in use by bank 1, so we won't clear any
    2144             :        bits.  If, on the other hand, the microblock scheduled to bank 1
    2145             :        completes first, bits 0 and 1 will be cleared for accounts C and
    2146             :        D, while bits 2 and 3 will remain set, which is correct.  Then
    2147             :        when bank 0 completes, bits 2 and 3 will be cleared. */
    2148    16214397 :     if( FD_LIKELY( !use->in_use_by ) ) { /* if in_use_by==0, doesn't include BIT_CLEARED */
    2149     3412413 :       fd_pack_bitset_acct_mapping_t * q = bitset_map_query( pack->acct_to_bitset, base[i].key, NULL );
    2150     3412413 :       FD_TEST( q );
    2151     3412413 :       FD_PACK_BITSET_CLEARN( bitset_w_in_use,  q->bit );
    2152     3412413 :       FD_PACK_BITSET_CLEARN( bitset_rw_in_use, q->bit );
    2153             : 
    2154             :       /* Because this account is no longer in use, it might be possible
    2155             :          to schedule a transaction that writes to it.  Check its
    2156             :          penalty treap if it has one, and potentially move it to the
    2157             :          main treap. */
    2158     3412413 :       fd_pack_penalty_treap_t * p_trp = penalty_map_query( pack->penalty_treaps, base[i].key, NULL );
    2159     3412413 :       if( FD_UNLIKELY( p_trp ) ) {
    2160      752813 :         fd_pack_ord_txn_t * best_in_trp = treap_rev_iter_ele( treap_rev_iter_init( p_trp->penalty_treap, pack->pool ), pack->pool );
    2161      752813 :         if( FD_UNLIKELY( !best || COMPARE_WORSE( best, best_in_trp ) ) ) {
    2162      301626 :           best         = best_in_trp;
    2163      301626 :           best_penalty = p_trp;
    2164      301626 :         }
    2165      752813 :       }
    2166     3412413 :     }
    2167             : 
    2168    16214397 :     if( FD_LIKELY( !(use->in_use_by & ~FD_PACK_IN_USE_BIT_CLEARED) ) ) acct_uses_remove( pack->acct_in_use, use );
    2169             : 
    2170    16214397 :     if( FD_UNLIKELY( i+1UL==pack->use_by_bank_txn[ bank_tile ][ txn_cnt ] ) ) {
    2171    13083486 :       txn_cnt++;
    2172    13083486 :       if( FD_LIKELY( best ) ) {
    2173             :         /* move best to the main treap */
    2174      301626 :         treap_ele_remove( best_penalty->penalty_treap, best, pack->pool );
    2175      301626 :         best->root = FD_ORD_TXN_ROOT_PENDING;
    2176      301626 :         treap_ele_insert( pack->pending,               best, pack->pool );
    2177             : 
    2178      301626 :         pack->pending_smallest->cus   = fd_ulong_min( pack->pending_smallest->cus,   best->compute_est             );
    2179      301626 :         pack->pending_smallest->bytes = fd_ulong_min( pack->pending_smallest->bytes, best->txn_e->txnp->payload_sz );
    2180             : 
    2181      301626 :         if( FD_UNLIKELY( !treap_ele_cnt( best_penalty->penalty_treap ) ) ) {
    2182        2892 :           treap_delete( treap_leave( best_penalty->penalty_treap ) );
    2183             :           /* Removal invalidates any pointers we got from
    2184             :              penalty_map_query, but we immediately set these to NULL, so
    2185             :              we're not keeping any pointers around. */
    2186        2892 :           penalty_map_remove( pack->penalty_treaps, best_penalty );
    2187        2892 :         }
    2188      301626 :         best         = NULL;
    2189      301626 :         best_penalty = NULL;
    2190      301626 :       }
    2191    13083486 :     }
    2192    16214397 :   }
    2193             : 
    2194      686883 :   pack->use_by_bank_cnt[bank_tile] = 0UL;
    2195             : 
    2196      686883 :   FD_PACK_BITSET_COPY( pack->bitset_rw_in_use, bitset_rw_in_use );
    2197      686883 :   FD_PACK_BITSET_COPY( pack->bitset_w_in_use,  bitset_w_in_use  );
    2198             : 
    2199             :   /* outstanding_microblock_mask never has the writable bit set, so we
    2200             :      don't care about clearing it here either. */
    2201      686883 :   pack->outstanding_microblock_mask &= clear_mask;
    2202      686883 :   return 1;
    2203      686883 : }
    2204             : 
    2205      753995 : #define TRY_BUNDLE_NO_READY_BUNDLES      0
    2206          21 : #define TRY_BUNDLE_HAS_CONFLICTS       (-1)
    2207          21 : #define TRY_BUNDLE_DOES_NOT_FIT        (-2)
    2208          21 : #define TRY_BUNDLE_SUCCESS(n)          ( n) /* schedule bundle with n transactions */
    2209             : static inline int
    2210             : fd_pack_try_schedule_bundle( fd_pack_t  * pack,
    2211             :                              ulong        bank_tile,
    2212      754016 :                              fd_txn_p_t * out ) {
    2213      754016 :   int state = pack->initializer_bundle_state;
    2214      754016 :   if( FD_UNLIKELY( (state==FD_PACK_IB_STATE_PENDING) | (state==FD_PACK_IB_STATE_FAILED ) ) ) return TRY_BUNDLE_NO_READY_BUNDLES;
    2215             : 
    2216      754016 :   fd_pack_ord_txn_t * pool    = pack->pool;
    2217      754016 :   treap_t           * bundles = pack->pending_bundles;
    2218             : 
    2219      754016 :   int require_ib;
    2220      754016 :   if( FD_UNLIKELY( state==FD_PACK_IB_STATE_NOT_INITIALIZED ) ) { require_ib = 1; }
    2221      754016 :   if( FD_LIKELY  ( state==FD_PACK_IB_STATE_READY           ) ) { require_ib = 0; }
    2222             : 
    2223      754016 :   treap_rev_iter_t _cur  = treap_rev_iter_init( bundles, pool );
    2224      754016 :   ulong bundle_idx = ULONG_MAX;
    2225             : 
    2226      754016 :   if( FD_UNLIKELY( treap_rev_iter_done( _cur ) ) ) return TRY_BUNDLE_NO_READY_BUNDLES;
    2227             : 
    2228          21 :   treap_rev_iter_t   _txn0 = _cur;
    2229          21 :   fd_pack_ord_txn_t * txn0 = treap_rev_iter_ele( _txn0, pool );
    2230          21 :   int is_ib = !!(txn0->txn->flags & FD_TXN_P_FLAGS_INITIALIZER_BUNDLE);
    2231          21 :   bundle_idx = RC_TO_REL_BUNDLE_IDX( txn0->rewards, txn0->compute_est );
    2232             : 
    2233          21 :   if( FD_UNLIKELY( require_ib & !is_ib ) ) return TRY_BUNDLE_NO_READY_BUNDLES;
    2234             : 
    2235             :   /* At this point, we have our candidate bundle, so we'll schedule it
    2236             :      if we can.  If we can't, we won't schedule anything. */
    2237             : 
    2238             : 
    2239          21 :   fd_pack_addr_use_t * bundle_temp_inserted[ FD_PACK_MAX_TXN_PER_BUNDLE * FD_TXN_ACCT_ADDR_MAX ];
    2240          21 :   ulong bundle_temp_inserted_cnt = 0UL;
    2241             : 
    2242          21 :   ulong bank_tile_mask = 1UL << bank_tile;
    2243             : 
    2244          21 :   int doesnt_fit   = 0;
    2245          21 :   int has_conflict = 0;
    2246          21 :   ulong txn_cnt = 0UL;
    2247             : 
    2248          21 :   ulong cu_limit         = pack->lim->max_cost_per_block        - pack->cumulative_block_cost;
    2249          21 :   ulong byte_limit       = pack->lim->max_data_bytes_per_block  - pack->data_bytes_consumed;
    2250          21 :   ulong microblock_limit = pack->lim->max_microblocks_per_block - pack->microblock_cnt;
    2251             : 
    2252          21 :   FD_PACK_BITSET_DECLARE( bitset_rw_in_use );
    2253          21 :   FD_PACK_BITSET_DECLARE( bitset_w_in_use  );
    2254          21 :   FD_PACK_BITSET_COPY( bitset_rw_in_use, pack->bitset_rw_in_use );
    2255          21 :   FD_PACK_BITSET_COPY( bitset_w_in_use,  pack->bitset_w_in_use  );
    2256             : 
    2257             :   /* last_use_in_txn_cnt[i+1] Keeps track of the number of accounts that
    2258             :      have their last reference in transaction i of the bundle.  This
    2259             :      esoteric value is important for computing use_by_bank_txn.
    2260             :      last_use_in_txn_cnt[0] is garbage. */
    2261          21 :   ulong last_use_in_txn_cnt[ 1UL+FD_PACK_MAX_TXN_PER_BUNDLE ] = { 0UL };
    2262             : 
    2263          21 :   fd_pack_addr_use_t   null_use[1]    = {{{{ 0 }}, { 0 }}};
    2264             : 
    2265          75 :   while( !(doesnt_fit | has_conflict) & !treap_rev_iter_done( _cur ) ) {
    2266          63 :     fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pool );
    2267          63 :     ulong this_bundle_idx = RC_TO_REL_BUNDLE_IDX( cur->rewards, cur->compute_est );
    2268          63 :     if( FD_UNLIKELY( this_bundle_idx!=bundle_idx ) ) break;
    2269             : 
    2270          54 :     if( FD_UNLIKELY( cur->compute_est>cu_limit ) ) {
    2271           0 :       doesnt_fit = 1;
    2272           0 :       FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_CU_LIMIT,   1UL );
    2273           0 :       break;
    2274           0 :     }
    2275          54 :     cu_limit -= cur->compute_est;
    2276             : 
    2277             :     /* Each transaction in a bundle turns into a microblock */
    2278          54 :     if( FD_UNLIKELY( microblock_limit==0UL ) ) {
    2279           0 :       doesnt_fit = 1;
    2280           0 :       FD_MCNT_INC( PACK, MICROBLOCK_PER_BLOCK_LIMIT, 1UL );
    2281           0 :       break;
    2282           0 :     }
    2283          54 :     microblock_limit--;
    2284             : 
    2285          54 :     if( FD_UNLIKELY( cur->txn->payload_sz+MICROBLOCK_DATA_OVERHEAD>byte_limit ) ) {
    2286           0 :       doesnt_fit = 1;
    2287           0 :       FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_BYTE_LIMIT, 1UL );
    2288           0 :       break;
    2289           0 :     }
    2290          54 :     byte_limit -= cur->txn->payload_sz + MICROBLOCK_DATA_OVERHEAD;
    2291             : 
    2292          54 :     if( FD_UNLIKELY( !FD_PACK_BITSET_INTERSECT4_EMPTY( pack->bitset_rw_in_use, pack->bitset_w_in_use, cur->w_bitset, cur->rw_bitset ) ) ) {
    2293           0 :       has_conflict = 1;
    2294           0 :       FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_FAST_PATH,  1UL );
    2295           0 :       break;
    2296           0 :     }
    2297             : 
    2298             :     /* Don't update the actual in-use bitset, because the transactions
    2299             :        in the bundle are allowed to conflict with each other. */
    2300          54 :     FD_PACK_BITSET_OR( bitset_rw_in_use, cur->rw_bitset );
    2301          54 :     FD_PACK_BITSET_OR( bitset_w_in_use,  cur->w_bitset  );
    2302             : 
    2303             : 
    2304          54 :     fd_txn_t const * txn = TXN(cur->txn);
    2305          54 :     fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, cur->txn->payload );
    2306          54 :     fd_acct_addr_t const * alt_adj = cur->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    2307             : 
    2308             :     /* Check conflicts between this transaction's writable accounts and
    2309             :        current readers */
    2310          54 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    2311         306 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2312             : 
    2313         252 :       fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    2314             : 
    2315         252 :       fd_pack_addr_use_t * in_bundle_temp = acct_uses_query( pack->bundle_temp_map, acct, null_use );
    2316         252 :       ulong current_cost                  = acct_uses_query( pack->writer_costs,    acct, null_use )->total_cost;
    2317         252 :       ulong carried_cost                  = (ulong)in_bundle_temp->carried_cost;
    2318         252 :       if( FD_UNLIKELY( current_cost + carried_cost + cur->compute_est > pack->lim->max_write_cost_per_acct ) ) {
    2319           0 :         doesnt_fit = 1;
    2320           0 :         FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_WRITE_COST, 1UL );
    2321           0 :         break;
    2322           0 :       }
    2323             : 
    2324         252 :       if( FD_LIKELY( in_bundle_temp==null_use ) ) { /* Not in temp bundle table yet */
    2325         192 :         in_bundle_temp    = acct_uses_insert( pack->bundle_temp_map, acct );
    2326         192 :         in_bundle_temp->_ = 0UL;
    2327         192 :         bundle_temp_inserted[ bundle_temp_inserted_cnt++ ] = in_bundle_temp;
    2328         192 :       }
    2329         252 :       in_bundle_temp->carried_cost += (uint)cur->compute_est; /* < 2^21, but >0 */
    2330         252 :       in_bundle_temp->ref_cnt++;
    2331         252 :       last_use_in_txn_cnt[ in_bundle_temp->last_use_in ]--;
    2332         252 :       in_bundle_temp->last_use_in = (ushort)(txn_cnt+1UL);
    2333         252 :       last_use_in_txn_cnt[ in_bundle_temp->last_use_in ]++;
    2334             : 
    2335         252 :       if( FD_UNLIKELY( acct_uses_query( pack->acct_in_use, acct, null_use )->in_use_by ) ) {
    2336           0 :         has_conflict = 1;
    2337           0 :         FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_SLOW_PATH,  1UL );
    2338           0 :         break;
    2339           0 :       }
    2340         252 :     }
    2341          54 :     if( has_conflict | doesnt_fit ) break;
    2342             : 
    2343             :     /* Check conflicts between this transaction's readonly accounts and
    2344             :        current writers */
    2345          54 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_READONLY );
    2346         297 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2347             : 
    2348         243 :       fd_acct_addr_t const * acct = ACCT_ITER_TO_PTR( iter );
    2349         243 :       if( fd_pack_unwritable_contains( acct ) ) continue; /* No need to track sysvars because they can't be writable */
    2350             : 
    2351         144 :       fd_pack_addr_use_t * in_bundle_temp = acct_uses_query( pack->bundle_temp_map, *acct, null_use );
    2352         144 :       if( FD_LIKELY( in_bundle_temp==null_use ) ) { /* Not in temp bundle table yet */
    2353          87 :         in_bundle_temp = acct_uses_insert( pack->bundle_temp_map, *acct );
    2354          87 :         in_bundle_temp->_ = 0UL;
    2355          87 :         bundle_temp_inserted[ bundle_temp_inserted_cnt++ ] = in_bundle_temp;
    2356          87 :       }
    2357         144 :       in_bundle_temp->ref_cnt++;
    2358         144 :       last_use_in_txn_cnt[ in_bundle_temp->last_use_in ]--;
    2359         144 :       in_bundle_temp->last_use_in = (ushort)(txn_cnt+1UL);
    2360         144 :       last_use_in_txn_cnt[ in_bundle_temp->last_use_in ]++;
    2361             : 
    2362         144 :       if( FD_UNLIKELY( acct_uses_query( pack->acct_in_use,  *acct, null_use )->in_use_by & FD_PACK_IN_USE_WRITABLE ) ) {
    2363           0 :         has_conflict = 1;
    2364           0 :         FD_MCNT_INC( PACK, TRANSACTION_SCHEDULE_SLOW_PATH,  1UL );
    2365           0 :         break;
    2366           0 :       }
    2367         144 :     }
    2368             : 
    2369          54 :     if( has_conflict | doesnt_fit ) break;
    2370             : 
    2371          54 :     txn_cnt++;
    2372          54 :     _cur = treap_rev_iter_next( _cur, pool );
    2373          54 :   }
    2374          21 :   int retval = fd_int_if( doesnt_fit, TRY_BUNDLE_DOES_NOT_FIT,
    2375          21 :                                       fd_int_if( has_conflict, TRY_BUNDLE_HAS_CONFLICTS, TRY_BUNDLE_SUCCESS( (int)txn_cnt ) ) );
    2376             : 
    2377          21 :   if( FD_UNLIKELY( retval<=0 ) ) {
    2378           0 :     for( ulong i=0UL; i<bundle_temp_inserted_cnt; i++ ) {
    2379           0 :       acct_uses_remove( pack->bundle_temp_map, bundle_temp_inserted[ bundle_temp_inserted_cnt-i-1UL ] );
    2380           0 :     }
    2381           0 :     FD_TEST( acct_uses_key_cnt( pack->bundle_temp_map )==0UL );
    2382           0 :     return retval;
    2383           0 :   }
    2384             : 
    2385             :   /* This bundle passed validation, so now we'll take it! */
    2386          21 :   pack->outstanding_microblock_mask |= bank_tile_mask;
    2387             : 
    2388          21 :   treap_rev_iter_t   _end  = _cur;
    2389          21 :   treap_rev_iter_t   _next;
    2390             : 
    2391             :   /* We'll carefully incrementally construct use_by_bank and
    2392             :      use_by_bank_txn based on the contents of bundle_temp and
    2393             :      last_use_in_txn_cnt. */
    2394          21 :   fd_pack_addr_use_t * use_by_bank     = pack->use_by_bank    [bank_tile];
    2395          21 :   ulong              * use_by_bank_txn = pack->use_by_bank_txn[bank_tile];
    2396          21 :   ulong cum_sum = 0UL;
    2397          75 :   for( ulong k=0UL; k<txn_cnt; k++ ) { use_by_bank_txn[k] = cum_sum; cum_sum += last_use_in_txn_cnt[ k+1UL ]; }
    2398          21 :   pack->use_by_bank_cnt[bank_tile] = cum_sum;
    2399             : 
    2400             : 
    2401          75 :   for( _cur=_txn0; _cur!=_end; _cur=_next ) {
    2402          54 :     _next = treap_rev_iter_next( _cur, pool );
    2403             : 
    2404          54 :     fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pool );
    2405          54 :     fd_txn_t const    * txn = TXN(cur->txn);
    2406          54 :     fd_memcpy( out->payload, cur->txn->payload, cur->txn->payload_sz                                           );
    2407          54 :     fd_memcpy( TXN(out),     txn,               fd_txn_footprint( txn->instr_cnt, txn->addr_table_lookup_cnt ) );
    2408          54 :     out->payload_sz                      = cur->txn->payload_sz;
    2409          54 :     out->pack_cu.requested_exec_plus_acct_data_cus = cur->txn->pack_cu.requested_exec_plus_acct_data_cus;
    2410          54 :     out->pack_cu.non_execution_cus       = cur->txn->pack_cu.non_execution_cus;
    2411          54 :     out->scheduler_arrival_time_nanos    = cur->txn->scheduler_arrival_time_nanos;
    2412          54 :     out->source_tpu                      = cur->txn->source_tpu;
    2413          54 :     out->source_ipv4                     = cur->txn->source_ipv4;
    2414          54 :     out->flags                           = cur->txn->flags;
    2415          54 :     out++;
    2416             : 
    2417          54 :     pack->cumulative_block_cost += cur->compute_est;
    2418          54 :     pack->data_bytes_consumed   += cur->txn->payload_sz + MICROBLOCK_DATA_OVERHEAD;
    2419          54 :     pack->microblock_cnt        += 1UL;
    2420             : 
    2421          54 :     if( FD_UNLIKELY( cur->txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE ) ) noncemap_ele_remove_fast( pack->noncemap, cur, pack->pool );
    2422          54 :     sig2txn_ele_remove_fast( pack->signature_map, cur, pack->pool );
    2423             : 
    2424          54 :     cur->root = FD_ORD_TXN_ROOT_FREE;
    2425          54 :     expq_remove( pack->expiration_q, cur->expq_idx );
    2426          54 :     treap_idx_remove( pack->pending_bundles, _cur, pack->pool );
    2427          54 :     trp_pool_idx_release( pack->pool, _cur );
    2428          54 :     pack->pending_txn_cnt--;
    2429          54 :   }
    2430             : 
    2431             : 
    2432         300 :   for( ulong i=0UL; i<bundle_temp_inserted_cnt; i++ ) {
    2433             :     /* In order to clear bundle_temp_map with the typical trick, we need
    2434             :        to iterate through bundle_temp_inserted backwards. */
    2435         279 :     fd_pack_addr_use_t * addr_use = bundle_temp_inserted[ bundle_temp_inserted_cnt-i-1UL ];
    2436             : 
    2437         279 :     int any_writers = addr_use->carried_cost>0U; /* Did any transaction in this bundle write lock this account address? */
    2438             : 
    2439         279 :     if( FD_LIKELY( any_writers ) ) { /* UNLIKELY? */
    2440         192 :       fd_pack_addr_use_t * in_wcost_table = acct_uses_query( pack->writer_costs, addr_use->key, NULL );
    2441         192 :       if( !in_wcost_table ) {
    2442         177 :         in_wcost_table = acct_uses_insert( pack->writer_costs, addr_use->key );
    2443         177 :         in_wcost_table->total_cost = 0UL;
    2444         177 :         pack->written_list[ pack->written_list_cnt ] = in_wcost_table;
    2445         177 :         pack->written_list_cnt = fd_ulong_min( pack->written_list_cnt+1UL, pack->written_list_max-1UL );
    2446         177 :       }
    2447         192 :       in_wcost_table->total_cost += (ulong)addr_use->carried_cost;
    2448         192 :     }
    2449             : 
    2450             :     /* in_use_by must be set before releasing the bit reference */
    2451         279 :     fd_pack_addr_use_t * use = acct_uses_query( pack->acct_in_use, addr_use->key, NULL );
    2452         279 :     if( !use ) { use = acct_uses_insert( pack->acct_in_use, addr_use->key ); use->in_use_by = 0UL; }
    2453         279 :     use->in_use_by |= bank_tile_mask | fd_ulong_if( any_writers, FD_PACK_IN_USE_WRITABLE, 0UL );
    2454         279 :     use->in_use_by &= ~FD_PACK_IN_USE_BIT_CLEARED;
    2455             : 
    2456         279 :     use_by_bank[ use_by_bank_txn[ addr_use->last_use_in-1UL ]++ ] = *use;
    2457             : 
    2458         675 :     for( ulong k=0UL; k<(ulong)addr_use->ref_cnt; k++ ) {
    2459         396 :       release_result_t ret = release_bit_reference( pack, &(addr_use->key) );
    2460         396 :       FD_PACK_BITSET_CLEARN( bitset_rw_in_use, ret.clear_rw_bit );
    2461         396 :       FD_PACK_BITSET_CLEARN( bitset_w_in_use,  ret.clear_w_bit  );
    2462         396 :     }
    2463             : 
    2464         279 :     acct_uses_remove( pack->bundle_temp_map, addr_use );
    2465         279 :   }
    2466             : 
    2467          21 :   FD_PACK_BITSET_COPY( pack->bitset_rw_in_use, bitset_rw_in_use );
    2468          21 :   FD_PACK_BITSET_COPY( pack->bitset_w_in_use,  bitset_w_in_use  );
    2469             : 
    2470          21 :   if( FD_UNLIKELY( is_ib ) ) {
    2471           9 :     pack->initializer_bundle_state = FD_PACK_IB_STATE_PENDING;
    2472           9 :   }
    2473          21 :   return retval;
    2474          21 : }
    2475             : 
    2476             : 
    2477             : ulong
    2478             : fd_pack_schedule_next_microblock( fd_pack_t *  pack,
    2479             :                                   ulong        total_cus,
    2480             :                                   float        vote_fraction,
    2481             :                                   ulong        bank_tile,
    2482             :                                   int          schedule_flags,
    2483      754235 :                                   fd_txn_p_t * out ) {
    2484             : 
    2485             :   /* TODO: Decide if these are exactly how we want to handle limits */
    2486      754235 :   total_cus = fd_ulong_min( total_cus, pack->lim->max_cost_per_block - pack->cumulative_block_cost );
    2487      754235 :   ulong vote_cus = fd_ulong_min( (ulong)((float)total_cus * vote_fraction),
    2488      754235 :                                  pack->lim->max_vote_cost_per_block - pack->cumulative_vote_cost );
    2489      754235 :   ulong vote_reserved_txns = fd_ulong_min( vote_cus/FD_PACK_SIMPLE_VOTE_COST,
    2490      754235 :                                            (ulong)((float)pack->lim->max_txn_per_microblock * vote_fraction) );
    2491             : 
    2492             : 
    2493      754235 :   if( FD_UNLIKELY( (pack->microblock_cnt>=pack->lim->max_microblocks_per_block) ) ) {
    2494           0 :     FD_MCNT_INC( PACK, MICROBLOCK_PER_BLOCK_LIMIT, 1UL );
    2495           0 :     return 0UL;
    2496           0 :   }
    2497      754235 :   if( FD_UNLIKELY( pack->data_bytes_consumed+MICROBLOCK_DATA_OVERHEAD+FD_TXN_MIN_SERIALIZED_SZ>pack->lim->max_data_bytes_per_block) ) {
    2498           0 :     FD_MCNT_INC( PACK, DATA_PER_BLOCK_LIMIT, 1UL );
    2499           0 :     return 0UL;
    2500           0 :   }
    2501             : 
    2502      754235 :   ulong * use_by_bank_txn = pack->use_by_bank_txn[ bank_tile ];
    2503             : 
    2504      754235 :   ulong cu_limit  = total_cus - vote_cus;
    2505      754235 :   ulong txn_limit = pack->lim->max_txn_per_microblock - vote_reserved_txns;
    2506      754235 :   ulong scheduled = 0UL;
    2507      754235 :   ulong byte_limit = pack->lim->max_data_bytes_per_block - pack->data_bytes_consumed - MICROBLOCK_DATA_OVERHEAD;
    2508             : 
    2509      754235 :   sched_return_t status = {0}, status1 = {0};
    2510             : 
    2511      754235 :   if( FD_LIKELY( schedule_flags & FD_PACK_SCHEDULE_VOTE ) ) {
    2512             :     /* Schedule vote transactions */
    2513      754136 :     status1= fd_pack_schedule_impl( pack, pack->pending_votes, vote_cus, vote_reserved_txns, byte_limit, bank_tile, pack->pending_votes_smallest, use_by_bank_txn, out+scheduled );
    2514             : 
    2515      754136 :     scheduled                   += status1.txns_scheduled;
    2516      754136 :     pack->cumulative_vote_cost  += status1.cus_scheduled;
    2517      754136 :     pack->cumulative_block_cost += status1.cus_scheduled;
    2518      754136 :     pack->data_bytes_consumed   += status1.bytes_scheduled;
    2519      754136 :     byte_limit                  -= status1.bytes_scheduled;
    2520      754136 :     use_by_bank_txn             += status1.txns_scheduled;
    2521             :     /* Add any remaining CUs/txns to the non-vote limits */
    2522      754136 :     txn_limit += vote_reserved_txns - status1.txns_scheduled;
    2523      754136 :     cu_limit  += vote_cus - status1.cus_scheduled;
    2524      754136 :   }
    2525             : 
    2526             :   /* Bundle can't mix with votes, so only try to schedule a bundle if we
    2527             :      didn't get any votes. */
    2528      754235 :   if( FD_UNLIKELY( !!(schedule_flags & FD_PACK_SCHEDULE_BUNDLE) & (status1.txns_scheduled==0UL) ) ) {
    2529      754016 :     int bundle_result = fd_pack_try_schedule_bundle( pack, bank_tile, out );
    2530      754016 :     if( FD_UNLIKELY( bundle_result>0                         ) ) return (ulong)bundle_result;
    2531      753995 :     if( FD_UNLIKELY( bundle_result==TRY_BUNDLE_HAS_CONFLICTS ) ) return 0UL;
    2532             :     /* in the NO_READY_BUNDLES or DOES_NOT_FIT case, we schedule like
    2533             :        normal. */
    2534             :     /* We have the early returns here because try_schedule_bundle does
    2535             :        the bookeeping internally, since the calculations are a bit
    2536             :        different in that case. */
    2537      753995 :   }
    2538             : 
    2539             : 
    2540             :   /* Fill any remaining space with non-vote transactions */
    2541      754214 :   if( FD_LIKELY( schedule_flags & FD_PACK_SCHEDULE_TXN ) ) {
    2542      754214 :     status = fd_pack_schedule_impl( pack, pack->pending,       cu_limit, txn_limit,          byte_limit, bank_tile, pack->pending_smallest,       use_by_bank_txn, out+scheduled );
    2543             : 
    2544      754214 :     scheduled                   += status.txns_scheduled;
    2545      754214 :     pack->cumulative_block_cost += status.cus_scheduled;
    2546      754214 :     pack->data_bytes_consumed   += status.bytes_scheduled;
    2547      754214 :   }
    2548             : 
    2549      754214 :   ulong nonempty = (ulong)(scheduled>0UL);
    2550      754214 :   pack->microblock_cnt              += nonempty;
    2551      754214 :   pack->outstanding_microblock_mask |= nonempty << bank_tile;
    2552      754214 :   pack->data_bytes_consumed         += nonempty * MICROBLOCK_DATA_OVERHEAD;
    2553             : 
    2554             :   /* Update metrics counters */
    2555      754214 :   fd_pack_metrics_write( pack );
    2556      754214 :   FD_MGAUGE_SET( PACK, CUS_CONSUMED_IN_BLOCK,         pack->cumulative_block_cost          );
    2557             : 
    2558      754214 :   fd_histf_sample( pack->txn_per_microblock,  scheduled              );
    2559      754214 :   fd_histf_sample( pack->vote_per_microblock, status1.txns_scheduled );
    2560             : 
    2561      251405 : #if FD_HAS_AVX512 && FD_PACK_USE_NON_TEMPORAL_MEMCPY
    2562      251405 :   _mm_sfence();
    2563      251405 : #endif
    2564             : 
    2565      754214 :   return scheduled;
    2566      754235 : }
    2567             : 
    2568      274530 : ulong fd_pack_bank_tile_cnt     ( fd_pack_t const * pack ) { return pack->bank_tile_cnt;         }
    2569        1368 : ulong fd_pack_current_block_cost( fd_pack_t const * pack ) { return pack->cumulative_block_cost; }
    2570             : 
    2571             : 
    2572             : void
    2573          37 : fd_pack_set_block_limits( fd_pack_t * pack, fd_pack_limits_t const * limits ) {
    2574          37 :   FD_TEST( limits->max_cost_per_block      >= FD_PACK_MAX_COST_PER_BLOCK_LOWER_BOUND      );
    2575          37 :   FD_TEST( limits->max_vote_cost_per_block >= FD_PACK_MAX_VOTE_COST_PER_BLOCK_LOWER_BOUND );
    2576          37 :   FD_TEST( limits->max_write_cost_per_acct >= FD_PACK_MAX_WRITE_COST_PER_ACCT_LOWER_BOUND );
    2577             : 
    2578          37 :   pack->lim->max_microblocks_per_block = limits->max_microblocks_per_block;
    2579          37 :   pack->lim->max_data_bytes_per_block  = limits->max_data_bytes_per_block;
    2580          37 :   pack->lim->max_cost_per_block        = limits->max_cost_per_block;
    2581          37 :   pack->lim->max_vote_cost_per_block   = limits->max_vote_cost_per_block;
    2582          37 :   pack->lim->max_write_cost_per_acct   = limits->max_write_cost_per_acct;
    2583          37 : }
    2584             : 
    2585             : void
    2586             : fd_pack_rebate_cus( fd_pack_t              * pack,
    2587          15 :                     fd_pack_rebate_t const * rebate ) {
    2588          15 :   if( FD_UNLIKELY( (rebate->ib_result!=0) & (pack->initializer_bundle_state==FD_PACK_IB_STATE_PENDING ) ) ) {
    2589           9 :     pack->initializer_bundle_state = fd_int_if( rebate->ib_result==1, FD_PACK_IB_STATE_READY, FD_PACK_IB_STATE_FAILED );
    2590           9 :   }
    2591             : 
    2592          15 :   pack->cumulative_block_cost  -= rebate->total_cost_rebate;
    2593          15 :   pack->cumulative_vote_cost   -= rebate->vote_cost_rebate;
    2594          15 :   pack->data_bytes_consumed    -= rebate->data_bytes_rebate;
    2595          15 :   pack->cumulative_rebated_cus += rebate->total_cost_rebate;
    2596             :   /* For now, we want to ignore the microblock count rebate.  There are
    2597             :      3 places the microblock count is kept (here, in the pack tile, and
    2598             :      in the PoH tile), and they all need to count microblocks that end
    2599             :      up being empty in the same way.  It would be better from a
    2600             :      DoS-resistance perspective for them all not to count empty
    2601             :      microblocks towards the total, but there's a race condition:
    2602             :      suppose pack schedules a microblock containing one transaction that
    2603             :      doesn't land on chain, the slot ends, and then pack informs PoH of
    2604             :      the number of microblocks before the final rebate comes through.
    2605             :      This isn't unsolvable, but it's pretty gross, so it's probably
    2606             :      better to just not apply the rebate for now. */
    2607          15 :   (void)rebate->microblock_cnt_rebate;
    2608             : 
    2609          15 :   fd_pack_addr_use_t * writer_costs = pack->writer_costs;
    2610          27 :   for( ulong i=0UL; i<rebate->writer_cnt; i++ ) {
    2611          12 :     fd_pack_addr_use_t * in_wcost_table = acct_uses_query( writer_costs, rebate->writer_rebates[i].key, NULL );
    2612          12 :     if( FD_UNLIKELY( !in_wcost_table ) ) FD_LOG_ERR(( "Rebate to unknown written account" ));
    2613          12 :     in_wcost_table->total_cost -= rebate->writer_rebates[i].rebate_cus;
    2614             :     /* Important: Even if this is 0, don't delete it from the table so
    2615             :        that the insert order doesn't get messed up. */
    2616          12 :   }
    2617          15 : }
    2618             : 
    2619             : 
    2620             : ulong
    2621             : fd_pack_expire_before( fd_pack_t * pack,
    2622          52 :                        ulong       expire_before ) {
    2623          52 :   expire_before = fd_ulong_max( expire_before, pack->expire_before );
    2624          52 :   ulong deleted_cnt = 0UL;
    2625          52 :   fd_pack_expq_t * prq = pack->expiration_q;
    2626         364 :   while( (expq_cnt( prq )>0UL) & (prq->expires_at<expire_before) ) {
    2627         312 :     fd_pack_ord_txn_t * expired = prq->txn;
    2628             : 
    2629             :     /* fd_pack_delete_transaction also removes it from the heap */
    2630             :     /* All the transactions in the same bundle have the same expiration
    2631             :        time, so this loop will end up deleting them all, even with
    2632             :        delete_full_bundle set to 0. */
    2633         312 :     ulong _delete_cnt = delete_transaction( pack, expired, 0, 1 );
    2634         312 :     deleted_cnt += _delete_cnt;
    2635         312 :     FD_TEST( _delete_cnt );
    2636         312 :   }
    2637             : 
    2638          52 :   pack->expire_before = expire_before;
    2639          52 :   return deleted_cnt;
    2640          52 : }
    2641             : 
    2642             : void
    2643        2657 : fd_pack_end_block( fd_pack_t * pack ) {
    2644             :   /* rounded division */
    2645        2657 :   ulong pct_cus_per_block = (pack->cumulative_block_cost*100UL + (pack->lim->max_cost_per_block>>1))/pack->lim->max_cost_per_block;
    2646        2657 :   fd_histf_sample( pack->pct_cus_per_block,       pct_cus_per_block                                          );
    2647        2657 :   fd_histf_sample( pack->net_cus_per_block,       pack->cumulative_block_cost                                );
    2648        2657 :   fd_histf_sample( pack->rebated_cus_per_block,   pack->cumulative_rebated_cus                               );
    2649        2657 :   fd_histf_sample( pack->scheduled_cus_per_block, pack->cumulative_rebated_cus + pack->cumulative_block_cost );
    2650             : 
    2651        2657 :   pack->microblock_cnt              = 0UL;
    2652        2657 :   pack->data_bytes_consumed         = 0UL;
    2653        2657 :   pack->cumulative_block_cost       = 0UL;
    2654        2657 :   pack->cumulative_vote_cost        = 0UL;
    2655        2657 :   pack->cumulative_rebated_cus      = 0UL;
    2656        2657 :   pack->outstanding_microblock_mask = 0UL;
    2657             : 
    2658        2657 :   pack->initializer_bundle_state = FD_PACK_IB_STATE_NOT_INITIALIZED;
    2659             : 
    2660        2657 :   acct_uses_clear( pack->acct_in_use  );
    2661             : 
    2662        2657 :   if( FD_LIKELY( pack->written_list_cnt<pack->written_list_max-1UL ) ) {
    2663             :     /* The less dangerous way of doing this is to instead record the
    2664             :        keys we inserted and do a query followed by a delete for each
    2665             :        key.  The downside of that is that keys are 32 bytes and a
    2666             :        pointer is only 8 bytes, plus the computational cost for the
    2667             :        query.
    2668             : 
    2669             :        However, if we're careful, we can pull this off.  We require two
    2670             :        things.  First, we started from an empty map and did nothing but
    2671             :        insert and update.  In particular, no deletions.  Second, we have
    2672             :        to be careful to delete in the opposite order that we inserted.
    2673             :        This is essentially like unwinding the inserts we did.  The
    2674             :        common case is that the element after the one we delete will be
    2675             :        empty, so we'll hit that case.  It's possible that there's
    2676             :        another independent probe sequence that will be entirely intact
    2677             :        starting in the element after, but we'll never hit the MAP_MOVE
    2678             :        case. */
    2679      779331 :     for( ulong i=0UL; i<pack->written_list_cnt; i++ ) {
    2680             :       /* Clearing the cost field here is unnecessary (since it gets
    2681             :          cleared on insert), but makes debugging a bit easier. */
    2682      776674 :       pack->written_list[ pack->written_list_cnt - 1UL - i ]->total_cost = 0UL;
    2683      776674 :       acct_uses_remove( pack->writer_costs, pack->written_list[ pack->written_list_cnt - 1UL - i ] );
    2684      776674 :     }
    2685        2657 :   } else {
    2686           0 :     acct_uses_clear( pack->writer_costs );
    2687           0 :   }
    2688        2657 :   pack->written_list_cnt = 0UL;
    2689             : 
    2690             :   /* compressed_slot_number is > FD_PACK_SKIP_CNT, which means +1 is the
    2691             :      max unless it overflows. */
    2692        2657 :   pack->compressed_slot_number = fd_ushort_max( (ushort)(pack->compressed_slot_number+1), (ushort)(FD_PACK_SKIP_CNT+1) );
    2693             : 
    2694        2657 :   FD_PACK_BITSET_CLEAR( pack->bitset_rw_in_use );
    2695        2657 :   FD_PACK_BITSET_CLEAR( pack->bitset_w_in_use  );
    2696             : 
    2697        9256 :   for( ulong i=0UL; i<pack->bank_tile_cnt; i++ ) pack->use_by_bank_cnt[i] = 0UL;
    2698             : 
    2699             :   /* If our stake is low and we don't become leader often, end_block
    2700             :      might get called on the order of O(1/hr), which feels too
    2701             :      infrequent to do anything related to metrics.  However, we only
    2702             :      update the histograms when we are leader, so this is actually a
    2703             :      good place to copy them. */
    2704        2657 :   FD_MHIST_COPY( PACK, TOTAL_TRANSACTIONS_PER_MICROBLOCK_COUNT, pack->txn_per_microblock  );
    2705        2657 :   FD_MHIST_COPY( PACK, VOTES_PER_MICROBLOCK_COUNT,              pack->vote_per_microblock );
    2706             : 
    2707        2657 :   FD_MGAUGE_SET( PACK, CUS_CONSUMED_IN_BLOCK, 0UL                           );
    2708        2657 :   FD_MHIST_COPY( PACK, CUS_SCHEDULED,         pack->scheduled_cus_per_block );
    2709        2657 :   FD_MHIST_COPY( PACK, CUS_REBATED,           pack->rebated_cus_per_block   );
    2710        2657 :   FD_MHIST_COPY( PACK, CUS_NET,               pack->net_cus_per_block       );
    2711        2657 :   FD_MHIST_COPY( PACK, CUS_PCT,               pack->pct_cus_per_block       );
    2712        2657 : }
    2713             : 
    2714             : static void
    2715             : release_tree( treap_t           * treap,
    2716             :               sig2txn_t         * signature_map,
    2717             :               noncemap_t        * noncemap,
    2718           9 :               fd_pack_ord_txn_t * pool ) {
    2719           9 :   treap_fwd_iter_t next;
    2720          18 :   for( treap_fwd_iter_t it=treap_fwd_iter_init( treap, pool ); !treap_fwd_iter_done( it ); it=next ) {
    2721           9 :     next = treap_fwd_iter_next( it, pool );
    2722           9 :     ulong idx = treap_fwd_iter_idx( it );
    2723           9 :     pool[ idx ].root = FD_ORD_TXN_ROOT_FREE;
    2724           9 :     treap_idx_remove       ( treap,         idx, pool );
    2725           9 :     sig2txn_idx_remove_fast( signature_map, idx, pool );
    2726           9 :     trp_pool_idx_release   ( pool,          idx       );
    2727           9 :     if( pool[ idx ].txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE ) {
    2728           9 :       noncemap_idx_remove_fast( noncemap, idx, pool );
    2729           9 :     }
    2730           9 :   }
    2731           9 : }
    2732             : 
    2733             : void
    2734           3 : fd_pack_clear_all( fd_pack_t * pack ) {
    2735           3 :   pack->pending_txn_cnt        = 0UL;
    2736           3 :   pack->microblock_cnt         = 0UL;
    2737           3 :   pack->cumulative_block_cost  = 0UL;
    2738           3 :   pack->cumulative_vote_cost   = 0UL;
    2739           3 :   pack->cumulative_rebated_cus = 0UL;
    2740             : 
    2741           3 :   pack->pending_smallest->cus         = ULONG_MAX;
    2742           3 :   pack->pending_smallest->bytes       = ULONG_MAX;
    2743           3 :   pack->pending_votes_smallest->cus   = ULONG_MAX;
    2744           3 :   pack->pending_votes_smallest->bytes = ULONG_MAX;
    2745             : 
    2746           3 :   release_tree( pack->pending,         pack->signature_map, pack->noncemap, pack->pool );
    2747           3 :   release_tree( pack->pending_votes,   pack->signature_map, pack->noncemap, pack->pool );
    2748           3 :   release_tree( pack->pending_bundles, pack->signature_map, pack->noncemap, pack->pool );
    2749             : 
    2750           3 :   ulong const pool_max = trp_pool_max( pack->pool );
    2751         132 :   for( ulong i=0UL; i<pool_max; i++ ) {
    2752         129 :     if( FD_UNLIKELY( pack->pool[ i ].root!=FD_ORD_TXN_ROOT_FREE ) ) {
    2753           0 :       fd_pack_ord_txn_t * const del = pack->pool + i;
    2754           0 :       fd_txn_t * txn = TXN( del->txn );
    2755           0 :       fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, del->txn->payload );
    2756           0 :       fd_acct_addr_t const * alt_adj = del->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    2757           0 :       fd_acct_addr_t penalty_acct = *ACCT_IDX_TO_PTR( FD_ORD_TXN_ROOT_PENALTY_ACCT_IDX( del->root ) );
    2758           0 :       fd_pack_penalty_treap_t * penalty_treap = penalty_map_query( pack->penalty_treaps, penalty_acct, NULL );
    2759           0 :       FD_TEST( penalty_treap );
    2760           0 :       release_tree( penalty_treap->penalty_treap, pack->signature_map, pack->noncemap, pack->pool );
    2761           0 :     }
    2762         129 :   }
    2763             : 
    2764           3 :   pack->compressed_slot_number = (ushort)(FD_PACK_SKIP_CNT+1);
    2765             : 
    2766           3 :   expq_remove_all( pack->expiration_q );
    2767             : 
    2768           3 :   acct_uses_clear( pack->acct_in_use  );
    2769           3 :   acct_uses_clear( pack->writer_costs );
    2770             : 
    2771           3 :   penalty_map_clear( pack->penalty_treaps );
    2772             : 
    2773           3 :   FD_PACK_BITSET_CLEAR( pack->bitset_rw_in_use );
    2774           3 :   FD_PACK_BITSET_CLEAR( pack->bitset_w_in_use  );
    2775           3 :   bitset_map_clear( pack->acct_to_bitset );
    2776           3 :   pack->bitset_avail[ 0 ] = FD_PACK_BITSET_SLOWPATH;
    2777        1027 :   for( ulong i=0UL; i<FD_PACK_BITSET_MAX; i++ ) pack->bitset_avail[ i+1UL ] = (ushort)i;
    2778           3 :   pack->bitset_avail_cnt = FD_PACK_BITSET_MAX;
    2779             : 
    2780           6 :   for( ulong i=0UL; i<pack->bank_tile_cnt; i++ ) pack->use_by_bank_cnt[i] = 0UL;
    2781           3 : }
    2782             : 
    2783             : 
    2784             : /* If delete_full_bundle is non-zero and the transaction to delete is
    2785             :    part of a bundle, the rest of the bundle it is part of will be
    2786             :    deleted as well.
    2787             :    If move_from_penalty_treap is non-zero and the transaction to delete
    2788             :    is in the pending treap, move the best transaction in any of the
    2789             :    conflicting penalty treaps to the pending treap (if there is one). */
    2790             : static ulong
    2791             : delete_transaction( fd_pack_t         * pack,
    2792             :                     fd_pack_ord_txn_t * containing,
    2793             :                     int                 delete_full_bundle,
    2794      495471 :                     int                 move_from_penalty_treap ) {
    2795             : 
    2796      495471 :   fd_txn_t * txn = TXN( containing->txn );
    2797      495471 :   fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, containing->txn->payload );
    2798      495471 :   fd_acct_addr_t const * alt_adj = containing->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    2799             : 
    2800      495471 :   treap_t * root = NULL;
    2801      495471 :   int root_idx = containing->root;
    2802      495471 :   fd_pack_penalty_treap_t * penalty_treap = NULL;
    2803      495471 :   switch( root_idx & FD_ORD_TXN_ROOT_TAG_MASK ) {
    2804           0 :     case FD_ORD_TXN_ROOT_FREE:           FD_LOG_CRIT(( "Double free detected" ));
    2805      492291 :     case FD_ORD_TXN_ROOT_PENDING:        root = pack->pending;         break;
    2806           0 :     case FD_ORD_TXN_ROOT_PENDING_VOTE:   root = pack->pending_votes;   break;
    2807         519 :     case FD_ORD_TXN_ROOT_PENDING_BUNDLE: root = pack->pending_bundles; break;
    2808        2661 :     case FD_ORD_TXN_ROOT_PENALTY( 0 ): {
    2809        2661 :       fd_acct_addr_t penalty_acct = *ACCT_IDX_TO_PTR( FD_ORD_TXN_ROOT_PENALTY_ACCT_IDX( root_idx ) );
    2810        2661 :       penalty_treap = penalty_map_query( pack->penalty_treaps, penalty_acct, NULL );
    2811        2661 :       FD_TEST( penalty_treap );
    2812        2661 :       root = penalty_treap->penalty_treap;
    2813        2661 :       break;
    2814        2661 :     }
    2815      495471 :   }
    2816             : 
    2817      495471 :   ulong delete_cnt = 0UL;
    2818      495471 :   if( FD_UNLIKELY( delete_full_bundle & (root==pack->pending_bundles) ) ) {
    2819             :     /* When we delete, the structure of the treap may move around, but
    2820             :        pointers to inside the pool will remain valid */
    2821         123 :     fd_pack_ord_txn_t * bundle_ptrs[ FD_PACK_MAX_TXN_PER_BUNDLE-1UL ];
    2822         123 :     fd_pack_ord_txn_t * pool       = pack->pool;
    2823         123 :     ulong               cnt        = 0UL;
    2824         123 :     ulong               bundle_idx = RC_TO_REL_BUNDLE_IDX( containing->rewards, containing->compute_est );
    2825             : 
    2826             :     /* Iterate in both directions from the current transaction */
    2827         123 :     for( treap_fwd_iter_t _cur=treap_fwd_iter_next( (treap_fwd_iter_t)treap_idx_fast( containing, pool ), pool );
    2828         426 :         !treap_fwd_iter_done( _cur ); _cur=treap_fwd_iter_next( _cur, pool ) ) {
    2829         303 :       fd_pack_ord_txn_t * cur = treap_fwd_iter_ele( _cur, pool );
    2830         303 :       if( FD_LIKELY( bundle_idx==RC_TO_REL_BUNDLE_IDX( cur->rewards, cur->compute_est ) ) ) {
    2831         303 :         bundle_ptrs[ cnt++ ] = cur;
    2832         303 :       } else {
    2833           0 :         break;
    2834           0 :       }
    2835         303 :       FD_TEST( cnt<FD_PACK_MAX_TXN_PER_BUNDLE );
    2836         303 :     }
    2837             : 
    2838         123 :     for( treap_rev_iter_t _cur=treap_rev_iter_next( (treap_rev_iter_t)treap_idx_fast( containing, pool ), pool );
    2839         216 :         !treap_rev_iter_done( _cur ); _cur=treap_rev_iter_next( _cur, pool ) ) {
    2840          93 :       fd_pack_ord_txn_t * cur = treap_rev_iter_ele( _cur, pool );
    2841          93 :       if( FD_LIKELY( bundle_idx==RC_TO_REL_BUNDLE_IDX( cur->rewards, cur->compute_est ) ) ) {
    2842          93 :         bundle_ptrs[ cnt++ ] = cur;
    2843          93 :       } else {
    2844           0 :         break;
    2845           0 :       }
    2846          93 :       FD_TEST( cnt<FD_PACK_MAX_TXN_PER_BUNDLE );
    2847          93 :     }
    2848             : 
    2849             :     /* Delete them each, setting delete_full_bundle to 0 to avoid
    2850             :        infinite recursion. */
    2851         519 :     for( ulong k=0UL; k<cnt; k++ ) delete_cnt += delete_transaction( pack, bundle_ptrs[ k ], 0, 0 );
    2852         123 :   }
    2853             : 
    2854             : 
    2855      495471 :   if( FD_UNLIKELY( move_from_penalty_treap & (root==pack->pending) ) ) {
    2856             : 
    2857      492285 :     fd_pack_ord_txn_t       * best         = NULL;
    2858      492285 :     fd_pack_penalty_treap_t * best_penalty = NULL;
    2859             : 
    2860      492285 :     for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    2861      986394 :         iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2862      494109 :       fd_pack_penalty_treap_t * p_trp = penalty_map_query( pack->penalty_treaps, *ACCT_ITER_TO_PTR( iter ), NULL );
    2863      494109 :       if( FD_UNLIKELY( p_trp ) ) {
    2864        1289 :         fd_pack_ord_txn_t * best_in_trp = treap_rev_iter_ele( treap_rev_iter_init( p_trp->penalty_treap, pack->pool ), pack->pool );
    2865        1289 :         if( FD_UNLIKELY( !best || COMPARE_WORSE( best, best_in_trp ) ) ) {
    2866         672 :           best         = best_in_trp;
    2867         672 :           best_penalty = p_trp;
    2868         672 :         }
    2869        1289 :       }
    2870      494109 :     }
    2871             : 
    2872      492285 :     if( FD_LIKELY( best ) ) {
    2873             :       /* move best to the main treap */
    2874         672 :       treap_ele_remove( best_penalty->penalty_treap, best, pack->pool );
    2875         672 :       best->root = FD_ORD_TXN_ROOT_PENDING;
    2876         672 :       treap_ele_insert( pack->pending,               best, pack->pool );
    2877             : 
    2878         672 :       pack->pending_smallest->cus   = fd_ulong_min( pack->pending_smallest->cus,   best->compute_est             );
    2879         672 :       pack->pending_smallest->bytes = fd_ulong_min( pack->pending_smallest->bytes, best->txn_e->txnp->payload_sz );
    2880             : 
    2881         672 :       if( FD_UNLIKELY( !treap_ele_cnt( best_penalty->penalty_treap ) ) ) {
    2882           9 :         treap_delete( treap_leave( best_penalty->penalty_treap ) );
    2883           9 :         penalty_map_remove( pack->penalty_treaps, best_penalty );
    2884           9 :       }
    2885         672 :     }
    2886      492285 :   }
    2887             : 
    2888      495471 :   for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_ALL );
    2889     2004108 :       iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    2890     1508637 :     if( FD_UNLIKELY( fd_pack_unwritable_contains( ACCT_ITER_TO_PTR( iter ) ) ) ) continue;
    2891             : 
    2892     1012098 :     release_result_t ret = release_bit_reference( pack, ACCT_ITER_TO_PTR( iter ) );
    2893     1012098 :     FD_PACK_BITSET_CLEARN( pack->bitset_rw_in_use, ret.clear_rw_bit );
    2894     1012098 :     FD_PACK_BITSET_CLEARN( pack->bitset_w_in_use,  ret.clear_w_bit  );
    2895     1012098 :   }
    2896             : 
    2897      495471 :   if( FD_UNLIKELY( containing->txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE ) ) {
    2898         261 :     noncemap_ele_remove_fast( pack->noncemap, containing, pack->pool );
    2899         261 :   }
    2900      495471 :   expq_remove( pack->expiration_q, containing->expq_idx );
    2901      495471 :   containing->root = FD_ORD_TXN_ROOT_FREE;
    2902      495471 :   treap_ele_remove( root, containing, pack->pool );
    2903      495471 :   sig2txn_ele_remove_fast( pack->signature_map, containing, pack->pool );
    2904      495471 :   trp_pool_ele_release( pack->pool, containing );
    2905             : 
    2906      495471 :   delete_cnt += 1UL;
    2907      495471 :   pack->pending_txn_cnt--;
    2908             : 
    2909      495471 :   if( FD_UNLIKELY( penalty_treap && treap_ele_cnt( root )==0UL ) ) {
    2910           0 :     penalty_map_remove( pack->penalty_treaps, penalty_treap );
    2911           0 :   }
    2912             : 
    2913      495471 :   return delete_cnt;
    2914      495471 : }
    2915             : 
    2916             : ulong
    2917             : fd_pack_delete_transaction( fd_pack_t              * pack,
    2918         180 :                             fd_ed25519_sig_t const * sig0 ) {
    2919         180 :   ulong cnt = 0;
    2920         180 :   ulong next = ULONG_MAX;
    2921         180 :   for( ulong idx = sig2txn_idx_query_const( pack->signature_map, (wrapped_sig_t const *)sig0, ULONG_MAX, pack->pool );
    2922         336 :       idx!=ULONG_MAX; idx=next ) {
    2923             :     /* Iterating while deleting, not just this element, but perhaps the
    2924             :        whole bundle, feels a bit dangerous, but is actually fine because
    2925             :        a bundle can't contain two transactions with the same signature.
    2926             :        That means we know next is not part of the same bundle as idx,
    2927             :        which means that deleting idx will not delete next. */
    2928         156 :     next = sig2txn_idx_next_const( idx, ULONG_MAX, pack->pool );
    2929         156 :     cnt += delete_transaction( pack, pack->pool+idx, 1, 1 );
    2930         156 :   }
    2931             : 
    2932         180 :   return cnt;
    2933         180 : }
    2934             : 
    2935             : 
    2936             : int
    2937             : fd_pack_verify( fd_pack_t * pack,
    2938         438 :                 void      * scratch ) {
    2939             :   /* Invariants:
    2940             :      sig2txn_query has exact same contents as all treaps combined
    2941             :      root matches treap
    2942             :      Keys of acct_to_bitset is exactly union of all accounts in all
    2943             :             transactions in treaps, with ref counted appropriately
    2944             :      bits in bitset_avail is complement of bits allocated in
    2945             :             acct_to_bitset
    2946             :      expires_at consistent between treap, prq
    2947             :      use_by_bank does not contain duplicates
    2948             :      use_by_bank consistent with acct_in_use
    2949             :      elements in pool but not in a treap have root set to free
    2950             :      all penalty treaps have at least one transaction
    2951             :      all elements in penalty treaps are in the one that the root indicates
    2952             :      */
    2953             : 
    2954             :   /* TODO:
    2955             :      bitset_{r}w_in_use = bitset_map_query( everything in acct_in_use that doesn't have FD_PACK_IN_USE_BIT_CLEARED )
    2956             :      bitset_w_in_use & bitset_rw_in_use == bitset_w_in_use
    2957             :      */
    2958      316762 : #define VERIFY_TEST( cond, ... ) do {   \
    2959      316762 :     if( FD_UNLIKELY( !(cond) ) ) {      \
    2960           0 :       FD_LOG_WARNING(( __VA_ARGS__ ));  \
    2961           0 :       return -(__LINE__);               \
    2962           0 :     }                                   \
    2963      316762 :   } while( 0 )
    2964             : 
    2965         438 :   ulong max_acct_in_treap  = pack->pack_depth * FD_TXN_ACCT_ADDR_MAX;
    2966         438 :   int lg_acct_in_trp = fd_ulong_find_msb( fd_ulong_pow2_up( 2UL*max_acct_in_treap  ) );
    2967         438 :   void * _bitset_map_copy = scratch;
    2968         438 :   void * _bitset_map_orig = bitset_map_leave( pack->acct_to_bitset );
    2969         438 :   fd_memcpy( _bitset_map_copy, _bitset_map_orig, bitset_map_footprint( lg_acct_in_trp ) );
    2970             : 
    2971         438 :   fd_pack_bitset_acct_mapping_t * bitset_copy = bitset_map_join( _bitset_map_copy );
    2972             : 
    2973             :   /* Check that each bit is in exactly one place */
    2974         438 :   FD_PACK_BITSET_DECLARE( processed ); FD_PACK_BITSET_CLEAR( processed );
    2975         438 :   FD_PACK_BITSET_DECLARE( bit       ); FD_PACK_BITSET_CLEAR( bit       );
    2976         438 :   FD_PACK_BITSET_DECLARE( full      ); FD_PACK_BITSET_CLEAR( full      );
    2977             : 
    2978         438 :   if( FD_UNLIKELY( pack->bitset_avail[0]!=FD_PACK_BITSET_SLOWPATH ) ) return -1;
    2979      149264 :   for( ulong i=1UL; i<=pack->bitset_avail_cnt; i++ ) {
    2980      148826 :     FD_PACK_BITSET_CLEAR( bit );
    2981      148826 :     FD_PACK_BITSET_SETN( bit, pack->bitset_avail[ i ] );
    2982      148826 :     VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, processed, processed ),
    2983      148826 :         "bit %hu in avail set twice", pack->bitset_avail[ i ] );
    2984      148826 :     FD_PACK_BITSET_OR( processed, bit );
    2985      148826 :   }
    2986             : 
    2987         438 :   ulong total_references = 0UL;
    2988  1589281206 :   for( ulong i=0UL; i<bitset_map_slot_cnt( bitset_copy ); i++ ) {
    2989  1589280768 :     if( !bitset_map_key_inval( bitset_copy[ i ].key ) ) {
    2990        1080 :       VERIFY_TEST( bitset_copy[ i ].ref_cnt>0UL, "account address in table with 0 ref count" );
    2991             : 
    2992        1080 :       total_references += bitset_copy[ i ].ref_cnt;
    2993             : 
    2994        1080 :       FD_PACK_BITSET_CLEAR( bit );
    2995        1080 :       FD_PACK_BITSET_SETN( bit, bitset_copy[ i ].bit );
    2996        1080 :       VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, processed, processed ), "bit %hu used twice", bitset_copy[ i ].bit );
    2997        1080 :       FD_PACK_BITSET_OR( processed, bit );
    2998        1080 :     }
    2999  1589280768 :   }
    3000      149942 :   for( ulong i=0UL; i<FD_PACK_BITSET_MAX; i++ ) {
    3001      149504 :     FD_PACK_BITSET_CLEAR( bit );
    3002      149504 :     FD_PACK_BITSET_SETN( bit, i );
    3003      149504 :     VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, processed, processed ), "bit %lu missing", i );
    3004      149504 :     FD_PACK_BITSET_SETN( full, i );
    3005      149504 :   }
    3006             : 
    3007             : 
    3008         438 :   fd_pack_ord_txn_t  * pool = pack->pool;
    3009         438 :   treap_t * treaps[ 3 ] = { pack->pending, pack->pending_votes, pack->pending_bundles };
    3010         438 :   ulong txn_cnt = 0UL;
    3011             : 
    3012    24834264 :   for( ulong k=0UL; k<3UL+penalty_map_slot_cnt( pack->penalty_treaps ); k++ ) {
    3013    24833826 :     treap_t * treap = NULL;
    3014             : 
    3015    24833826 :     if( k<3UL ) treap = treaps[ k ];
    3016    24832512 :     else if( FD_LIKELY( penalty_map_key_inval( pack->penalty_treaps[ k-3UL ].key ) ) ) continue;
    3017           0 :     else {
    3018           0 :       treap = pack->penalty_treaps[ k-3UL ].penalty_treap;
    3019           0 :       VERIFY_TEST( treap_ele_cnt( treap )>0UL, "empty penalty treap in map" );
    3020           0 :     }
    3021             : 
    3022        1737 :     for( treap_rev_iter_t _cur=treap_rev_iter_init( treap, pool ); !treap_rev_iter_done( _cur );
    3023        1314 :         _cur=treap_rev_iter_next( _cur, pool ) ) {
    3024         423 :       txn_cnt++;
    3025         423 :       fd_pack_ord_txn_t const * cur = treap_rev_iter_ele_const( _cur, pool );
    3026         423 :       fd_txn_t const * txn = TXN(cur->txn);
    3027         423 :       fd_acct_addr_t const * accts   = fd_txn_get_acct_addrs( txn, cur->txn->payload );
    3028         423 :       fd_acct_addr_t const * alt_adj = cur->txn_e->alt_accts - fd_txn_account_cnt( txn, FD_TXN_ACCT_CAT_IMM );
    3029             : 
    3030         423 :       fd_ed25519_sig_t const * sig0 = fd_txn_get_signatures( txn, cur->txn->payload );
    3031             : 
    3032         423 :       fd_pack_ord_txn_t const * in_tbl = sig2txn_ele_query_const( pack->signature_map, (wrapped_sig_t const *)sig0, NULL, pool );
    3033         423 :       VERIFY_TEST( in_tbl, "signature missing from sig2txn" );
    3034             : 
    3035         423 :       VERIFY_TEST( (ulong)(cur->root & FD_ORD_TXN_ROOT_TAG_MASK)==fd_ulong_min( k, 3UL )+1UL, "treap element had bad root" );
    3036         423 :       if( FD_LIKELY( (cur->root & FD_ORD_TXN_ROOT_TAG_MASK)==FD_ORD_TXN_ROOT_PENALTY(0) ) ) {
    3037           0 :         fd_acct_addr_t const * penalty_acct = ACCT_IDX_TO_PTR( FD_ORD_TXN_ROOT_PENALTY_ACCT_IDX( cur->root ) );
    3038           0 :         VERIFY_TEST( !memcmp( penalty_acct, pack->penalty_treaps[ k-3UL ].key.b, 32UL ), "transaction in wrong penalty treap" );
    3039           0 :       }
    3040         423 :       VERIFY_TEST( cur->expires_at>=pack->expire_before, "treap element expired" );
    3041             : 
    3042         423 :       fd_pack_expq_t const * eq = pack->expiration_q + cur->expq_idx;
    3043         423 :       VERIFY_TEST( eq->txn==cur, "expq inconsistent" );
    3044         423 :       VERIFY_TEST( eq->expires_at==cur->expires_at, "expq expires_at inconsistent" );
    3045             : 
    3046         423 :       FD_PACK_BITSET_DECLARE( complement );
    3047         423 :       FD_PACK_BITSET_COPY( complement, full );
    3048         423 :       for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_WRITABLE );
    3049        1413 :           iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    3050         990 :         fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    3051             : 
    3052         990 :         fd_pack_bitset_acct_mapping_t * q = bitset_map_query( bitset_copy, acct, NULL );
    3053         990 :         VERIFY_TEST( q, "account in transaction missing from bitset mapping" );
    3054         990 :         VERIFY_TEST( q->ref_cnt>0UL, "account in transaction ref_cnt already 0" );
    3055         990 :         q->ref_cnt--;
    3056         990 :         total_references--;
    3057             : 
    3058         990 :         FD_PACK_BITSET_CLEAR( bit );
    3059         990 :         FD_PACK_BITSET_SETN( bit, q->bit );
    3060         990 :         if( q->bit<FD_PACK_BITSET_MAX ) {
    3061         597 :           VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, cur->rw_bitset, cur->rw_bitset ), "missing from rw bitset" );
    3062         597 :           VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, cur->w_bitset,  cur->w_bitset  ), "missing from w bitset" );
    3063         597 :         }
    3064         990 :         FD_PACK_BITSET_CLEARN( complement, q->bit );
    3065         990 :       }
    3066         423 :       VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY( complement, complement, cur->w_bitset,  cur->w_bitset ), "extra in w bitset" );
    3067             : 
    3068         423 :       for( fd_txn_acct_iter_t iter=fd_txn_acct_iter_init( txn, FD_TXN_ACCT_CAT_READONLY );
    3069        1836 :           iter!=fd_txn_acct_iter_end(); iter=fd_txn_acct_iter_next( iter ) ) {
    3070             : 
    3071        1413 :         fd_acct_addr_t acct = *ACCT_ITER_TO_PTR( iter );
    3072        1413 :         if( FD_UNLIKELY( fd_pack_unwritable_contains( &acct ) ) ) continue;
    3073         888 :         fd_pack_bitset_acct_mapping_t * q = bitset_map_query( bitset_copy, acct, NULL );
    3074         888 :         VERIFY_TEST( q, "account in transaction missing from bitset mapping" );
    3075         888 :         VERIFY_TEST( q->ref_cnt>0UL, "account in transaction ref_cnt already 0" );
    3076         888 :         q->ref_cnt--;
    3077         888 :         total_references--;
    3078             : 
    3079         888 :         FD_PACK_BITSET_CLEAR( bit );
    3080         888 :         FD_PACK_BITSET_SETN( bit, q->bit );
    3081         888 :         if( q->bit<FD_PACK_BITSET_MAX ) {
    3082         879 :           VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, cur->rw_bitset, cur->rw_bitset ), "missing from rw bitset" );
    3083         879 :         }
    3084         888 :         FD_PACK_BITSET_CLEARN( complement, q->bit );
    3085         888 :       }
    3086         423 :       VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY( complement, complement, cur->rw_bitset,  cur->rw_bitset ), "extra in rw bitset" );
    3087         423 :     }
    3088        1314 :   }
    3089             : 
    3090         438 :   bitset_map_leave( bitset_copy );
    3091         438 :   VERIFY_TEST( txn_cnt==pack->pending_txn_cnt, "txn_cnt" );
    3092             : 
    3093         438 :   VERIFY_TEST( total_references==0UL, "extra references in bitset mapping" );
    3094         438 :   ulong sig2txn_key_cnt = 0UL;
    3095         438 :   for( sig2txn_iter_t iter = sig2txn_iter_init( pack->signature_map, pool );
    3096         861 :       !sig2txn_iter_done( iter, pack->signature_map, pool );
    3097         438 :       iter = sig2txn_iter_next( iter, pack->signature_map, pool ) ) {
    3098         423 :     sig2txn_key_cnt++;
    3099         423 :   }
    3100         438 :   VERIFY_TEST( txn_cnt==sig2txn_key_cnt, "extra signatures in sig2txn" );
    3101         438 :   VERIFY_TEST( !sig2txn_verify( pack->signature_map, trp_pool_max( pool ), pool ), "sig2txn corrupt" );
    3102             : 
    3103             :   /* Count noncemap keys */
    3104         438 :   ulong noncemap_key_cnt = 0UL;
    3105         438 :   for( noncemap_iter_t iter = noncemap_iter_init( pack->noncemap, pool );
    3106         486 :       !noncemap_iter_done( iter, pack->noncemap, pool );
    3107         438 :       iter = noncemap_iter_next( iter, pack->noncemap, pool ) ) {
    3108          48 :     noncemap_key_cnt++;
    3109             :     /* Ensure element is in pool */
    3110          48 :     fd_pack_ord_txn_t const * ord = noncemap_iter_ele_const( iter, pack->noncemap, pool );
    3111          48 :     VERIFY_TEST( ord->txn->flags & FD_TXN_P_FLAGS_DURABLE_NONCE, "invalid entry in noncemap" );
    3112             : 
    3113             :     /* Although pack allows multiple transactions with the same
    3114             :        signature in sig2txn (MAP_MULTI==1), the noncemap checks prevent
    3115             :        multiple nonce transactions with the same signature. */
    3116          48 :     wrapped_sig_t sig = FD_LOAD( wrapped_sig_t, fd_txn_get_signatures( TXN( ord->txn ), ord->txn->payload ) );
    3117          48 :     VERIFY_TEST( ord==sig2txn_ele_query_const( pack->signature_map, &sig, NULL, pool ), "noncemap and sig2txn desynced" );
    3118          48 :   }
    3119         438 :   VERIFY_TEST( txn_cnt>=noncemap_key_cnt, "phantom txns in noncemap" );
    3120         438 :   VERIFY_TEST( !noncemap_verify( pack->noncemap, trp_pool_max( pool ), pool ), "noncemap corrupt" );
    3121             : 
    3122         438 :   ulong slots_found = 0UL;
    3123         438 :   ulong const pool_max = trp_pool_max( pool );
    3124     3890922 :   for( ulong i=0UL; i<pool_max; i++ ) {
    3125     3890484 :     fd_pack_ord_txn_t * ord = pack->pool + i;
    3126     3890484 :     if( ord->root!=FD_ORD_TXN_ROOT_FREE ) slots_found++;
    3127     3890484 :   }
    3128         438 :   VERIFY_TEST( slots_found==txn_cnt, "phantom slots in pool" );
    3129             : 
    3130         438 :   bitset_map_join( _bitset_map_orig );
    3131             : 
    3132         438 :   int lg_uses_tbl_sz = acct_uses_lg_slot_cnt( pack->acct_in_use );
    3133             : 
    3134         438 :   void * _acct_in_use_copy = scratch;
    3135         438 :   void * _acct_in_use_orig = acct_uses_leave( pack->acct_in_use );
    3136         438 :   fd_memcpy( _acct_in_use_copy, _acct_in_use_orig, acct_uses_footprint( lg_uses_tbl_sz ) );
    3137             : 
    3138         438 :   fd_pack_addr_use_t * acct_in_use_copy = acct_uses_join( _acct_in_use_copy );
    3139             : 
    3140         438 :   FD_PACK_BITSET_DECLARE(  w_complement );
    3141         438 :   FD_PACK_BITSET_DECLARE( rw_complement );
    3142         438 :   FD_PACK_BITSET_COPY(  w_complement, full );
    3143         438 :   FD_PACK_BITSET_COPY( rw_complement, full );
    3144             : 
    3145         438 :   FD_PACK_BITSET_DECLARE( rw_bitset );  FD_PACK_BITSET_COPY( rw_bitset, pack->bitset_rw_in_use );
    3146         438 :   FD_PACK_BITSET_DECLARE(  w_bitset );  FD_PACK_BITSET_COPY(  w_bitset, pack->bitset_w_in_use  );
    3147             : 
    3148             : 
    3149         438 :   ulong const EMPTY_MASK = ~(FD_PACK_IN_USE_WRITABLE | FD_PACK_IN_USE_BIT_CLEARED);
    3150             : 
    3151       12255 :   for( ulong bank=0UL; bank<pack->bank_tile_cnt; bank++ ) {
    3152             : 
    3153       11817 :     fd_pack_addr_use_t const * base = pack->use_by_bank[ bank ];
    3154       11817 :     ulong bank_mask = 1UL << bank;
    3155             : 
    3156       12672 :     for( ulong i=0UL; i<pack->use_by_bank_cnt[ bank ]; i++ ) {
    3157         855 :       fd_pack_addr_use_t * use = acct_uses_query( acct_in_use_copy, base[i].key, NULL );
    3158         855 :       VERIFY_TEST( use, "acct in use by bank not in acct_in_use, or in uses_by_bank twice" );
    3159             : 
    3160         855 :       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" );
    3161             : 
    3162         855 :       fd_pack_bitset_acct_mapping_t * q = bitset_map_query( pack->acct_to_bitset, base[i].key, NULL );
    3163             :       /* The normal case is that the acct->bit mapping is preserved
    3164             :          while in use by other transactions in the pending list.  This
    3165             :          might not always happen though.  It's okay for the mapping to
    3166             :          get deleted while the acct is in use, which is noted with
    3167             :          BIT_CLEARED.  If that is set, the mapping may not exist, or it
    3168             :          may have been re-created, perhaps with a different bit. */
    3169         855 :       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" );
    3170           0 :       else if( !(use->in_use_by & FD_PACK_IN_USE_BIT_CLEARED) ) {
    3171           0 :         FD_PACK_BITSET_CLEAR( bit );
    3172           0 :         FD_PACK_BITSET_SETN( bit, q->bit );
    3173           0 :         if( q->bit<FD_PACK_BITSET_MAX ) {
    3174           0 :           VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, rw_bitset, rw_bitset ), "missing from rw bitset" );
    3175           0 :           if( use->in_use_by & FD_PACK_IN_USE_WRITABLE ) {
    3176           0 :             VERIFY_TEST( !FD_PACK_BITSET_INTERSECT4_EMPTY( bit, bit, w_bitset, w_bitset ), "missing from w bitset" );
    3177           0 :             FD_PACK_BITSET_CLEARN( w_complement, q->bit );
    3178           0 :           }
    3179           0 :         }
    3180           0 :         FD_PACK_BITSET_CLEARN( rw_complement, q->bit );
    3181           0 :       }
    3182         855 :       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" );
    3183             : 
    3184         855 :       use->in_use_by &= ~bank_mask;
    3185         855 :       if( !(use->in_use_by & EMPTY_MASK) ) acct_uses_remove( acct_in_use_copy, use );
    3186         855 :     }
    3187       11817 :   }
    3188         438 :   VERIFY_TEST( acct_uses_key_cnt( acct_in_use_copy )==0UL, "stray uses in acct_in_use" );
    3189         438 :   VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY( rw_complement, rw_complement, rw_bitset,  rw_bitset ), "extra in rw bitset" );
    3190         438 :   VERIFY_TEST( FD_PACK_BITSET_INTERSECT4_EMPTY(  w_complement,  w_complement,  w_bitset,   w_bitset ), "extra in w bitset" );
    3191             : 
    3192         438 :   acct_uses_leave( acct_in_use_copy );
    3193             : 
    3194         438 :   acct_uses_join( _acct_in_use_orig );
    3195         438 :   return 0;
    3196         438 : }
    3197             : 
    3198           3 : void * fd_pack_leave ( fd_pack_t * pack ) { FD_COMPILER_MFENCE(); return (void *)pack; }
    3199           3 : void * fd_pack_delete( void      * mem  ) { FD_COMPILER_MFENCE(); return mem;          }

Generated by: LCOV version 1.14