LCOV - code coverage report
Current view: top level - disco/pack - fd_pack.h (source / functions) Hit Total Coverage
Test: cov.lcov Lines: 35 42 83.3 %
Date: 2025-11-13 04:35:47 Functions: 4 272 1.5 %

          Line data    Source code
       1             : #ifndef HEADER_fd_src_disco_pack_fd_pack_h
       2             : #define HEADER_fd_src_disco_pack_fd_pack_h
       3             : 
       4             : /* fd_pack defines methods that prioritizes Solana transactions,
       5             :    selecting a subset (potentially all) and ordering them to attempt to
       6             :    maximize the overall profitability of the validator. */
       7             : 
       8             : #include "../../ballet/fd_ballet_base.h"
       9             : #include "../../ballet/txn/fd_txn.h"
      10             : #include "../shred/fd_shred_batch.h"
      11             : #include "fd_est_tbl.h"
      12             : #include "fd_microblock.h"
      13             : #include "fd_pack_rebate_sum.h"
      14             : 
      15         123 : #define FD_PACK_ALIGN     (128UL)
      16             : 
      17       46824 : #define FD_PACK_MAX_BANK_TILES 62UL
      18             : 
      19    27172641 : #define FD_PACK_FEE_PER_SIGNATURE           (5000UL) /* In lamports */
      20             : 
      21             : /* Each block is limited to 32k parity shreds.  We don't want pack to
      22             :    produce a block with so many transactions we can't shred it, but the
      23             :    correspondence between transactions and parity shreds is somewhat
      24             :    complicated, so we need to use conservative limits. */
      25         126 : #define FD_PACK_MAX_DATA_PER_BLOCK (FD_SHRED_BATCH_BLOCK_DATA_SZ_MAX)
      26             : 
      27             : /* Optionally allow up to 1M shreds per block for benchmarking. */
      28           0 : #define LARGER_MAX_DATA_PER_BLOCK  (32UL*FD_SHRED_BATCH_BLOCK_DATA_SZ_MAX)
      29             : 
      30             : /* Optionally allow a larger limit for benchmarking */
      31           0 : #define LARGER_MAX_COST_PER_BLOCK (18UL*FD_PACK_MAX_COST_PER_BLOCK_LOWER_BOUND)
      32             : 
      33             : /* ---- End consensus-critical constants */
      34             : 
      35    27201372 : #define FD_TXN_P_FLAGS_IS_SIMPLE_VOTE     ( 1U)
      36    13587579 : #define FD_TXN_P_FLAGS_BUNDLE             ( 2U)
      37    13588056 : #define FD_TXN_P_FLAGS_INITIALIZER_BUNDLE ( 4U)
      38         126 : #define FD_TXN_P_FLAGS_SANITIZE_SUCCESS   ( 8U)
      39         276 : #define FD_TXN_P_FLAGS_EXECUTE_SUCCESS    (16U)
      40           0 : #define FD_TXN_P_FLAGS_FEES_ONLY          (32U)
      41    27172641 : #define FD_TXN_P_FLAGS_DURABLE_NONCE      (64U)
      42             : 
      43         171 : #define FD_TXN_P_FLAGS_RESULT_MASK  (0xFF000000U)
      44             : 
      45             : /* A bundle is a sequence of between 1 and FD_PACK_MAX_TXN_PER_BUNDLE
      46             :    transactions (both inclusive) that executes and commits atomically.
      47             :  */
      48       13998 : #define FD_PACK_MAX_TXN_PER_BUNDLE      5UL
      49             : 
      50             : /* The percentage of the transaction fees that are burned */
      51    13586319 : #define FD_PACK_TXN_FEE_BURN_PCT        50UL
      52             : 
      53             : /* The Solana network and Firedancer implementation details impose
      54             :    several limits on what pack can produce.  These limits are grouped in
      55             :    this one struct fd_pack_limits_t, which is just a convenient way to
      56             :    pass them around.  The limits listed below are arithmetic limits.
      57             :    The limits imposed by practical constraints are almost certainly
      58             :    much, much tighter. */
      59             : struct fd_pack_limits {
      60             :   /* max_{cost, vote_cost}_per_block, max_write_cost_per_acct are
      61             :      consensus-critical limits and must be agreed on cluster-wide.  A
      62             :      block that consumes more than max_cost_per_block cost units
      63             :      (closely related to, but not identical to CUs) in total is invalid.
      64             :      Similarly, a block where the sum of the cost of all vote
      65             :      transactions exceeds max_vote_cost_per_block cost units is invalid.
      66             :      Similarly, a block in where the sum of the cost of all transactions
      67             :      that write to a given account exceeds max_write_cost_per_acct is
      68             :      invalid. */
      69             :   ulong max_cost_per_block;          /* in [0, ULONG_MAX) */
      70             :   ulong max_vote_cost_per_block;     /* in [0, max_cost_per_block] */
      71             :   ulong max_write_cost_per_acct;     /* in [0, max_cost_per_block] */
      72             : 
      73             :   /* max_data_bytes_per_block is derived from consensus-critical limits
      74             :      on the number of shreds in a block, but is not directly enforced.
      75             :      Separation of concerns means that it's not a good idea for pack to
      76             :      know exactly how the block will be shredded, but at the same time,
      77             :      we don't want to end up in a situation where we produced a block
      78             :      that had too many shreds, because the shred tile's only recourse
      79             :      would be to kill the block.  To address this, pack limits the size
      80             :      of the data it puts into the block to a limit that we can prove
      81             :      will never cause the shred tile to produce too many shreds.
      82             : 
      83             :      This limit includes transaction and microblock headers for
      84             :      non-empty microblocks that pack produces. */
      85             :   ulong max_data_bytes_per_block;    /* in [0, ULONG_MAX - 183] */
      86             : 
      87             :   /* max_txn_per_microblock and max_microblocks_per_block are
      88             :      Firedancer-imposed implementation limits to bound the amount of
      89             :      memory consumption that pack uses.  Pack will produce microblocks
      90             :      with no more than max_txn_per_microblock transactions.
      91             :      Additionally, once pack produces max_microblocks_per_block
      92             :      non-empty microblocks in a block, all subsequent attempts to
      93             :      schedule a microblock will return an empty microblock until
      94             :      fd_pack_end_block is called. */
      95             :   ulong max_txn_per_microblock;      /* in [0, 16777216] */
      96             :   ulong max_microblocks_per_block;   /* in [0, 1e12) */
      97             : 
      98             : };
      99             : typedef struct fd_pack_limits fd_pack_limits_t;
     100             : 
     101             : /* fd_pack_addr_use_t: Used for three distinct purposes:
     102             :     -  to record that an address is in use and can't be used again until
     103             :          certain microblocks finish execution
     104             :     -  to keep track of the cost of all transactions that write to the
     105             :          specified account.
     106             :     -  to keep track of the write cost for accounts referenced by
     107             :          transactions in a bundle and which transactions use which
     108             :          accounts.
     109             :    Making these separate structs might make it more clear, but then
     110             :    they'd have identical shape and result in several fd_map_dynamic sets
     111             :    of functions with identical code.  It doesn't seem like the compiler
     112             :    is very good at merging code like that, so in order to reduce code
     113             :    bloat, we'll just combine them. */
     114             : struct fd_pack_private_addr_use_record {
     115             :   fd_acct_addr_t key; /* account address */
     116             :   union {
     117             :     ulong          _;
     118             :     ulong          in_use_by;  /* Bitmask indicating which banks */
     119             :     ulong          total_cost; /* In cost units/CUs */
     120             :     struct { uint    carried_cost;   /* In cost units */
     121             :              ushort  ref_cnt;        /* In transactions */
     122             :              ushort  last_use_in; }; /* In transactions */
     123             :   };
     124             : };
     125             : typedef struct fd_pack_private_addr_use_record fd_pack_addr_use_t;
     126             : 
     127             : /* The point of this array it to keep a simple heap of the top 5
     128             :    writable accounts by cus in a given slot. The top writers heap is
     129             :    constructed and available at the end of a leader slot, after all CUs
     130             :    have been rebated. */
     131     1553266 : #define FD_PACK_TOP_WRITERS_CNT (5UL)
     132     3125720 : #define FD_PACK_TOP_WRITERS_SORT_BEFORE(writer1,writer2) ( (memcmp( (writer1).key.b, &(uchar[32]){ 0 }, FD_TXN_ACCT_ADDR_SZ ) && (writer1).total_cost>(writer2).total_cost) || !memcmp( (writer2).key.b, &(uchar[32]){ 0 }, FD_TXN_ACCT_ADDR_SZ ))
     133             : 
     134             : #define SORT_NAME        fd_pack_writer_cost_sort
     135     6232252 : #define SORT_KEY_T       fd_pack_addr_use_t
     136     3125720 : #define SORT_BEFORE(a,b) (FD_PACK_TOP_WRITERS_SORT_BEFORE(a,b))
     137             : #define SORT_FN_ATTR     __attribute__((no_sanitize("address", "undefined"))) /* excessive ASan slowdown */
     138             : #include "../../util/tmpl/fd_sort.c"
     139             : 
     140             : /* fd_pack_limit_usage_t is used to store the actual per-slot resource
     141             :    utilization.  Each utilization field has a corresponding limit field
     142             :    in fd_pack_limits_t which is greater than or equal to the utilization
     143             :    field. */
     144             : struct fd_pack_limits_usage {
     145             :   ulong block_cost;
     146             :   ulong vote_cost;
     147             : 
     148             :   /* Contains the top 5 writers in the block. If there are less than 5
     149             :      writeable accounts, unused slots will have their pubkey zeroed out. */
     150             :   fd_pack_addr_use_t top_writers[ FD_PACK_TOP_WRITERS_CNT ];
     151             :   ulong block_data_bytes;
     152             :   ulong microblocks;
     153             : };
     154             : 
     155             : typedef struct fd_pack_limits_usage fd_pack_limits_usage_t;
     156             : 
     157             : /* fd_pack_smallest: We want to keep track of the smallest transaction
     158             :    in each treap.  That way, if we know the amount of space left in the
     159             :    block is less than the smallest transaction in the heap, we can just
     160             :    skip the heap.  Since transactions can be deleted, etc. maintaining
     161             :    this precisely is hard, but we can maintain a conservative value
     162             :    fairly cheaply.  Since the CU limit or the byte limit can be the one
     163             :    that matters, we keep track of the smallest by both. */
     164             : struct fd_pack_smallest {
     165             :   ulong cus;
     166             :   ulong bytes;
     167             : };
     168             : typedef struct fd_pack_smallest fd_pack_smallest_t;
     169             : 
     170             : /* Forward declare opaque handle */
     171             : struct fd_pack_private;
     172             : typedef struct fd_pack_private fd_pack_t;
     173             : 
     174             : /* fd_pack_{align,footprint} return the required alignment and
     175             :    footprint in bytes for a region of memory to be used as a pack
     176             :    object.
     177             : 
     178             :    pack_depth sets the maximum number of pending transactions that pack
     179             :    stores and may eventually schedule.  pack_depth must be at least 4.
     180             : 
     181             :    If bundle_meta_sz is non-zero, then the bundle-related functions on
     182             :    this pack object can be used, and it can schedule bundles.
     183             :    Additionally, if bundle_meta_sz is non-zero, then a region of size
     184             :    bundle_meta_sz bytes (with no additional alignment) will be reserved
     185             :    for each bundle.
     186             : 
     187             :    Note: if you'd like to use bundles, but don't require metadata for
     188             :    the bundles, simply use a small positive value (e.g. 1), always pass
     189             :    NULL in insert_bundle_fini, and never call fd_pack_peek_bundle_meta.
     190             : 
     191             :    bank_tile_cnt sets the number of bank tiles to which this pack object
     192             :    can schedule transactions.  bank_tile_cnt must be in [1,
     193             :    FD_PACK_MAX_BANK_TILES].
     194             : 
     195             :    limits sets various limits for the blocks and microblocks that pack
     196             :    can produce. */
     197             : 
     198         123 : FD_FN_CONST static inline ulong fd_pack_align       ( void ) { return FD_PACK_ALIGN; }
     199             : 
     200             : FD_FN_PURE ulong
     201             : fd_pack_footprint( ulong                    pack_depth,
     202             :                    ulong                    bundle_meta_sz,
     203             :                    ulong                    bank_tile_cnt,
     204             :                    fd_pack_limits_t const * limits );
     205             : 
     206             : 
     207             : /* fd_pack_new formats a region of memory to be suitable for use as a
     208             :    pack object.  mem is a non-NULL pointer to a region of memory in the
     209             :    local address space with the required alignment and footprint.
     210             :    pack_depth, bundle_meta_sz, bank_tile_cnt, and limits are as above.
     211             :    rng is a local join to a random number generator used to perturb
     212             :    estimates.
     213             : 
     214             :    Returns `mem` (which will be properly formatted as a pack object) on
     215             :    success and NULL on failure.  Logs details on failure.  The caller
     216             :    will not be joined to the pack object when this function returns. */
     217             : void * fd_pack_new( void                   * mem,
     218             :                     ulong                    pack_depth,
     219             :                     ulong                    bundle_meta_sz,
     220             :                     ulong                    bank_tile_cnt,
     221             :                     fd_pack_limits_t const * limits,
     222             :                     fd_rng_t               * rng );
     223             : 
     224             : /* fd_pack_join joins the caller to the pack object.  Every successful
     225             :    join should have a matching leave.  Returns mem. */
     226             : fd_pack_t * fd_pack_join( void * mem );
     227             : 
     228             : 
     229             : /* fd_pack_avail_txn_cnt returns the number of transactions that this
     230             :    pack object has available to schedule but that have not been
     231             :    scheduled yet. pack must be a valid local join.  The return value
     232             :    will be in [0, pack_depth). */
     233             : 
     234             : /* For performance reasons, implement this here.  The offset is STATIC_ASSERTed
     235             :    in fd_pack.c. */
     236       55017 : #define FD_PACK_PENDING_TXN_CNT_OFF 72
     237             : FD_FN_PURE static inline ulong
     238       55017 : fd_pack_avail_txn_cnt( fd_pack_t const * pack ) {
     239       55017 :   return *((ulong const *)((uchar const *)pack + FD_PACK_PENDING_TXN_CNT_OFF));
     240       55017 : }
     241             : 
     242             : /* fd_pack_current_block_cost returns the number of CUs that have been
     243             :    scheduled in the current block, net of any rebates.  It should be
     244             :    between 0 and the specified value of max_cost_per_block, but it can
     245             :    be slightly higher due to temporary cost model nonsense.  Due to
     246             :    rebates, this number may decrease as the block progresses.  pack must
     247             :    be a valid local join. */
     248             : FD_FN_PURE ulong fd_pack_current_block_cost( fd_pack_t const * pack );
     249             : 
     250             : /* fd_pack_bank_tile_cnt: returns the value of bank_tile_cnt provided in
     251             :    pack when the pack object was initialized with fd_pack_new.  pack
     252             :    must be a valid local join.  The result will be in [1,
     253             :    FD_PACK_MAX_BANK_TILES]. */
     254             : FD_FN_PURE ulong fd_pack_bank_tile_cnt( fd_pack_t const * pack );
     255             : 
     256             : /* fd_pack_set_block_limits: Updates the limits provided fd_pack_new to
     257             :    these new values.  Any future microblocks produced by this pack
     258             :    object will not cause a block to have more than
     259             :    limits->max_microblocks_per_block non-empty microblocks or more than
     260             :    limits->max_data_bytes_per_block data bytes (counting microblock
     261             :    headers as before).  future microblocks will also exclude those that
     262             :    cause the total block cost to exceed limits->max_cost_per_block.
     263             :    Similarly those that cause the total vote-only cost to exceed
     264             :    limits->max_vote_cost_per_block. Also, those that cause the total
     265             :    per-account, per block write cost to exceed
     266             :    limits->max_write_cost_per_acct.  Note that
     267             :    limits->max_txn_per_microblock is ignored. Limits are inclusive, as
     268             :    per usual (i.e. a block may have exactly max_microblocks_per_block
     269             :    microblocks, but not more).  pack must be a valid local join.
     270             : 
     271             :    The typical place to call this is immediately after
     272             :    fd_pack_end_block; if this is called after some microblocks have been
     273             :    produced for the current block, and the current block already exceeds
     274             :    the limits, all the remaining microblocks in the block will be empty,
     275             :    but the call is valid. */
     276             : void fd_pack_set_block_limits( fd_pack_t * pack, fd_pack_limits_t const * limits );
     277             : 
     278             : /* fd_pack_get_block_limits: Copies the currently active pack limits
     279             :    into opt_limits, if opt_limits is not NULL.  Copies the current limit
     280             :    utilization in opt_limits_usage, if opt_limits_usage is not NULL.
     281             : 
     282             :    Limit utilization is updated both when each transactions is scheduled
     283             :    and when any used resources are rebated.
     284             : 
     285             :    The opt_limits_usage->top_writers field is ignored. */
     286             : void fd_pack_get_block_limits( fd_pack_t * pack, fd_pack_limits_usage_t * opt_limits_usage, fd_pack_limits_t * opt_limits );
     287             : 
     288             : /* fd_pack_get_top_writers copies the top FD_PACK_TOP_WRITERS_CNT by
     289             :    writer cost writers into top_writers.
     290             : 
     291             :    This should be called at the end of the relevant leader slot right
     292             :    after fd_pack_end_block, otherwise the copied data will be stale. */
     293             : void fd_pack_get_top_writers( fd_pack_t * pack, fd_pack_addr_use_t * top_writers );
     294             : 
     295             : /* Copies the currently smallest pending,
     296             :    non-conflicting, non-vote transaction into opt_pending_smallest iff
     297             :    it is not NULL and the smallest pending vote into opt_vote_smallest
     298             :    iff it is not NULL.  These values are updates any time a new
     299             :    transaction is inserted into the pending treap, or moved from another
     300             :    treap into the pending treap. */
     301             : void fd_pack_get_pending_smallest( fd_pack_t * pack, fd_pack_smallest_t * opt_pending_smallest, fd_pack_smallest_t * opt_votes_smallest );
     302             : 
     303             : /* Return values for fd_pack_insert_txn_fini:  Non-negative values
     304             :    indicate the transaction was accepted and may be returned in a future
     305             :    microblock.  Negative values indicate that the transaction was
     306             :    rejected and will never be returned in a future microblock.
     307             :    Transactions can be rejected through no fault of their own, so it
     308             :    doesn't necessarily imply bad behavior.
     309             : 
     310             :    The non-negative (success) codes are essentially a bitflag of three
     311             :    bits:
     312             :     * (1) whether the transaction met the criteria for a simple vote or
     313             :       not,
     314             :     * (2) whether this transaction replaced a previously accepted, low
     315             :       priority transaction, rather than being accepted in addition to
     316             :       all the previously accepted transactions.
     317             :     * (4) whether this transaction is a durable nonce transaction
     318             : 
     319             :    Since pack maintains a heap with a fixed max size of pack_depth,
     320             :    replacing transaction is necessary whenever the heap is full.
     321             :    Additionally, only one transaction with a given (nonce account, nonce
     322             :    authority, recent blockhash) value is allowed in pack's heap at a
     323             :    time, which means if there's already a lower priority transaction
     324             :    with the same nonce info, then this transaction will replace it.
     325             :    When the heap is full, and a nonce transaction is inserted, these
     326             :    return values don't allow you to disambiguate whether the replaced
     327             :    transaction had the same nonce info or not.
     328             : 
     329             :    Vote and durable nonce transactions are mutually exclusive.
     330             : 
     331             :    The negative (failure) codes are a normal enumeration (not a
     332             :    bitflag).
     333             :     * PRIORITY: pack's heap was full and the transaction's priority was
     334             :       lower than the worst currently accepted transaction.
     335             :     * NONCE_PRIORITY: pack's heap had a transaction with the same
     336             :       durable nonce info that was higher priority.
     337             :     * DUPLICATE: the transaction is a duplicate of a currently accepted
     338             :       transaction.
     339             :     * UNAFFORDABLE: the fee payer could not afford the transaction fee
     340             :       (not yet implemented).
     341             :     * ADDR_LUT: the transaction tried to load an account from an address
     342             :       lookup table, which is not yet supported.
     343             :     * EXPIRED: the transaction was already expired upon insertion based
     344             :       on the provided value of expires_at compared to the last call to
     345             :       fd_pack_expire_before.
     346             :     * TOO_LARGE: the transaction requested too many CUs and would never
     347             :       be scheduled if it had been accepted.
     348             :     * ACCOUNT_CNT: the transaction tried to load more than 64 account
     349             :       addresses.
     350             :     * DUPLICATE_ACCT: the transaction included an account address twice
     351             :       in its list of account addresses to load.
     352             :     * ESTIMATION_FAIL: estimation of the transaction's compute cost and
     353             :       fee failed, typically because the transaction contained a
     354             :       malformed ComputeBudgetProgram instruction.
     355             :     * WRITES_SYSVAR: the transaction attempts to write-lock a sysvar.
     356             :       Write-locking a sysvar can cause heavy contention.  Agave
     357             :       solves this by downgrading these to read locks, but we instead
     358             :       solve it by refusing to pack such transactions.
     359             :     * INVALID_NONCE: the transaction looks like a durable nonce
     360             :       transaction, but the nonce authority did not sign the transaction.
     361             :     * BUNDLE_BLACKLIST: bundles are enabled and the transaction uses an
     362             :       account in the bundle blacklist.
     363             :     * NONCE_CONFLICT: bundle with two transactions that attempt to lock
     364             :       the exact same durable nonce (nonce account, authority, and block
     365             :       hash).
     366             : 
     367             :     NOTE: The corresponding enum in metrics.xml must be kept in sync
     368             :     with any changes to these return values. */
     369             : #define FD_PACK_INSERT_ACCEPT_NONCE_NONVOTE_REPLACE (  6)
     370             : #define FD_PACK_INSERT_ACCEPT_NONCE_NONVOTE_ADD     (  4)
     371             : #define FD_PACK_INSERT_ACCEPT_VOTE_REPLACE          (  3)
     372             : #define FD_PACK_INSERT_ACCEPT_NONVOTE_REPLACE       (  2)
     373             : #define FD_PACK_INSERT_ACCEPT_VOTE_ADD              (  1)
     374             : #define FD_PACK_INSERT_ACCEPT_NONVOTE_ADD           (  0)
     375           0 : #define FD_PACK_INSERT_REJECT_PRIORITY              ( -1)
     376           9 : #define FD_PACK_INSERT_REJECT_NONCE_PRIORITY        ( -2)
     377             : #define FD_PACK_INSERT_REJECT_DUPLICATE             ( -3)
     378           0 : #define FD_PACK_INSERT_REJECT_UNAFFORDABLE          ( -4)
     379             : #define FD_PACK_INSERT_REJECT_ADDR_LUT              ( -5)
     380          12 : #define FD_PACK_INSERT_REJECT_EXPIRED               ( -6)
     381           0 : #define FD_PACK_INSERT_REJECT_TOO_LARGE             ( -7)
     382           3 : #define FD_PACK_INSERT_REJECT_ACCOUNT_CNT           ( -8)
     383           3 : #define FD_PACK_INSERT_REJECT_DUPLICATE_ACCT        ( -9)
     384           3 : #define FD_PACK_INSERT_REJECT_ESTIMATION_FAIL       (-10)
     385          93 : #define FD_PACK_INSERT_REJECT_WRITES_SYSVAR         (-11)
     386           3 : #define FD_PACK_INSERT_REJECT_INVALID_NONCE         (-12)
     387           0 : #define FD_PACK_INSERT_REJECT_BUNDLE_BLACKLIST      (-13)
     388         243 : #define FD_PACK_INSERT_REJECT_NONCE_CONFLICT        (-14)
     389             : 
     390             : /* The FD_PACK_INSERT_{ACCEPT, REJECT}_* values defined above are in the
     391             :    range [-FD_PACK_INSERT_RETVAL_OFF,
     392             :    -FD_PACK_INSERT_RETVAL_OFF+FD_PACK_INSERT_RETVAL_CNT ) */
     393        3192 : #define FD_PACK_INSERT_RETVAL_OFF 14
     394          30 : #define FD_PACK_INSERT_RETVAL_CNT 21
     395             : 
     396             : FD_STATIC_ASSERT( FD_PACK_INSERT_REJECT_NONCE_CONFLICT>=-FD_PACK_INSERT_RETVAL_OFF, pack_retval );
     397             : FD_STATIC_ASSERT( FD_PACK_INSERT_ACCEPT_NONCE_NONVOTE_REPLACE<FD_PACK_INSERT_RETVAL_CNT-FD_PACK_INSERT_RETVAL_OFF, pack_retval );
     398             : 
     399             : /* fd_pack_insert_txn_{init,fini,cancel} execute the process of
     400             :    inserting a new transaction into the pool of available transactions
     401             :    that may be scheduled by the pack object.
     402             : 
     403             :    fd_pack_insert_txn_init returns a piece of memory from the txnmem
     404             :    region where the transaction should be stored.  The lifetime of this
     405             :    memory is managed by fd_pack as explained below.
     406             : 
     407             :    Every call to fd_pack_insert_init must be paired with a call to
     408             :    exactly one of _fini or _cancel.  Calling fd_pack_insert_txn_fini
     409             :    finalizes the transaction insert process and makes the newly-inserted
     410             :    transaction available for scheduling.  Calling
     411             :    fd_pack_insert_txn_cancel aborts the transaction insertion process.
     412             :    The txn pointer passed to _fini or _cancel must come from the most
     413             :    recent call to _init.
     414             : 
     415             :    The caller of these methods should not retain any read or write
     416             :    interest in the transaction after _fini or _cancel have been called.
     417             : 
     418             :    expires_at (for _fini only) bounds the lifetime of the inserted
     419             :    transaction.  No particular unit is prescribed, and it need not be
     420             :    higher than the previous call to txn_fini.  If fd_pack_expire_before
     421             :    has been previously called with a value larger (strictly) than the
     422             :    provided expires_at, the transaction will be rejected with EXPIRED.
     423             :    See fd_pack_expire_before for more details.
     424             : 
     425             :    pack must be a local join of a pack object.  From the caller's
     426             :    perspective, these functions cannot fail, though pack may reject a
     427             :    transaction for a variety of reasons.  fd_pack_insert_txn_fini
     428             :    returns one of the FD_PACK_INSERT_ACCEPT_* or FD_PACK_INSERT_REJECT_*
     429             :    codes explained above.
     430             :  */
     431             : fd_txn_e_t * fd_pack_insert_txn_init  ( fd_pack_t * pack                                                         );
     432             : int          fd_pack_insert_txn_fini  ( fd_pack_t * pack, fd_txn_e_t * txn, ulong expires_at, ulong * delete_cnt );
     433             : void         fd_pack_insert_txn_cancel( fd_pack_t * pack, fd_txn_e_t * txn                                       );
     434             : 
     435             : /* fd_pack_insert_bundle_{init,fini,cancel} are parallel to the
     436             :    similarly named fd_pack_insert_txn functions but can be used to
     437             :    insert a bundle instead of a transaction.
     438             : 
     439             :    fd_pack_insert_bundle_init populates and returns bundle.
     440             :    Specifically, it populates bundle[0], ...  bundle[txn_cnt-1] with
     441             :    pointers to fd_txn_p_t structs that should receive a new transaction.
     442             :    The pointers themselves should not be changed which is what the const
     443             :    indicates, but the contents of the fd_txn_p_t structs must be changed
     444             :    in order for this to be useful.  bundle must be a pointer to the
     445             :    first element of an array of at least txn_cnt pointers.
     446             : 
     447             :    The bundle consists of the transactions in the order they are
     448             :    provided.  I.e. bundle[0] will execute first in the bundle.
     449             : 
     450             :    Like with insert_txn, every call to fd_pack_insert_bundle_init must
     451             :    be paired with a call to exactly one of _fini or _cancel.  Calling
     452             :    fd_pack_insert_bundle_fini finalizes the bundle insertion process and
     453             :    makes the newly-inserted bundle available for scheduling.  Calling
     454             :    fd_pack_insert_bundle_cancel aborts the transaction insertion
     455             :    process.  There can be at most two outstanding bundles, of which one
     456             :    should be an initializer bundle.  The bundle argument passed to _fini
     457             :    or _cancel must be the return value of a call to _init with the same
     458             :    value of txn_cnt.  Additionally, it is okay to interleave calls to
     459             :    the insert_txn family of functions with calls to the insert_bundle
     460             :    family of functions.
     461             : 
     462             :    The caller of these methods should not retain any read or write
     463             :    interest in the fd_txn_p_t structs that the entries of bundle
     464             :    point to after _fini or _cancel have been called.
     465             : 
     466             :    expires_at has the same meaning as above.  Although transactions in
     467             :    the bundle may have different recent blockhashes, all transactions in
     468             :    the bundle have the same expires_at value, since if one expires, the
     469             :    whole bundle becomes invalid.
     470             : 
     471             :    If initializer_bundle is non-zero, this bundle will be inserted at
     472             :    the front of the bundle queue so that it is the next bundle
     473             :    scheduled.  Otherwise, the bundle will be inserted at the back of the
     474             :    bundle queue, and will be scheduled in FIFO order with the rest of
     475             :    the bundles.  If an initializer bundle is already present in pack's
     476             :    pending transactions, that bundle will be deleted.  Additionally, if
     477             :    initializer_bundle is non-zero, the transactions in the bundle will
     478             :    not be checked against the bundle blacklist; otherwise, the check
     479             :    will be performed as normal.  See the section below on initializer
     480             :    bundles for more details.
     481             : 
     482             :    Other than the blacklist check, transactions in a bundle are subject
     483             :    to the same checks as other transactions.  If any transaction in the
     484             :    bundle fails validation, the whole bundle will be rejected.
     485             : 
     486             :    _fini also accepts bundle_meta, an optional opaque pointer to a
     487             :    region of memory of size bundle_meta_sz (as provided in pack_new).
     488             :    If bundle_meta is non-NULL, the contents of the memory will be copied
     489             :    to a metadata region associated with this bundle and can be retrieved
     490             :    later with fd_pack_peek_bundle_meta.  The contents of bundle_meta is
     491             :    not retrievable if initializer_bundle is non-zero, so you may wish to
     492             :    just pass NULL in that case.  This function does not retain any
     493             :    interest in the contents of bundle_meta after it returns.
     494             : 
     495             :    txn_cnt must be in [1, MAX_TXN_PER_BUNDLE].  A txn_cnt of 1 inserts a
     496             :    single-transaction bundle which is transaction with extremely high
     497             :    priority.  That said, inserting transactions as bundles instead of
     498             :    transactions can hurt performance and throughput by introducing
     499             :    unnecessary stalls.
     500             : 
     501             :    fd_pack_insert_bundle_fini returns one of the FD_PACK_INSERT_ACCEPT_*
     502             :    or FD_PACK_INSERT_REJECT_* codes explained above.  If there are
     503             :    multiple reasons for rejecting a bundle, the which of the reasons it
     504             :    returns is unspecified.  delete_cnt is the number of existing
     505             :    transactions that were deleted as a side effect of insertion.
     506             : 
     507             :    These functions must not be called if the pack object was initialized
     508             :    with bundle_meta_sz==0. */
     509             : 
     510             : fd_txn_e_t * const * fd_pack_insert_bundle_init  ( fd_pack_t * pack, fd_txn_e_t *       * bundle, ulong txn_cnt                                        );
     511             : int                  fd_pack_insert_bundle_fini  ( fd_pack_t * pack, fd_txn_e_t * const * bundle, ulong txn_cnt,
     512             :                                                    ulong expires_at, int initializer_bundle, void const * bundle_meta, ulong * delete_cnt );
     513             : void                 fd_pack_insert_bundle_cancel( fd_pack_t * pack, fd_txn_e_t * const * bundle, ulong txn_cnt                                        );
     514             : 
     515             : 
     516             : /* =========== More details about initializer bundles ===============
     517             :    Initializer bundles are a special type of bundle with special support
     518             :    from the pack object to facilitate preparing on-chain state for the
     519             :    execution of bundles by this validator.  This design is a bit
     520             :    complicated, but it eliminates excessive coupling between pack and
     521             :    block engine details.
     522             : 
     523             :    The pack object maintains a small state machine (initializer bundle
     524             :    abbreviated IB):
     525             : 
     526             :       [Not Initialized]  ------------------------->|
     527             :           ^                                        | Schedule an
     528             :           |     End            Rebate shows        | IB
     529             :           |     block          IB failed           |
     530             :           |<----------[Failed]--------------|      v
     531             :           |                               --===[Pending]
     532             :           |<------------------------------/     ^  |
     533             :           |     End block                   /---|  |
     534             :           |                                 |      | Rebate shows
     535             :           |                        Schedule |      | IB succeeded
     536             :           |                      another IB |      |
     537             :           |     End block                   |      V
     538             :           -----------------------------------===[Ready]
     539             : 
     540             : 
     541             :    When attempting to schedule a bundle the pack object checks the
     542             :    state, and employs the following rules:
     543             :    * [Not Initialized]: If the top bundle is an IB, schedule it,
     544             :      removing it like normal, then transition to [Pending].  Otherwise,
     545             :      do not schedule a bundle.
     546             :    * [Pending]: Do not schedule a bundle.
     547             :    * [Failed]: Do not schedule a bundle
     548             :    * [Ready]: Attempt to schedule the next bundle.  If scheduling an IB,
     549             :      transition to [Pending].
     550             : 
     551             :    As described in the state machine, ending the block (via
     552             :    fd_pack_end_block) transitions to [Not Initialized], and calls to
     553             :    fd_pack_rebate_cus control the transition out of [Pending].
     554             : 
     555             :    This design supports a typical block engine system where some state
     556             :    may need to be initialized at the start of the slot and some state
     557             :    may need to change between runs of transactions (e.g. 5 transactions
     558             :    from block builder A followed by 5 transactions from block builder
     559             :    B).  This can be done by inserting an initializer bundle whenever the
     560             :    top non-initializer bundle's metadata state (retrievable with
     561             :    fd_pack_peek_bundle_meta) doesn't match the current on-chain state.
     562             :    Since the initializer bundle will execute before the bundle that was
     563             :    previously the top one, by the time the non-initializer bundle
     564             :    executes, the on-chain state will be correctly configured.  In this
     565             :    scheme, in the rare case that an initializer bundle was inserted but
     566             :    never executed, it should be deleted at the end of the slot.
     567             : 
     568             :    If at the start of the slot, it is determined that the on-chain state
     569             :    is in good shape, the state machine can transition directly to
     570             :    [Ready] by calling fd_pack_set_initializer_bundles_ready.
     571             : 
     572             :    Initializer bundles are not exempt from expiration, but it should not
     573             :    be a problem if they are always inserted with the most recent
     574             :    blockhash and deleted at the end of the slot.
     575             : 
     576             :    Additionally, a bundle marked as an IB is exempted from the bundle
     577             :    account blacklist checks.  For this reason, it's important that IB be
     578             :    generated by trusted code with minimal or sanitized
     579             :    attacker-controlled input. */
     580             : 
     581             : 
     582             : /* fd_pack_peek_bundle_meta returns a constant pointer to the bundle
     583             :    metadata associated with the bundle currently in line to be scheduled
     584             :    next, or NULL in any of the following cases:
     585             :      * There are no bundles
     586             :      * The bundle currently in line to be scheduled next is an IB
     587             :      * The bundle state is currently [Pending] or [Failed].
     588             : 
     589             :    The lifetime of the returned pointer is until the next pack insert,
     590             :    schedule, delete, or expire call.  The size of the region pointed to
     591             :    by the returned pointer is bundle_meta_sz.  If this bundle was
     592             :    inserted with bundle_meta==NULL, then the contents of the region
     593             :    pointed to by the returned pointer are arbitrary, but it will be safe
     594             :    to read.
     595             : 
     596             :    Pack doesn't do anything special to ensure the returned pointer
     597             :    points to memory with any particular alignment.  It will naturally
     598             :    have an alignment of at least GCD( 64, bundle_meta_sz ). */
     599             : void const * fd_pack_peek_bundle_meta( fd_pack_t const * pack );
     600             : 
     601             : /* fd_pack_set_initializer_bundles_ready sets the IB state machine state
     602             :    (see long initializer bundle comment above) to the [Ready] state.
     603             :    This function makes it easy to use bundles without initializer
     604             :    bundles.  pack must be a valid local join. */
     605             : void fd_pack_set_initializer_bundles_ready( fd_pack_t * pack );
     606             : 
     607             : 
     608             : /* FD_PACK_SCHEDULE_{VOTE,BUNDLE,TXN} form a set of bitflags used in
     609             :    fd_pack_schedule_next_microblock below.  They control what types of
     610             :    scheduling are allowed.  The names should be self-explanatory. */
     611      493110 : #define FD_PACK_SCHEDULE_VOTE   1
     612      493209 : #define FD_PACK_SCHEDULE_BUNDLE 2
     613      493206 : #define FD_PACK_SCHEDULE_TXN    4
     614             : 
     615             : /* fd_pack_schedule_next_microblock schedules pending transactions.
     616             :    These transaction either form a microblock, which is a set of
     617             :    non-conflicting transactions, or a bundle.  The semantics of this
     618             :    function are a bit different depending on which one it picks, but
     619             :    there are some reasons why they both use this function.
     620             : 
     621             :    For both codepaths, pack must be a local join of a pack object.
     622             :    schedule_flags must be a bitwise combination of the
     623             :    FD_PACK_SCHEDULE_* values defined above.  When the bit is set
     624             :    corresponding to a transaction type, this function will consider
     625             :    scheduling transactions of that type.  Passing 0 for schedule_flags
     626             :    is a no-op.  The full policy is as follows:
     627             :     1. If the VOTE bit is set, attempt to schedule votes.  This is the
     628             :        microblock case.
     629             :     2. If the BUNDLE bit is set, and step 1 did not schedule any votes,
     630             :        attempt to schedule bundles.  This is the bundle case.
     631             :     3. If the TXN bit is set, and step 2 did not schedule any bundles
     632             :        for a reason other than account conflicts, attempt to schedule
     633             :        normal transactions.  This is the microblock case.
     634             :    Note that it is possible to schedule a microblock containing both
     635             :    votes and normal transactions, but bundles cannot be combined with
     636             :    either other type.  Additionally, if the BUNDLE bit is not set, step
     637             :    2 will not schedule any bundles for that reason, which is a reason
     638             :    other than account conflicts, so that clause will always be
     639             :    satisfied.
     640             : 
     641             :    Microblock case:
     642             :    Transactions part of the scheduled microblock are copied to out in no
     643             :    particular order.  The cumulative cost of these transactions will not
     644             :    exceed total_cus, and the number of transactions will not exceed the
     645             :    value of max_txn_per_microblock given in fd_pack_new.
     646             : 
     647             :    The block will not contain more than
     648             :    vote_fraction*max_txn_per_microblock votes, and votes in total will
     649             :    not consume more than vote_fraction*total_cus of the microblock.
     650             : 
     651             :    Bundle case:
     652             :    Transactions part of the scheduled bundled are copied in execution
     653             :    order (i.e. out[0] must be executed first).  The number of
     654             :    transactions will not exceed FD_PACK_MAX_TXN_PER_BUNDLE.
     655             :    max_txn_per_microblock, total_cus, and vote_fraction are ignored,
     656             :    though the block-level limits are respected.
     657             : 
     658             :    Both cases:
     659             :    The non_execution_cus and requested_exec_plus_acct_data_cus fields of
     660             :    each transaction will be populated with the non execution CUs and
     661             :    requested execution CUs (including cus derived from the requested
     662             :    loaded accounts data size), respectively.  The sum of these two
     663             :    values is the total cost of the transaction, i.e. what is used for
     664             :    all limits, including the total_cus value.  The lower 3 bits of the
     665             :    flags field will be populated (simple vote, bundle, initializer
     666             :    bundle). Inspecting these flags is the proper way to tell which
     667             :    codepath executed.
     668             : 
     669             :    Returns the number of transactions in the scheduled microblock or
     670             :    bundle.  The return value may be 0 if there are no eligible
     671             :    transactions at the moment. */
     672             : 
     673             : ulong
     674             : fd_pack_schedule_next_microblock( fd_pack_t  * pack,
     675             :                                   ulong        total_cus,
     676             :                                   float        vote_fraction,
     677             :                                   ulong        bank_tile,
     678             :                                   int          schedule_flags,
     679             :                                   fd_txn_p_t * out );
     680             : 
     681             : 
     682             : /* fd_pack_rebate_cus adjusts the compute unit accounting for the
     683             :    specified transactions to take into account the actual consumed CUs
     684             :    after execution.  When a transaction is scheduled by
     685             :    schedule_next_microblock, pack assumes that it uses all the CUs it
     686             :    requests for the purposes of several CU limits.  If it doesn't use
     687             :    all the requested CUs, this function "rebates" them to pack so that
     688             :    they can be consumed by a different transaction in the block.
     689             : 
     690             :    pack must be a valid local join of a pack object.  rebate must point
     691             :    to a valid rebate report produced by fd_pack_rebate_sum_t.
     692             : 
     693             :    IMPORTANT: CU limits are reset at the end of each block, so this
     694             :    should not be called for transactions from a prior block.
     695             :    Specifically, there must not be a call to fd_pack_end_block between
     696             :    the call to schedule_next_microblock this is paired with and the call
     697             :    to rebate_cus.
     698             : 
     699             :    This function operates independently of microblock_complete.  In
     700             :    general, you probably need to call both.  microblock_complete must be
     701             :    called before scheduling another microblock to that bank tile, while
     702             :    rebate_cus is optional and has much more relaxed ordering
     703             :    constraints.  The restriction about intervening calls to end_block
     704             :    and that this must come after schedule_next_microblock are the only
     705             :    ordering constraints. */
     706             : void fd_pack_rebate_cus( fd_pack_t * pack, fd_pack_rebate_t const * rebate );
     707             : 
     708             : /* fd_pack_microblock_complete signals that the bank_tile with index
     709             :    bank_tile has completed its previously scheduled microblock.  This
     710             :    permits the scheduling of transactions that conflict with the
     711             :    previously scheduled microblock.  It is safe to call this multiple
     712             :    times after a microblock or even if bank_tile does not have a
     713             :    previously scheduled; in this case, the function will return 0 and
     714             :    act as a no-op.  Returns 1 if the bank_tile had an outstanding,
     715             :    previously scheduled microblock to mark as completed. */
     716             : int fd_pack_microblock_complete( fd_pack_t * pack, ulong bank_tile );
     717             : 
     718             : /* fd_pack_expire_before deletes all available transactions with
     719             :    expires_at values strictly less than expire_before.  pack must be a
     720             :    local join of a pack object.  Returns the number of transactions
     721             :    deleted.  Subsequent calls to fd_pack_expire_before with the same or
     722             :    a smaller value are no-ops. */
     723             : ulong fd_pack_expire_before( fd_pack_t * pack, ulong expire_before );
     724             : 
     725             : /* fd_pack_delete_txn removes a transaction (identified by its first
     726             :    signature) from the pool of available transactions.  Returns a
     727             :    nonzero count of the number of transactions deleted, if the
     728             :    transaction was found (and then removed) and 0 if not.  The count
     729             :    might be >1 if a bundle was caused to be deleted. */
     730             : ulong fd_pack_delete_transaction( fd_pack_t * pack, fd_ed25519_sig_t const * sig0 );
     731             : 
     732             : /* fd_pack_end_block resets some state to prepare for the next block.
     733             :    Specifically, the per-block limits are cleared and transactions in
     734             :    the microblocks scheduled after the call to this function are allowed
     735             :    to conflict with transactions in microblocks scheduled before the
     736             :    call to this function, even within gap microblocks. */
     737             : void fd_pack_end_block( fd_pack_t * pack );
     738             : 
     739             : 
     740             : /* fd_pack_clear_all resets the state associated with this pack object.
     741             :    All pending transactions are removed from the pool of available
     742             :    transactions and all limits are reset. */
     743             : void fd_pack_clear_all( fd_pack_t * pack );
     744             : 
     745             : 
     746             : /* fd_pack_metrics_write writes period metric values to the metrics
     747             :    system.  pack must be a valid local join. */
     748             : void
     749             : fd_pack_metrics_write( fd_pack_t const * pack );
     750             : 
     751             : 
     752             : /* fd_pack_leave leaves a local join of a pack object.  Returns pack. */
     753             : void * fd_pack_leave(  fd_pack_t * pack );
     754             : /* fd_pack_delete unformats a memory region used to store a pack object
     755             :    and returns ownership of the memory to the caller.  Returns mem. */
     756             : void * fd_pack_delete( void      * mem  );
     757             : 
     758             : /* fd_pack_verify (for debugging use primarily) checks to ensure several
     759             :    invariants are satisfied.  scratch must point to the first byte of a
     760             :    piece of memory meeting the same alignment and footprint constraints
     761             :    as pack.  Returns 0 on success and a negative value on failure
     762             :    (logging a warning with details). */
     763             : int fd_pack_verify( fd_pack_t * pack, void * scratch );
     764             : 
     765             : FD_PROTOTYPES_END
     766             : 
     767             : #endif /* HEADER_fd_src_disco_pack_fd_pack_h */

Generated by: LCOV version 1.14