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