Line data Source code
1 : #define _GNU_SOURCE
2 :
3 : /* Let's say there was a computer, the "leader" computer, that acted as
4 : a bank. Users could send it messages saying they wanted to deposit
5 : money, or transfer it to someone else.
6 :
7 : That's how, for example, Bank of America works but there are problems
8 : with it. One simple problem is: the bank can set your balance to
9 : zero if they don't like you.
10 :
11 : You could try to fix this by having the bank periodically publish the
12 : list of all account balances and transactions. If the customers add
13 : unforgeable signatures to their deposit slips and transfers, then
14 : the bank cannot zero a balance without it being obvious to everyone.
15 :
16 : There's still problems. The bank can't lie about your balance now or
17 : take your money, but it can just not accept deposits on your behalf
18 : by ignoring you.
19 :
20 : You could fix this by getting a few independent banks together, lets
21 : say Bank of America, Bank of England, and Westpac, and having them
22 : rotate who operates the leader computer periodically. If one bank
23 : ignores your deposits, you can just wait and send them to the next
24 : one.
25 :
26 : This is Solana.
27 :
28 : There's still problems of course but they are largely technical. How
29 : do the banks agree who is leader? How do you recover if a leader
30 : misbehaves? How do customers verify the transactions aren't forged?
31 : How do banks receive and publish and verify each others work quickly?
32 : These are the main technical innovations that enable Solana to work
33 : well.
34 :
35 : What about Proof of History?
36 :
37 : One particular niche problem is about the leader schedule. When the
38 : leader computer is moving from one bank to another, the new bank must
39 : wait for the old bank to say it's done and provide a final list of
40 : balances that it can start working off of. But: what if the computer
41 : at the old bank crashes and never says its done?
42 :
43 : Does the new leader just take over at some point? What if the new
44 : leader is malicious, and says the past thousand leaders crashed, and
45 : there have been no transactions for days? How do you check?
46 :
47 : This is what Proof of History solves. Each bank in the network must
48 : constantly do a lot of busywork (compute hashes), even when it is not
49 : leader.
50 :
51 : If the prior thousand leaders crashed, and no transactions happened
52 : in an hour, the new leader would have to show they did about an hour
53 : of busywork for everyone else to believe them.
54 :
55 : A better name for this is proof of skipping. If a leader is skipping
56 : slots (building off of a slot that is not the direct parent), it must
57 : prove that it waited a good amount of time to do so.
58 :
59 : It's not a perfect solution. For one thing, some banks have really
60 : fast computers and can compute a lot of busywork in a short amount of
61 : time, allowing them to skip prior slot(s) anyway. But: there is a
62 : social component that prevents validators from skipping the prior
63 : leader slot. It is easy to detect when this happens and the network
64 : could respond by ignoring their votes or stake.
65 :
66 : You could come up with other schemes: for example, the network could
67 : just use wall clock time. If a new leader publishes a block without
68 : waiting 400 milliseconds for the prior slot to complete, then there
69 : is no "proof of skipping" and the nodes ignore the slot.
70 :
71 : These schemes have a problem in that they are not deterministic
72 : across the network (different computers have different clocks), and
73 : so they will cause frequent forks which are very expensive to
74 : resolve. Even though the proof of history scheme is not perfect,
75 : it is better than any alternative which is not deterministic.
76 :
77 : With all that background, we can now describe at a high level what
78 : this PoH tile actually does,
79 :
80 : (1) Whenever any other leader in the network finishes a slot, and
81 : the slot is determined to be the best one to build off of, this
82 : tile gets "reset" onto that block, the so called "reset slot".
83 :
84 : (2) The tile is constantly doing busy work, hash(hash(hash(...))) on
85 : top of the last reset slot, even when it is not leader.
86 :
87 : (3) When the tile becomes leader, it continues hashing from where it
88 : was. Typically, the prior leader finishes their slot, so the
89 : reset slot will be the parent one, and this tile only publishes
90 : hashes for its own slot. But if prior slots were skipped, then
91 : there might be a whole chain already waiting.
92 :
93 : That's pretty much it. When we are leader, in addition to doing
94 : busywork, we publish ticks and microblocks to the shred tile. A
95 : microblock is a non-empty group of transactions whose hashes are
96 : mixed-in to the chain, while a tick is a periodic stamp of the
97 : current hash, with no transactions (nothing mixed in). We need
98 : to send both to the shred tile, as ticks are important for other
99 : validators to verify in parallel.
100 :
101 : As well, the tile should never become leader for a slot that it has
102 : published anything for, otherwise it may create a duplicate block.
103 :
104 : Some particularly common misunderstandings:
105 :
106 : - PoH is critical to security.
107 :
108 : This largely isn't true. The target hash rate of the network is
109 : so slow (1 hash per 500 nanoseconds) that a malicious leader can
110 : easily catch up if they start from an old hash, and the only
111 : practical attack prevented is the proof of skipping. Most of the
112 : long range attacks in the Solana whitepaper are not relevant.
113 :
114 : - PoH keeps passage of time.
115 :
116 : This is also not true. The way the network keeps time so it can
117 : decide who is leader is that, each leader uses their operating
118 : system clock to time 400 milliseconds and publishes their block
119 : when this timer expires.
120 :
121 : If a leader just hashed as fast as they could, they could publish
122 : a block in tens of milliseconds, and the rest of the network
123 : would happily accept it. This is why the Solana "clock" as
124 : determined by PoH is not accurate and drifts over time.
125 :
126 : - PoH prevents transaction reordering by the leader.
127 :
128 : The leader can, in theory, wait until the very end of their
129 : leader slot to publish anything at all to the network. They can,
130 : in particular, hold all received transactions for 400
131 : milliseconds and then reorder and publish some right at the end
132 : to advantage certain transactions.
133 :
134 : You might be wondering... if all the PoH chain is helping us do is
135 : prove that slots were skipped correctly, why do we need to "mix in"
136 : transactions to the hash value? Or do anything at all for slots
137 : where we don't skip the prior slot?
138 :
139 : It's a good question, and the answer is that this behavior is not
140 : necessary. An ideal implementation of PoH have no concept of ticks
141 : or mixins, and would not be part of the TPU pipeline at all.
142 : Instead, there would be a simple field "skip_proof" on the last
143 : shred we send for a slot, the hash(hash(...)) value. This field
144 : would only be filled in (and only verified by replayers) in cases
145 : where the slot actually skipped a parent.
146 :
147 : Then what is the "clock? In Solana, time is constructed as follows:
148 :
149 : HASHES
150 :
151 : The base unit of time is a hash. Hereafter, any values whose
152 : units are in hashes are called a "hashcnt" to distinguish them
153 : from actual hashed values.
154 :
155 : Agave generally defines a constant duration for each tick
156 : (see below) and then varies the number of hashcnt per tick, but
157 : as we consider the hashcnt the base unit of time, Firedancer and
158 : this PoH implementation defines everything in terms of hashcnt
159 : duration instead.
160 :
161 : In mainnet-beta, testnet, and devnet the hashcnt ticks over
162 : (increments) every 100 nanoseconds. The hashcnt rate is
163 : specified as 500 nanoseconds according to the genesis, but there
164 : are several features which increase the number of hashes per
165 : tick while keeping tick duration constant, which make the time
166 : per hashcnt lower. These features up to and including the
167 : `update_hashes_per_tick6` feature are activated on mainnet-beta,
168 : devnet, and testnet, and are described in the TICKS section
169 : below.
170 :
171 : Other chains and development environments might have a different
172 : hashcnt rate in the genesis, or they might not have activated
173 : the features which increase the rate yet, which we also support.
174 :
175 : In practice, although each validator follows a hashcnt rate of
176 : 100 nanoseconds, the overall observed hashcnt rate of the
177 : network is a little slower than once every 100 nanoseconds,
178 : mostly because there are gaps and clock synchronization issues
179 : during handoff between leaders. This is referred to as clock
180 : drift.
181 :
182 : TICKS
183 :
184 : The leader needs to periodically checkpoint the hash value
185 : associated with a given hashcnt so that they can publish it to
186 : other nodes for verification.
187 :
188 : On mainnet-beta, testnet, and devnet this occurs once every
189 : 62,500 hashcnts, or approximately once every 6.4 microseconds.
190 : This value is determined at genesis time, and according to the
191 : features below, and could be different in development
192 : environments or on other chains which we support.
193 :
194 : Due to protocol limitations, when mixing in transactions to the
195 : proof-of-history chain, it cannot occur on a tick boundary (but
196 : can occur at any other hashcnt).
197 :
198 : Ticks exist mainly so that verification can happen in parallel.
199 : A verifier computer, rather than needing to do hash(hash(...))
200 : all in sequence to verify a proof-of-history chain, can do,
201 :
202 : Core 0: hash(hash(...))
203 : Core 1: hash(hash(...))
204 : Core 2: hash(hash(...))
205 : Core 3: hash(hash(...))
206 : ...
207 :
208 : Between each pair of tick boundaries.
209 :
210 : Solana sometimes calls the current tick the "tick height",
211 : although it makes more sense to think of it as a counter from
212 : zero, it's just the number of ticks since the genesis hash.
213 :
214 : There is a set of features which increase the number of hashcnts
215 : per tick. These are all deployed on mainnet-beta, devnet, and
216 : testnet.
217 :
218 : name: update_hashes_per_tick
219 : id: 3uFHb9oKdGfgZGJK9EHaAXN4USvnQtAFC13Fh5gGFS5B
220 : hashes per tick: 12,500
221 : hashcnt duration: 500 nanos
222 :
223 : name: update_hashes_per_tick2
224 : id: EWme9uFqfy1ikK1jhJs8fM5hxWnK336QJpbscNtizkTU
225 : hashes per tick: 17,500
226 : hashcnt duration: 357.142857143 nanos
227 :
228 : name: update_hashes_per_tick3
229 : id: 8C8MCtsab5SsfammbzvYz65HHauuUYdbY2DZ4sznH6h5
230 : hashes per tick: 27,500
231 : hashcnt duration: 227.272727273 nanos
232 :
233 : name: update_hashes_per_tick4
234 : id: 8We4E7DPwF2WfAN8tRTtWQNhi98B99Qpuj7JoZ3Aikgg
235 : hashes per tick: 47,500
236 : hashcnt duration: 131.578947368 nanos
237 :
238 : name: update_hashes_per_tick5
239 : id: BsKLKAn1WM4HVhPRDsjosmqSg2J8Tq5xP2s2daDS6Ni4
240 : hashes per tick: 57,500
241 : hashcnt duration: 108.695652174 nanos
242 :
243 : name: update_hashes_per_tick6
244 : id: FKu1qYwLQSiehz644H6Si65U5ZQ2cp9GxsyFUfYcuADv
245 : hashes per tick: 62,500
246 : hashcnt duration: 100 nanos
247 :
248 : In development environments, there is a way to configure the
249 : hashcnt per tick to be "none" during genesis, for a so-called
250 : "low power" tick producer. The idea is not to spin cores during
251 : development. This is equivalent to setting the hashcnt per tick
252 : to be 1, and increasing the hashcnt duration to the desired tick
253 : duration.
254 :
255 : SLOTS
256 :
257 : Each leader needs to be leader for a fixed amount of time, which
258 : is called a slot. During a slot, a leader has an opportunity to
259 : receive transactions and produce a block for the network,
260 : although they may miss ("skip") the slot if they are offline or
261 : not behaving.
262 :
263 : In mainnet-beta, testnet, and devnet a slot is 64 ticks, or
264 : 4,000,000 hashcnts, or approximately 400 milliseconds.
265 :
266 : Due to the way the leader schedule is constructed, each leader
267 : is always given at least four (4) consecutive slots in the
268 : schedule. This means when becoming leader you will be leader
269 : for at least 4 slots, or 1.6 seconds.
270 :
271 : It is rare, although can happen that a leader gets more than 4
272 : consecutive slots (eg, 8, or 12), if they are lucky with the
273 : leader schedule generation.
274 :
275 : The number of ticks in a slot is fixed at genesis time, and
276 : could be different for development or other chains, which we
277 : support. There is nothing special about 4 leader slots in a
278 : row, and this might be changed in future, and the proof of
279 : history makes no assumptions that this is the case.
280 :
281 : EPOCHS
282 :
283 : Infrequently, the network needs to do certain housekeeping,
284 : mainly things like collecting rent and deciding on the leader
285 : schedule. The length of an epoch is fixed on mainnet-beta,
286 : devnet and testnet at 420,000 slots, or around ~2 (1.94) days.
287 : This value is fixed at genesis time, and could be different for
288 : other chains including development, which we support. Typically
289 : in development, epochs are every 8,192 slots, or around ~1 hour
290 : (54.61 minutes), although it depends on the number of ticks per
291 : slot and the target hashcnt rate of the genesis as well.
292 :
293 : In development, epochs need not be a fixed length either. There
294 : is a "warmup" option, where epochs start short and grow, which
295 : is useful for quickly warming up stake during development.
296 :
297 : The epoch is important because it is the only time the leader
298 : schedule is updated. The leader schedule is a list of which
299 : leader is leader for which slot, and is generated by a special
300 : algorithm that is deterministic and known to all nodes.
301 :
302 : The leader schedule is computed one epoch in advance, so that
303 : at slot T, we always know who will be leader up until the end
304 : of slot T+EPOCH_LENGTH. Specifically, the leader schedule for
305 : epoch N is computed during the epoch boundary crossing from
306 : N-2 to N-1. For mainnet-beta, the slots per epoch is fixed and
307 : will always be 420,000. */
308 :
309 : #include "../../disco/tiles.h"
310 : #include "../../disco/bundle/fd_bundle_crank.h"
311 : #include "../../disco/pack/fd_pack.h"
312 : #include "../../ballet/sha256/fd_sha256.h"
313 : #include "../../disco/metrics/fd_metrics.h"
314 : #include "../../util/pod/fd_pod.h"
315 : #include "../../disco/shred/fd_shredder.h"
316 : #include "../../disco/keyguard/fd_keyload.h"
317 : #include "../../disco/keyguard/fd_keyswitch.h"
318 : #include "../../disco/metrics/generated/fd_metrics_poh.h"
319 : #include "../../disco/plugin/fd_plugin.h"
320 : #include "../../flamenco/leaders/fd_multi_epoch_leaders.h"
321 :
322 : #include <string.h>
323 :
324 : /* The maximum number of microblocks that pack is allowed to pack into a
325 : single slot. This is not consensus critical, and pack could, if we
326 : let it, produce as many microblocks as it wants, and the slot would
327 : still be valid.
328 :
329 : We have this here instead so that PoH can estimate slot completion,
330 : and keep the hashcnt up to date as pack progresses through packing
331 : the slot. If this upper bound was not enforced, PoH could tick to
332 : the last hash of the slot and have no hashes left to mixin incoming
333 : microblocks from pack, so this upper bound is a coordination
334 : mechanism so that PoH can progress hashcnts while the slot is active,
335 : and know that pack will not need those hashcnts later to do mixins. */
336 0 : #define MAX_MICROBLOCKS_PER_SLOT (32768UL)
337 :
338 : /* When we are hashing in the background in case a prior leader skips
339 : their slot, we need to store the result of each tick hash so we can
340 : publish them when we become leader. The network requires at least
341 : one leader slot to publish in each epoch for the leader schedule to
342 : generate, so in the worst case we might need two full epochs of slots
343 : to store the hashes. (Eg, if epoch T only had a published slot in
344 : position 0 and epoch T+1 only had a published slot right at the end).
345 :
346 : There is a tighter bound: the block data limit of mainnet-beta is
347 : currently FD_PACK_MAX_DATA_PER_BLOCK, or 27,332,342 bytes per slot.
348 : At 48 bytes per tick, it is not possible to publish a slot that skips
349 : 569,424 or more prior slots. */
350 0 : #define MAX_SKIPPED_TICKS (1UL+(FD_PACK_MAX_DATA_PER_BLOCK/48UL))
351 :
352 0 : #define IN_KIND_BANK (0)
353 0 : #define IN_KIND_PACK (1)
354 0 : #define IN_KIND_STAKE (2)
355 :
356 :
357 : typedef struct {
358 : fd_wksp_t * mem;
359 : ulong chunk0;
360 : ulong wmark;
361 : } fd_poh_in_ctx_t;
362 :
363 : typedef struct {
364 : ulong idx;
365 : fd_wksp_t * mem;
366 : ulong chunk0;
367 : ulong wmark;
368 : ulong chunk;
369 : } fd_poh_out_ctx_t;
370 :
371 : typedef struct {
372 : fd_stem_context_t * stem;
373 :
374 : /* Static configuration determined at genesis creation time. See
375 : long comment above for more information. */
376 : ulong tick_duration_ns;
377 : ulong hashcnt_per_tick;
378 : ulong ticks_per_slot;
379 :
380 : /* Derived from the above configuration, but we precompute it. */
381 : double slot_duration_ns;
382 : double hashcnt_duration_ns;
383 : ulong hashcnt_per_slot;
384 : /* Constant, fixed at initialization. The maximum number of
385 : microblocks that the pack tile can publish in each slot. */
386 : ulong max_microblocks_per_slot;
387 :
388 : /* Consensus-critical slot cost limits. */
389 : struct {
390 : ulong slot_max_cost;
391 : ulong slot_max_vote_cost;
392 : ulong slot_max_write_cost_per_acct;
393 : } limits;
394 :
395 : /* The current slot and hashcnt within that slot of the proof of
396 : history, including hashes we have been producing in the background
397 : while waiting for our next leader slot. */
398 : ulong slot;
399 : ulong hashcnt;
400 : ulong cus_used;
401 :
402 : /* When we send a microblock on to the shred tile, we need to tell
403 : it how many hashes there have been since the last microblock, so
404 : this tracks the hashcnt of the last published microblock.
405 :
406 : If we are skipping slots prior to our leader slot, the last_slot
407 : will be quite old, and potentially much larger than the number of
408 : hashcnts in one slot. */
409 : ulong last_slot;
410 : ulong last_hashcnt;
411 :
412 : /* If we have published a tick or a microblock for a particular slot
413 : to the shred tile, we should never become leader for that slot
414 : again, otherwise we could publish a duplicate block.
415 :
416 : This value tracks the max slot that we have published a tick or
417 : microblock for so we can prevent this. */
418 : ulong highwater_leader_slot;
419 :
420 : /* See how this field is used below. If we have sequential leader
421 : slots, we don't reset the expected slot end time between the two,
422 : to prevent clock drift. If we didn't do this, our 2nd slot would
423 : end 400ms + `time_for_replay_to_move_slot_and_reset_poh` after
424 : our 1st, rather than just strictly 400ms. */
425 : int lagged_consecutive_leader_start;
426 : ulong expect_sequential_leader_slot;
427 :
428 : /* There's a race condition ... let's say two banks A and B, bank A
429 : processes some transactions, then releases the account locks, and
430 : sends the microblock to PoH to be stamped. Pack now re-packs the
431 : same accounts with a new microblock, sends to bank B, bank B
432 : executes and sends the microblock to PoH, and this all happens fast
433 : enough that PoH picks the 2nd block to stamp before the 1st. The
434 : accounts database changes now are misordered with respect to PoH so
435 : replay could fail.
436 :
437 : To prevent this race, we order all microblocks and only process
438 : them in PoH in the order they are produced by pack. This is a
439 : little bit over-strict, we just need to ensure that microblocks
440 : with conflicting accounts execute in order, but this is easiest to
441 : implement for now. */
442 : uint expect_pack_idx;
443 :
444 : /* The PoH tile must never drop microblocks that get committed by the
445 : bank, so it needs to always be able to mixin a microblock hash.
446 : Mixing in requires incrementing the hashcnt, so we need to ensure
447 : at all times that there is enough hascnts left in the slot to
448 : mixin whatever future microblocks pack might produce for it.
449 :
450 : This value tracks that. At any time, max_microblocks_per_slot
451 : - microblocks_lower_bound is an upper bound on the maximum number
452 : of microblocks that might still be received in this slot. */
453 : ulong microblocks_lower_bound;
454 :
455 : uchar __attribute__((aligned(32UL))) reset_hash[ 32 ];
456 : uchar __attribute__((aligned(32UL))) hash[ 32 ];
457 :
458 : /* When we are not leader, we need to save the hashes that were
459 : produced in case the prior leader skips. If they skip, we will
460 : replay these skipped hashes into our next leader bank so that
461 : the slot hashes sysvar can be updated correctly, and also publish
462 : them to peer nodes as part of our outgoing shreds. */
463 : uchar skipped_tick_hashes[ MAX_SKIPPED_TICKS ][ 32 ];
464 :
465 : /* The timestamp in nanoseconds of when the reset slot was received.
466 : This is the timestamp we are building on top of to determine when
467 : our next leader slot starts. */
468 : long reset_slot_start_ns;
469 :
470 : /* The timestamp in nanoseconds of when we got the bank for the
471 : current leader slot. */
472 : long leader_bank_start_ns;
473 :
474 : /* The hashcnt corresponding to the start of the current reset slot. */
475 : ulong reset_slot;
476 :
477 : /* The hashcnt at which our next leader slot begins, or ULONG max if
478 : we have no known next leader slot. */
479 : ulong next_leader_slot;
480 :
481 : /* If an in progress frag should be skipped */
482 : int skip_frag;
483 :
484 : ulong max_active_descendant;
485 :
486 : /* If we currently are the leader according the clock AND we have
487 : received the leader bank for the slot from the replay stage,
488 : this value will be non-NULL.
489 :
490 : Note that we might be inside our leader slot, but not have a bank
491 : yet, in which case this will still be NULL.
492 :
493 : It will be NULL for a brief race period between consecutive leader
494 : slots, as we ping-pong back to replay stage waiting for a new bank.
495 :
496 : Agave refers to this as the "working bank". */
497 : void const * current_leader_bank;
498 :
499 : fd_sha256_t * sha256;
500 :
501 : fd_multi_epoch_leaders_t * mleaders;
502 :
503 : /* The last sequence number of an outgoing fragment to the shred tile,
504 : or ULONG max if no such fragment. See fd_keyswitch.h for details
505 : of how this is used. */
506 : ulong shred_seq;
507 :
508 : int halted_switching_key;
509 :
510 : fd_keyswitch_t * keyswitch;
511 : fd_pubkey_t identity_key;
512 :
513 : /* We need a few pieces of information to compute the right addresses
514 : for bundle crank information that we need to send to pack. */
515 : struct {
516 : int enabled;
517 : fd_pubkey_t vote_account;
518 : fd_bundle_crank_gen_t gen[1];
519 : } bundle;
520 :
521 :
522 : /* The Agave client needs to be notified when the leader changes,
523 : so that they can resume the replay stage if it was suspended waiting. */
524 : void * signal_leader_change;
525 :
526 : /* These are temporarily set in during_frag so they can be used in
527 : after_frag once the frag has been validated as not overrun. */
528 : uchar _txns[ USHORT_MAX ];
529 : fd_microblock_trailer_t _microblock_trailer[ 1 ];
530 :
531 : int in_kind[ 64 ];
532 : fd_poh_in_ctx_t in[ 64 ];
533 :
534 : fd_poh_out_ctx_t shred_out[ 1 ];
535 : fd_poh_out_ctx_t pack_out[ 1 ];
536 : fd_poh_out_ctx_t plugin_out[ 1 ];
537 :
538 : fd_histf_t begin_leader_delay[ 1 ];
539 : fd_histf_t first_microblock_delay[ 1 ];
540 : fd_histf_t slot_done_delay[ 1 ];
541 : fd_histf_t bundle_init_delay[ 1 ];
542 :
543 : ulong features_activation_avail;
544 : fd_shred_features_activation_t features_activation[1];
545 :
546 : ulong parent_slot;
547 : uchar parent_block_id[ 32 ];
548 :
549 : uchar __attribute__((aligned(FD_MULTI_EPOCH_LEADERS_ALIGN))) mleaders_mem[ FD_MULTI_EPOCH_LEADERS_FOOTPRINT ];
550 : } fd_poh_ctx_t;
551 :
552 : /* The PoH recorder is implemented in Firedancer but for now needs to
553 : work with Agave, so we have a locking scheme for them to
554 : co-operate.
555 :
556 : This is because the PoH tile lives in the Agave memory address
557 : space and their version of concurrency is locking the PoH recorder
558 : and reading arbitrary fields.
559 :
560 : So we allow them to lock the PoH tile, although with a very bad (for
561 : them) locking scheme. By default, the tile has full and exclusive
562 : access to the data. If part of Agave wishes to read/write they
563 : can either,
564 :
565 : 1. Rewrite their concurrency to message passing based on mcache
566 : (preferred, but not feasible).
567 : 2. Signal to the tile they wish to acquire the lock, by setting
568 : fd_poh_waiting_lock to 1.
569 :
570 : During after_credit, the tile will check if the waiting lock is set
571 : to 1, and if so, set the returned lock to 1, indicating to the waiter
572 : that they may now proceed.
573 :
574 : When the waiter is done reading and writing, they restore the
575 : returned lock value back to zero, and the POH tile continues with its
576 : day. */
577 :
578 : static fd_poh_ctx_t * fd_poh_global_ctx;
579 :
580 : static volatile ulong fd_poh_waiting_lock __attribute__((aligned(128UL)));
581 : static volatile ulong fd_poh_returned_lock __attribute__((aligned(128UL)));
582 :
583 : /* Agave also needs to write to some mcaches, so we trampoline
584 : that via. the PoH tile as well. */
585 :
586 : struct poh_link {
587 : fd_frag_meta_t * mcache;
588 : ulong depth;
589 : ulong tx_seq;
590 :
591 : void * mem;
592 : void * dcache;
593 : ulong chunk0;
594 : ulong wmark;
595 : ulong chunk;
596 :
597 : ulong cr_avail;
598 : ulong rx_cnt;
599 : ulong * rx_fseqs[ 32UL ];
600 : };
601 :
602 : typedef struct poh_link poh_link_t;
603 :
604 : static poh_link_t gossip_dedup;
605 : static poh_link_t stake_out;
606 : static poh_link_t crds_shred;
607 : static poh_link_t replay_resolv;
608 : static poh_link_t executed_txn;
609 :
610 : static poh_link_t replay_plugin;
611 : static poh_link_t gossip_plugin;
612 : static poh_link_t start_progress_plugin;
613 : static poh_link_t vote_listener_plugin;
614 : static poh_link_t validator_info_plugin;
615 :
616 : static void
617 0 : poh_link_wait_credit( poh_link_t * link ) {
618 0 : if( FD_LIKELY( link->cr_avail ) ) return;
619 :
620 0 : while( 1 ) {
621 0 : ulong cr_query = ULONG_MAX;
622 0 : for( ulong i=0UL; i<link->rx_cnt; i++ ) {
623 0 : ulong const * _rx_seq = link->rx_fseqs[ i ];
624 0 : ulong rx_seq = FD_VOLATILE_CONST( *_rx_seq );
625 0 : ulong rx_cr_query = (ulong)fd_long_max( (long)link->depth - fd_long_max( fd_seq_diff( link->tx_seq, rx_seq ), 0L ), 0L );
626 0 : cr_query = fd_ulong_min( rx_cr_query, cr_query );
627 0 : }
628 0 : if( FD_LIKELY( cr_query>0UL ) ) {
629 0 : link->cr_avail = cr_query;
630 0 : break;
631 0 : }
632 0 : FD_SPIN_PAUSE();
633 0 : }
634 0 : }
635 :
636 : static void
637 : poh_link_publish( poh_link_t * link,
638 : ulong sig,
639 : uchar const * data,
640 0 : ulong data_sz ) {
641 0 : while( FD_UNLIKELY( !FD_VOLATILE_CONST( link->mcache ) ) ) FD_SPIN_PAUSE();
642 0 : if( FD_UNLIKELY( !link->mem ) ) return; /* link not enabled, don't publish */
643 0 : poh_link_wait_credit( link );
644 :
645 0 : uchar * dst = (uchar *)fd_chunk_to_laddr( link->mem, link->chunk );
646 0 : fd_memcpy( dst, data, data_sz );
647 0 : ulong tspub = (ulong)fd_frag_meta_ts_comp( fd_tickcount() );
648 0 : fd_mcache_publish( link->mcache, link->depth, link->tx_seq, sig, link->chunk, data_sz, 0UL, 0UL, tspub );
649 0 : link->chunk = fd_dcache_compact_next( link->chunk, data_sz, link->chunk0, link->wmark );
650 0 : link->cr_avail--;
651 0 : link->tx_seq++;
652 0 : }
653 :
654 : static void
655 : poh_link_init( poh_link_t * link,
656 : fd_topo_t * topo,
657 : fd_topo_tile_t * tile,
658 0 : ulong out_idx ) {
659 0 : fd_topo_link_t * topo_link = &topo->links[ tile->out_link_id[ out_idx ] ];
660 0 : fd_topo_wksp_t * wksp = &topo->workspaces[ topo->objs[ topo_link->dcache_obj_id ].wksp_id ];
661 :
662 0 : link->mem = wksp->wksp;
663 0 : link->depth = fd_mcache_depth( topo_link->mcache );
664 0 : link->tx_seq = 0UL;
665 0 : link->dcache = topo_link->dcache;
666 0 : link->chunk0 = fd_dcache_compact_chunk0( wksp->wksp, topo_link->dcache );
667 0 : link->wmark = fd_dcache_compact_wmark ( wksp->wksp, topo_link->dcache, topo_link->mtu );
668 0 : link->chunk = link->chunk0;
669 0 : link->cr_avail = 0UL;
670 0 : link->rx_cnt = 0UL;
671 0 : for( ulong i=0UL; i<topo->tile_cnt; i++ ) {
672 0 : fd_topo_tile_t * _tile = &topo->tiles[ i ];
673 0 : for( ulong j=0UL; j<_tile->in_cnt; j++ ) {
674 0 : if( _tile->in_link_id[ j ]==topo_link->id && _tile->in_link_reliable[ j ] ) {
675 0 : FD_TEST( link->rx_cnt<32UL );
676 0 : link->rx_fseqs[ link->rx_cnt++ ] = _tile->in_link_fseq[ j ];
677 0 : break;
678 0 : }
679 0 : }
680 0 : }
681 0 : FD_COMPILER_MFENCE();
682 0 : link->mcache = topo_link->mcache;
683 0 : FD_COMPILER_MFENCE();
684 0 : FD_TEST( link->mcache );
685 0 : }
686 :
687 : /* To help show correctness, functions that might be called from
688 : Rust, either directly or indirectly, have this fake "attribute"
689 : CALLED_FROM_RUST, which is actually nothing. Calls from Rust
690 : typically execute on threads did not call fd_boot, so they do not
691 : have the typical FD_TL variables. In particular, they cannot use
692 : normal metrics, and their log messages don't have full context.
693 : Additionally, Rust functions marked CALLED_FROM_RUST cannot call back
694 : into a C fd_ext function without causing a deadlock (although the
695 : other Rust fd_ext functions have a similar problem).
696 :
697 : To prevent annotation from polluting the whole codebase, calls to
698 : functions outside this file are manually checked and marked as being
699 : safe at each call rather than annotated. */
700 : #define CALLED_FROM_RUST
701 :
702 : static CALLED_FROM_RUST fd_poh_ctx_t *
703 0 : fd_ext_poh_write_lock( void ) {
704 0 : for(;;) {
705 : /* Acquire the waiter lock to make sure we are the first writer in the queue. */
706 0 : if( FD_LIKELY( !FD_ATOMIC_CAS( &fd_poh_waiting_lock, 0UL, 1UL) ) ) break;
707 0 : FD_SPIN_PAUSE();
708 0 : }
709 0 : FD_COMPILER_MFENCE();
710 0 : for(;;) {
711 : /* Now wait for the tile to tell us we can proceed. */
712 0 : if( FD_LIKELY( FD_VOLATILE_CONST( fd_poh_returned_lock ) ) ) break;
713 0 : FD_SPIN_PAUSE();
714 0 : }
715 0 : FD_COMPILER_MFENCE();
716 0 : return fd_poh_global_ctx;
717 0 : }
718 :
719 : static CALLED_FROM_RUST void
720 0 : fd_ext_poh_write_unlock( void ) {
721 0 : FD_COMPILER_MFENCE();
722 0 : FD_VOLATILE( fd_poh_returned_lock ) = 0UL;
723 0 : }
724 :
725 : /* The PoH tile needs to interact with the Agave address space to
726 : do certain operations that Firedancer hasn't reimplemented yet, a.k.a
727 : transaction execution. We have Agave export some wrapper
728 : functions that we call into during regular tile execution. These do
729 : not need any locking, since they are called serially from the single
730 : PoH tile. */
731 :
732 : extern CALLED_FROM_RUST void fd_ext_bank_acquire( void const * bank );
733 : extern CALLED_FROM_RUST void fd_ext_bank_release( void const * bank );
734 : extern CALLED_FROM_RUST void fd_ext_poh_signal_leader_change( void * sender );
735 : extern void fd_ext_poh_register_tick( void const * bank, uchar const * hash );
736 :
737 : /* fd_ext_poh_initialize is called by Agave on startup to
738 : initialize the PoH tile with some static configuration, and the
739 : initial reset slot and hash which it retrieves from a snapshot.
740 :
741 : This function is called by some random Agave thread, but
742 : it blocks booting of the PoH tile. The tile will spin until it
743 : determines that this initialization has happened.
744 :
745 : signal_leader_change is an opaque Rust object that is used to
746 : tell the replay stage that the leader has changed. It is a
747 : Box::into_raw(Arc::increment_strong(crossbeam::Sender)), so it
748 : has infinite lifetime unless this C code releases the refcnt.
749 :
750 : It can be used with `fd_ext_poh_signal_leader_change` which
751 : will just issue a nonblocking send on the channel. */
752 :
753 : CALLED_FROM_RUST void
754 : fd_ext_poh_initialize( ulong tick_duration_ns, /* See clock comments above, will be 6.4 microseconds for mainnet-beta. */
755 : ulong hashcnt_per_tick, /* See clock comments above, will be 62,500 for mainnet-beta. */
756 : ulong ticks_per_slot, /* See clock comments above, will almost always be 64. */
757 : ulong tick_height, /* The counter (height) of the tick to start hashing on top of. */
758 : uchar const * last_entry_hash, /* Points to start of a 32 byte region of memory, the hash itself at the tick height. */
759 0 : void * signal_leader_change /* See comment above. */ ) {
760 0 : FD_COMPILER_MFENCE();
761 0 : for(;;) {
762 : /* Make sure the ctx is initialized before trying to take the lock. */
763 0 : if( FD_LIKELY( FD_VOLATILE_CONST( fd_poh_global_ctx ) ) ) break;
764 0 : FD_SPIN_PAUSE();
765 0 : }
766 0 : fd_poh_ctx_t * ctx = fd_ext_poh_write_lock();
767 :
768 0 : ctx->slot = tick_height/ticks_per_slot;
769 0 : ctx->hashcnt = 0UL;
770 0 : ctx->cus_used = 0UL;
771 0 : ctx->last_slot = ctx->slot;
772 0 : ctx->last_hashcnt = 0UL;
773 0 : ctx->reset_slot = ctx->slot;
774 0 : ctx->reset_slot_start_ns = fd_log_wallclock(); /* safe to call from Rust */
775 :
776 0 : memcpy( ctx->reset_hash, last_entry_hash, 32UL );
777 0 : memcpy( ctx->hash, last_entry_hash, 32UL );
778 :
779 0 : ctx->signal_leader_change = signal_leader_change;
780 :
781 : /* Static configuration about the clock. */
782 0 : ctx->tick_duration_ns = tick_duration_ns;
783 0 : ctx->hashcnt_per_tick = hashcnt_per_tick;
784 0 : ctx->ticks_per_slot = ticks_per_slot;
785 :
786 : /* Recompute derived information about the clock. */
787 0 : ctx->slot_duration_ns = (double)ticks_per_slot*(double)tick_duration_ns;
788 0 : ctx->hashcnt_duration_ns = (double)tick_duration_ns/(double)hashcnt_per_tick;
789 0 : ctx->hashcnt_per_slot = ticks_per_slot*hashcnt_per_tick;
790 :
791 0 : if( FD_UNLIKELY( ctx->hashcnt_per_tick==1UL ) ) {
792 : /* Low power producer, maximum of one microblock per tick in the slot */
793 0 : ctx->max_microblocks_per_slot = ctx->ticks_per_slot;
794 0 : } else {
795 : /* See the long comment in after_credit for this limit */
796 0 : ctx->max_microblocks_per_slot = fd_ulong_min( MAX_MICROBLOCKS_PER_SLOT, ctx->ticks_per_slot*(ctx->hashcnt_per_tick-1UL) );
797 0 : }
798 :
799 0 : fd_ext_poh_write_unlock();
800 0 : }
801 :
802 : /* fd_ext_poh_acquire_bank gets the current leader bank if there is one
803 : currently active. PoH might think we are leader without having a
804 : leader bank if the replay stage has not yet noticed we are leader.
805 :
806 : The bank that is returned is owned the caller, and must be converted
807 : to an Arc<Bank> by calling Arc::from_raw() on it. PoH increments the
808 : reference count before returning the bank, so that it can also keep
809 : its internal copy.
810 :
811 : If there is no leader bank, NULL is returned. In this case, the
812 : caller should not call `Arc::from_raw()`. */
813 :
814 : CALLED_FROM_RUST void const *
815 0 : fd_ext_poh_acquire_leader_bank( void ) {
816 0 : fd_poh_ctx_t * ctx = fd_ext_poh_write_lock();
817 0 : void const * bank = NULL;
818 0 : if( FD_LIKELY( ctx->current_leader_bank ) ) {
819 : /* Clone refcount before we release the lock. */
820 0 : fd_ext_bank_acquire( ctx->current_leader_bank );
821 0 : bank = ctx->current_leader_bank;
822 0 : }
823 0 : fd_ext_poh_write_unlock();
824 0 : return bank;
825 0 : }
826 :
827 : /* fd_ext_poh_reset_slot returns the slot height one above the last good
828 : (unskipped) slot we are building on top of. This is always a good
829 : known value, and will not be ULONG_MAX. */
830 :
831 : CALLED_FROM_RUST ulong
832 0 : fd_ext_poh_reset_slot( void ) {
833 0 : fd_poh_ctx_t * ctx = fd_ext_poh_write_lock();
834 0 : ulong reset_slot = ctx->reset_slot;
835 0 : fd_ext_poh_write_unlock();
836 0 : return reset_slot;
837 0 : }
838 :
839 : CALLED_FROM_RUST void
840 0 : fd_ext_poh_update_active_descendant( ulong max_active_descendant ) {
841 0 : fd_poh_ctx_t * ctx = fd_ext_poh_write_lock();
842 0 : ctx->max_active_descendant = max_active_descendant;
843 0 : fd_ext_poh_write_unlock();
844 0 : }
845 :
846 : /* fd_ext_poh_reached_leader_slot returns 1 if we have reached a slot
847 : where we are leader. This is used by the replay stage to determine
848 : if it should create a new leader bank descendant of the prior reset
849 : slot block.
850 :
851 : Sometimes, even when we reach our slot we do not return 1, as we are
852 : giving a grace period to the prior leader to finish publishing their
853 : block.
854 :
855 : out_leader_slot is the slot height of the leader slot we reached, and
856 : reset_slot is the slot height of the last good (unskipped) slot we
857 : are building on top of. */
858 :
859 : CALLED_FROM_RUST int
860 : fd_ext_poh_reached_leader_slot( ulong * out_leader_slot,
861 0 : ulong * out_reset_slot ) {
862 0 : fd_poh_ctx_t * ctx = fd_ext_poh_write_lock();
863 :
864 0 : *out_leader_slot = ctx->next_leader_slot;
865 0 : *out_reset_slot = ctx->reset_slot;
866 :
867 0 : if( FD_UNLIKELY( ctx->next_leader_slot==ULONG_MAX ||
868 0 : ctx->slot<ctx->next_leader_slot ) ) {
869 : /* Didn't reach our leader slot yet. */
870 0 : fd_ext_poh_write_unlock();
871 0 : return 0;
872 0 : }
873 :
874 0 : if( FD_UNLIKELY( ctx->halted_switching_key ) ) {
875 : /* Reached our leader slot, but the leader pipeline is halted
876 : because we are switching identity key. */
877 0 : fd_ext_poh_write_unlock();
878 0 : return 0;
879 0 : }
880 :
881 0 : if( FD_LIKELY( ctx->reset_slot==ctx->next_leader_slot ) ) {
882 : /* We were reset onto our leader slot, because the prior leader
883 : completed theirs, so we should start immediately, no need for a
884 : grace period. */
885 0 : fd_ext_poh_write_unlock();
886 0 : return 1;
887 0 : }
888 :
889 0 : long now_ns = fd_log_wallclock();
890 0 : long expected_start_time_ns = ctx->reset_slot_start_ns + (long)((double)(ctx->next_leader_slot-ctx->reset_slot)*ctx->slot_duration_ns);
891 :
892 : /* If a prior leader is still in the process of publishing their slot,
893 : delay ours to let them finish ... unless they are so delayed that
894 : we risk getting skipped by the leader following us. 1.2 seconds
895 : is a reasonable default here, although any value between 0 and 1.6
896 : seconds could be considered reasonable. This is arbitrary and
897 : chosen due to intuition. */
898 :
899 0 : if( FD_UNLIKELY( now_ns<expected_start_time_ns+(long)(3.0*ctx->slot_duration_ns) ) ) {
900 : /* If the max_active_descendant is >= next_leader_slot, we waited
901 : too long and a leader after us started publishing to try and skip
902 : us. Just start our leader slot immediately, we might win ... */
903 :
904 0 : if( FD_LIKELY( ctx->max_active_descendant>=ctx->reset_slot && ctx->max_active_descendant<ctx->next_leader_slot ) ) {
905 : /* If one of the leaders between the reset slot and our leader
906 : slot is in the process of publishing (they have a descendant
907 : bank that is in progress of being replayed), then keep waiting.
908 : We probably wouldn't get a leader slot out before they
909 : finished.
910 :
911 : Unless... we are past the deadline to start our slot by more
912 : than 1.2 seconds, in which case we should probably start it to
913 : avoid getting skipped by the leader behind us. */
914 0 : fd_ext_poh_write_unlock();
915 0 : return 0;
916 0 : }
917 0 : }
918 :
919 0 : fd_ext_poh_write_unlock();
920 0 : return 1;
921 0 : }
922 :
923 : CALLED_FROM_RUST static inline void
924 : publish_plugin_slot_start( fd_poh_ctx_t * ctx,
925 : ulong slot,
926 0 : ulong parent_slot ) {
927 0 : if( FD_UNLIKELY( !ctx->plugin_out->mem ) ) return;
928 :
929 0 : fd_plugin_msg_slot_start_t * slot_start = (fd_plugin_msg_slot_start_t *)fd_chunk_to_laddr( ctx->plugin_out->mem, ctx->plugin_out->chunk );
930 0 : *slot_start = (fd_plugin_msg_slot_start_t){ .slot = slot, .parent_slot = parent_slot };
931 0 : fd_stem_publish( ctx->stem, ctx->plugin_out->idx, FD_PLUGIN_MSG_SLOT_START, ctx->plugin_out->chunk, sizeof(fd_plugin_msg_slot_start_t), 0UL, 0UL, 0UL );
932 0 : ctx->plugin_out->chunk = fd_dcache_compact_next( ctx->plugin_out->chunk, sizeof(fd_plugin_msg_slot_start_t), ctx->plugin_out->chunk0, ctx->plugin_out->wmark );
933 0 : }
934 :
935 : CALLED_FROM_RUST static inline void
936 : publish_plugin_slot_end( fd_poh_ctx_t * ctx,
937 : ulong slot,
938 0 : ulong cus_used ) {
939 0 : if( FD_UNLIKELY( !ctx->plugin_out->mem ) ) return;
940 :
941 0 : fd_plugin_msg_slot_end_t * slot_end = (fd_plugin_msg_slot_end_t *)fd_chunk_to_laddr( ctx->plugin_out->mem, ctx->plugin_out->chunk );
942 0 : *slot_end = (fd_plugin_msg_slot_end_t){ .slot = slot, .cus_used = cus_used };
943 0 : fd_stem_publish( ctx->stem, ctx->plugin_out->idx, FD_PLUGIN_MSG_SLOT_END, ctx->plugin_out->chunk, sizeof(fd_plugin_msg_slot_end_t), 0UL, 0UL, 0UL );
944 0 : ctx->plugin_out->chunk = fd_dcache_compact_next( ctx->plugin_out->chunk, sizeof(fd_plugin_msg_slot_end_t), ctx->plugin_out->chunk0, ctx->plugin_out->wmark );
945 0 : }
946 :
947 : extern int
948 : fd_ext_bank_load_account( void const * bank,
949 : int fixed_root,
950 : uchar const * addr,
951 : uchar * owner,
952 : uchar * data,
953 : ulong * data_sz );
954 :
955 : CALLED_FROM_RUST static void
956 : publish_became_leader( fd_poh_ctx_t * ctx,
957 : ulong slot,
958 0 : ulong epoch ) {
959 0 : double tick_per_ns = fd_tempo_tick_per_ns( NULL );
960 0 : fd_histf_sample( ctx->begin_leader_delay, (ulong)((double)(fd_log_wallclock()-ctx->reset_slot_start_ns)/tick_per_ns) );
961 :
962 0 : if( FD_UNLIKELY( ctx->lagged_consecutive_leader_start ) ) {
963 : /* If we are mirroring Agave behavior, the wall clock gets reset
964 : here so we don't count time spent waiting for a bank to freeze
965 : or replay stage to actually start the slot towards our 400ms.
966 :
967 : See extended comments in the config file on this option. */
968 0 : ctx->reset_slot_start_ns = fd_log_wallclock() - (long)((double)(slot-ctx->reset_slot)*ctx->slot_duration_ns);
969 0 : }
970 :
971 0 : fd_bundle_crank_tip_payment_config_t config[1] = { 0 };
972 0 : fd_acct_addr_t tip_receiver_owner[1] = { 0 };
973 :
974 0 : if( FD_UNLIKELY( ctx->bundle.enabled ) ) {
975 0 : long bundle_time = -fd_tickcount();
976 0 : fd_acct_addr_t tip_payment_config[1];
977 0 : fd_acct_addr_t tip_receiver[1];
978 0 : fd_bundle_crank_get_addresses( ctx->bundle.gen, epoch, tip_payment_config, tip_receiver );
979 :
980 0 : fd_acct_addr_t _dummy[1];
981 0 : uchar dummy[1];
982 :
983 0 : void const * bank = ctx->current_leader_bank;
984 :
985 : /* Calling rust from a C function that is CALLED_FROM_RUST risks
986 : deadlock. In this case, I checked the load_account function and
987 : ensured it never calls any C functions that acquire the lock. */
988 0 : ulong sz1 = sizeof(config), sz2 = 1UL;
989 0 : int found1 = fd_ext_bank_load_account( bank, 0, tip_payment_config->b, _dummy->b, (uchar *)config, &sz1 );
990 0 : int found2 = fd_ext_bank_load_account( bank, 0, tip_receiver->b, tip_receiver_owner->b, dummy, &sz2 );
991 : /* The bundle crank code detects whether the accounts were found by
992 : whether they have non-zero values (since found and uninitialized
993 : should be treated the same), so we actually don't really care
994 : about the value of found{1,2}. */
995 0 : (void)found1; (void)found2;
996 0 : bundle_time += fd_tickcount();
997 0 : fd_histf_sample( ctx->bundle_init_delay, (ulong)bundle_time );
998 0 : }
999 :
1000 0 : long slot_start_ns = ctx->reset_slot_start_ns + (long)((double)(slot-ctx->reset_slot)*ctx->slot_duration_ns);
1001 :
1002 : /* No need to check flow control, there are always credits became when we
1003 : are leader, we will not "become" leader again until we are done, so at
1004 : most one frag in flight at a time. */
1005 :
1006 0 : uchar * dst = (uchar *)fd_chunk_to_laddr( ctx->pack_out->mem, ctx->pack_out->chunk );
1007 :
1008 0 : fd_became_leader_t * leader = (fd_became_leader_t *)dst;
1009 0 : leader->slot_start_ns = slot_start_ns;
1010 0 : leader->slot_end_ns = (long)((double)slot_start_ns + ctx->slot_duration_ns);
1011 0 : leader->bank = ctx->current_leader_bank;
1012 0 : leader->max_microblocks_in_slot = ctx->max_microblocks_per_slot;
1013 0 : leader->ticks_per_slot = ctx->ticks_per_slot;
1014 0 : leader->total_skipped_ticks = ctx->ticks_per_slot*(slot-ctx->reset_slot);
1015 0 : leader->epoch = epoch;
1016 0 : leader->bundle->config[0] = config[0];
1017 :
1018 0 : leader->limits.slot_max_cost = ctx->limits.slot_max_cost;
1019 0 : leader->limits.slot_max_vote_cost = ctx->limits.slot_max_vote_cost;
1020 0 : leader->limits.slot_max_write_cost_per_acct = ctx->limits.slot_max_write_cost_per_acct;
1021 :
1022 0 : memcpy( leader->bundle->last_blockhash, ctx->reset_hash, 32UL );
1023 0 : memcpy( leader->bundle->tip_receiver_owner, tip_receiver_owner, 32UL );
1024 :
1025 0 : if( FD_UNLIKELY( leader->ticks_per_slot+leader->total_skipped_ticks>=MAX_SKIPPED_TICKS ) )
1026 0 : FD_LOG_ERR(( "Too many skipped ticks %lu for slot %lu, chain must halt", leader->ticks_per_slot+leader->total_skipped_ticks, slot ));
1027 :
1028 0 : ulong sig = fd_disco_poh_sig( slot, POH_PKT_TYPE_BECAME_LEADER, 0UL );
1029 0 : fd_stem_publish( ctx->stem, ctx->pack_out->idx, sig, ctx->pack_out->chunk, sizeof(fd_became_leader_t), 0UL, 0UL, 0UL );
1030 0 : ctx->pack_out->chunk = fd_dcache_compact_next( ctx->pack_out->chunk, sizeof(fd_became_leader_t), ctx->pack_out->chunk0, ctx->pack_out->wmark );
1031 0 : }
1032 :
1033 : /* The PoH tile knows when it should become leader by waiting for its
1034 : leader slot (with the operating system clock). This function is so
1035 : that when it becomes the leader, it can be told what the leader bank
1036 : is by the replay stage. See the notes in the long comment above for
1037 : more on how this works. */
1038 :
1039 : CALLED_FROM_RUST void
1040 : fd_ext_poh_begin_leader( void const * bank,
1041 : ulong slot,
1042 : ulong epoch,
1043 : ulong hashcnt_per_tick,
1044 : ulong cus_block_limit,
1045 : ulong cus_vote_cost_limit,
1046 0 : ulong cus_account_cost_limit ) {
1047 0 : fd_poh_ctx_t * ctx = fd_ext_poh_write_lock();
1048 :
1049 0 : FD_TEST( !ctx->current_leader_bank );
1050 :
1051 0 : if( FD_UNLIKELY( slot!=ctx->slot ) ) FD_LOG_ERR(( "Trying to begin leader slot %lu but we are now on slot %lu", slot, ctx->slot ));
1052 0 : if( FD_UNLIKELY( slot!=ctx->next_leader_slot ) ) FD_LOG_ERR(( "Trying to begin leader slot %lu but next leader slot is %lu", slot, ctx->next_leader_slot ));
1053 :
1054 0 : if( FD_UNLIKELY( ctx->hashcnt_per_tick!=hashcnt_per_tick ) ) {
1055 0 : FD_LOG_WARNING(( "hashes per tick changed from %lu to %lu", ctx->hashcnt_per_tick, hashcnt_per_tick ));
1056 :
1057 : /* Recompute derived information about the clock. */
1058 0 : ctx->hashcnt_duration_ns = (double)ctx->tick_duration_ns/(double)hashcnt_per_tick;
1059 0 : ctx->hashcnt_per_slot = ctx->ticks_per_slot*hashcnt_per_tick;
1060 0 : ctx->hashcnt_per_tick = hashcnt_per_tick;
1061 :
1062 0 : if( FD_UNLIKELY( ctx->hashcnt_per_tick==1UL ) ) {
1063 : /* Low power producer, maximum of one microblock per tick in the slot */
1064 0 : ctx->max_microblocks_per_slot = ctx->ticks_per_slot;
1065 0 : } else {
1066 : /* See the long comment in after_credit for this limit */
1067 0 : ctx->max_microblocks_per_slot = fd_ulong_min( MAX_MICROBLOCKS_PER_SLOT, ctx->ticks_per_slot*(ctx->hashcnt_per_tick-1UL) );
1068 0 : }
1069 :
1070 : /* Discard any ticks we might have done in the interim. They will
1071 : have the wrong number of hashes per tick. We can just catch back
1072 : up quickly if not too many slots were skipped and hopefully
1073 : publish on time. Note that tick production and verification of
1074 : skipped slots is done for the eventual bank that publishes a
1075 : slot, for example:
1076 :
1077 : Reset Slot: 998
1078 : Epoch Transition Slot: 1000
1079 : Leader Slot: 1002
1080 :
1081 : In this case, if a feature changing the hashcnt_per_tick is
1082 : activated in slot 1000, and we are publishing empty ticks for
1083 : slots 998, 999, 1000, and 1001, they should all have the new
1084 : hashes_per_tick number of hashes, rather than the older one, or
1085 : some combination. */
1086 :
1087 0 : FD_TEST( ctx->last_slot==ctx->reset_slot );
1088 0 : FD_TEST( !ctx->last_hashcnt );
1089 0 : ctx->slot = ctx->reset_slot;
1090 0 : ctx->hashcnt = 0UL;
1091 0 : }
1092 :
1093 0 : ctx->current_leader_bank = bank;
1094 0 : ctx->microblocks_lower_bound = 0UL;
1095 0 : ctx->cus_used = 0UL;
1096 :
1097 0 : ctx->limits.slot_max_cost = cus_block_limit;
1098 0 : ctx->limits.slot_max_vote_cost = cus_vote_cost_limit;
1099 0 : ctx->limits.slot_max_write_cost_per_acct = cus_account_cost_limit;
1100 :
1101 : /* clamp and warn if we are underutilizing CUs */
1102 0 : if( FD_UNLIKELY( ctx->limits.slot_max_cost > FD_PACK_MAX_COST_PER_BLOCK_UPPER_BOUND ) ) {
1103 0 : FD_LOG_WARNING(( "Underutilizing protocol slot CU limit. protocol_limit=%lu validator_limit=%lu", ctx->limits.slot_max_cost, FD_PACK_MAX_COST_PER_BLOCK_UPPER_BOUND ));
1104 0 : ctx->limits.slot_max_cost = FD_PACK_MAX_COST_PER_BLOCK_UPPER_BOUND;
1105 0 : }
1106 0 : if( FD_UNLIKELY( ctx->limits.slot_max_vote_cost > FD_PACK_MAX_VOTE_COST_PER_BLOCK_UPPER_BOUND ) ) {
1107 0 : FD_LOG_WARNING(( "Underutilizing protocol vote CU limit. protocol_limit=%lu validator_limit=%lu", ctx->limits.slot_max_vote_cost, FD_PACK_MAX_VOTE_COST_PER_BLOCK_UPPER_BOUND ));
1108 0 : ctx->limits.slot_max_vote_cost = FD_PACK_MAX_VOTE_COST_PER_BLOCK_UPPER_BOUND;
1109 0 : }
1110 0 : if( FD_UNLIKELY( ctx->limits.slot_max_write_cost_per_acct > FD_PACK_MAX_WRITE_COST_PER_ACCT_UPPER_BOUND ) ) {
1111 0 : FD_LOG_WARNING(( "Underutilizing protocol write CU limit. protocol_limit=%lu validator_limit=%lu", ctx->limits.slot_max_write_cost_per_acct, FD_PACK_MAX_WRITE_COST_PER_ACCT_UPPER_BOUND ));
1112 0 : ctx->limits.slot_max_write_cost_per_acct = FD_PACK_MAX_WRITE_COST_PER_ACCT_UPPER_BOUND;
1113 0 : }
1114 :
1115 : /* We are about to start publishing to the shred tile for this slot
1116 : so update the highwater mark so we never republish in this slot
1117 : again. Also check that the leader slot is greater than the
1118 : highwater, which should have been ensured earlier. */
1119 :
1120 0 : FD_TEST( ctx->highwater_leader_slot==ULONG_MAX || slot>=ctx->highwater_leader_slot );
1121 0 : ctx->highwater_leader_slot = fd_ulong_max( fd_ulong_if( ctx->highwater_leader_slot==ULONG_MAX, 0UL, ctx->highwater_leader_slot ), slot );
1122 :
1123 0 : publish_became_leader( ctx, slot, epoch );
1124 0 : FD_LOG_INFO(( "fd_ext_poh_begin_leader(slot=%lu, highwater_leader_slot=%lu, last_slot=%lu, last_hashcnt=%lu)", slot, ctx->highwater_leader_slot, ctx->last_slot, ctx->last_hashcnt ));
1125 :
1126 0 : fd_ext_poh_write_unlock();
1127 0 : }
1128 :
1129 : /* Determine what the next slot is in the leader schedule is that we are
1130 : leader. Includes the current slot. If we are not leader in what
1131 : remains of the current and next epoch, return ULONG_MAX. */
1132 :
1133 : static inline CALLED_FROM_RUST ulong
1134 0 : next_leader_slot( fd_poh_ctx_t * ctx ) {
1135 : /* If we have published anything in a particular slot, then we
1136 : should never become leader for that slot again. */
1137 0 : ulong min_leader_slot = fd_ulong_max( ctx->slot, fd_ulong_if( ctx->highwater_leader_slot==ULONG_MAX, 0UL, ctx->highwater_leader_slot ) );
1138 0 : return fd_multi_epoch_leaders_get_next_slot( ctx->mleaders, min_leader_slot, &ctx->identity_key );
1139 0 : }
1140 :
1141 : extern int
1142 : fd_ext_admin_rpc_set_identity( uchar const * identity_keypair,
1143 : int require_tower );
1144 :
1145 : static inline int FD_FN_SENSITIVE
1146 : maybe_change_identity( fd_poh_ctx_t * ctx,
1147 0 : int definitely_not_leader ) {
1148 0 : if( FD_UNLIKELY( ctx->halted_switching_key && fd_keyswitch_state_query( ctx->keyswitch )==FD_KEYSWITCH_STATE_UNHALT_PENDING ) ) {
1149 0 : ctx->halted_switching_key = 0;
1150 0 : fd_keyswitch_state( ctx->keyswitch, FD_KEYSWITCH_STATE_COMPLETED );
1151 0 : return 1;
1152 0 : }
1153 :
1154 : /* Cannot change identity while in the middle of a leader slot, else
1155 : poh state machine would become corrupt. */
1156 :
1157 0 : int is_leader = !definitely_not_leader && ctx->next_leader_slot!=ULONG_MAX && ctx->slot>=ctx->next_leader_slot;
1158 0 : if( FD_UNLIKELY( is_leader ) ) return 0;
1159 :
1160 0 : if( FD_UNLIKELY( fd_keyswitch_state_query( ctx->keyswitch )==FD_KEYSWITCH_STATE_SWITCH_PENDING ) ) {
1161 0 : int failed = fd_ext_admin_rpc_set_identity( ctx->keyswitch->bytes, fd_keyswitch_param_query( ctx->keyswitch )==1 );
1162 0 : explicit_bzero( ctx->keyswitch->bytes, 32UL );
1163 0 : FD_COMPILER_MFENCE();
1164 0 : if( FD_UNLIKELY( failed==-1 ) ) {
1165 0 : fd_keyswitch_state( ctx->keyswitch, FD_KEYSWITCH_STATE_FAILED );
1166 0 : return 0;
1167 0 : }
1168 :
1169 0 : memcpy( ctx->identity_key.uc, ctx->keyswitch->bytes+32UL, 32UL );
1170 :
1171 : /* When we switch key, we might have ticked part way through a slot
1172 : that we are now leader in. This violates the contract of the
1173 : tile, that when we become leader, we have not ticked in that slot
1174 : at all. To see why this would be bad, consider the case where we
1175 : have ticked almost to the end, and there isn't enough space left
1176 : to reserve the minimum amount of microblocks needed by pack.
1177 :
1178 : To resolve this, we just reset PoH back to the reset slot, and
1179 : let it try to catch back up quickly. This is OK since the network
1180 : rarely skips. */
1181 0 : ctx->slot = ctx->reset_slot;
1182 0 : ctx->hashcnt = 0UL;
1183 0 : memcpy( ctx->hash, ctx->reset_hash, 32UL );
1184 :
1185 0 : ctx->halted_switching_key = 1;
1186 0 : ctx->keyswitch->result = ctx->shred_seq;
1187 0 : fd_keyswitch_state( ctx->keyswitch, FD_KEYSWITCH_STATE_COMPLETED );
1188 0 : }
1189 :
1190 0 : return 0;
1191 0 : }
1192 :
1193 : static CALLED_FROM_RUST void
1194 0 : no_longer_leader( fd_poh_ctx_t * ctx ) {
1195 0 : if( FD_UNLIKELY( ctx->current_leader_bank ) ) fd_ext_bank_release( ctx->current_leader_bank );
1196 : /* If we stop being leader in a slot, we can never become leader in
1197 : that slot again, and all in-flight microblocks for that slot
1198 : should be dropped. */
1199 0 : ctx->highwater_leader_slot = fd_ulong_max( fd_ulong_if( ctx->highwater_leader_slot==ULONG_MAX, 0UL, ctx->highwater_leader_slot ), ctx->slot );
1200 0 : ctx->current_leader_bank = NULL;
1201 0 : int identity_changed = maybe_change_identity( ctx, 1 );
1202 0 : ctx->next_leader_slot = next_leader_slot( ctx );
1203 0 : if( FD_UNLIKELY( identity_changed ) ) {
1204 0 : FD_LOG_INFO(( "fd_poh_identity_changed(next_leader_slot=%lu)", ctx->next_leader_slot ));
1205 0 : }
1206 :
1207 0 : FD_COMPILER_MFENCE();
1208 0 : fd_ext_poh_signal_leader_change( ctx->signal_leader_change );
1209 0 : FD_LOG_INFO(( "no_longer_leader(next_leader_slot=%lu)", ctx->next_leader_slot ));
1210 0 : }
1211 :
1212 : /* fd_ext_poh_reset is called by the Agave client when a slot on
1213 : the active fork has finished a block and we need to reset our PoH to
1214 : be ticking on top of the block it produced. */
1215 :
1216 : CALLED_FROM_RUST void
1217 : fd_ext_poh_reset( ulong completed_bank_slot, /* The slot that successfully produced a block */
1218 : uchar const * reset_blockhash, /* The hash of the last tick in the produced block */
1219 : ulong hashcnt_per_tick, /* The hashcnt per tick of the bank that completed */
1220 : uchar const * parent_block_id, /* The block id of the parent block */
1221 0 : ulong const * features_activation /* The activation slot of shred-tile features */ ) {
1222 0 : fd_poh_ctx_t * ctx = fd_ext_poh_write_lock();
1223 :
1224 0 : ulong slot_before_reset = ctx->slot;
1225 0 : int leader_before_reset = ctx->slot>=ctx->next_leader_slot;
1226 0 : if( FD_UNLIKELY( leader_before_reset && ctx->current_leader_bank ) ) {
1227 : /* If we were in the middle of a leader slot that we notified pack
1228 : pack to start packing for we can never publish into that slot
1229 : again, mark all in-flight microblocks to be dropped. */
1230 0 : ctx->highwater_leader_slot = fd_ulong_max( fd_ulong_if( ctx->highwater_leader_slot==ULONG_MAX, 0UL, ctx->highwater_leader_slot ), 1UL+ctx->slot );
1231 0 : }
1232 :
1233 0 : ctx->leader_bank_start_ns = fd_log_wallclock(); /* safe to call from Rust */
1234 0 : if( FD_UNLIKELY( ctx->expect_sequential_leader_slot==(completed_bank_slot+1UL) ) ) {
1235 : /* If we are being reset onto a slot, it means some block was fully
1236 : processed, so we reset to build on top of it. Typically we want
1237 : to update the reset_slot_start_ns to the current time, because
1238 : the network will give the next leader 400ms to publish,
1239 : regardless of how long the prior leader took.
1240 :
1241 : But: if we were leader in the prior slot, and the block was our
1242 : own we can do better. We know that the next slot should start
1243 : exactly 400ms after the prior one started, so we can use that as
1244 : the reset slot start time instead. */
1245 0 : ctx->reset_slot_start_ns = ctx->reset_slot_start_ns + (long)((double)((completed_bank_slot+1UL)-ctx->reset_slot)*ctx->slot_duration_ns);
1246 0 : } else {
1247 0 : ctx->reset_slot_start_ns = ctx->leader_bank_start_ns;
1248 0 : }
1249 0 : ctx->expect_sequential_leader_slot = ULONG_MAX;
1250 :
1251 0 : memcpy( ctx->reset_hash, reset_blockhash, 32UL );
1252 0 : memcpy( ctx->hash, reset_blockhash, 32UL );
1253 0 : if( FD_LIKELY( parent_block_id!=NULL ) ) {
1254 0 : ctx->parent_slot = completed_bank_slot;
1255 0 : memcpy( ctx->parent_block_id, parent_block_id, 32UL );
1256 0 : } else {
1257 0 : FD_LOG_WARNING(( "fd_ext_poh_reset(block_id=null,reset_slot=%lu,parent_slot=%lu) - ignored", completed_bank_slot, ctx->parent_slot ));
1258 0 : }
1259 0 : ctx->slot = completed_bank_slot+1UL;
1260 0 : ctx->hashcnt = 0UL;
1261 0 : ctx->last_slot = ctx->slot;
1262 0 : ctx->last_hashcnt = 0UL;
1263 0 : ctx->reset_slot = ctx->slot;
1264 :
1265 0 : if( FD_UNLIKELY( ctx->hashcnt_per_tick!=hashcnt_per_tick ) ) {
1266 0 : FD_LOG_WARNING(( "hashes per tick changed from %lu to %lu", ctx->hashcnt_per_tick, hashcnt_per_tick ));
1267 :
1268 : /* Recompute derived information about the clock. */
1269 0 : ctx->hashcnt_duration_ns = (double)ctx->tick_duration_ns/(double)hashcnt_per_tick;
1270 0 : ctx->hashcnt_per_slot = ctx->ticks_per_slot*hashcnt_per_tick;
1271 0 : ctx->hashcnt_per_tick = hashcnt_per_tick;
1272 :
1273 0 : if( FD_UNLIKELY( ctx->hashcnt_per_tick==1UL ) ) {
1274 : /* Low power producer, maximum of one microblock per tick in the slot */
1275 0 : ctx->max_microblocks_per_slot = ctx->ticks_per_slot;
1276 0 : } else {
1277 : /* See the long comment in after_credit for this limit */
1278 0 : ctx->max_microblocks_per_slot = fd_ulong_min( MAX_MICROBLOCKS_PER_SLOT, ctx->ticks_per_slot*(ctx->hashcnt_per_tick-1UL) );
1279 0 : }
1280 0 : }
1281 :
1282 : /* When we reset, we need to allow PoH to tick freely again rather
1283 : than being constrained. If we are leader after the reset, this
1284 : is OK because we won't tick until we get a bank, and the lower
1285 : bound will be reset with the value from the bank. */
1286 0 : ctx->microblocks_lower_bound = ctx->max_microblocks_per_slot;
1287 :
1288 0 : if( FD_UNLIKELY( leader_before_reset ) ) {
1289 : /* No longer have a leader bank if we are reset. Replay stage will
1290 : call back again to give us a new one if we should become leader
1291 : for the reset slot.
1292 :
1293 : The order is important here, ctx->hashcnt must be updated before
1294 : calling no_longer_leader. */
1295 0 : no_longer_leader( ctx );
1296 0 : }
1297 0 : ctx->next_leader_slot = next_leader_slot( ctx );
1298 0 : FD_LOG_INFO(( "fd_ext_poh_reset(slot=%lu,next_leader_slot=%lu)", ctx->reset_slot, ctx->next_leader_slot ));
1299 :
1300 0 : if( FD_UNLIKELY( ctx->slot>=ctx->next_leader_slot ) ) {
1301 : /* We are leader after the reset... two cases: */
1302 0 : if( FD_LIKELY( ctx->slot==slot_before_reset ) ) {
1303 : /* 1. We are reset onto the same slot we are already leader on.
1304 : This is a common case when we have two leader slots in a
1305 : row, replay stage will reset us to our own slot. No need to
1306 : do anything here, we already sent a SLOT_START. */
1307 0 : FD_TEST( leader_before_reset );
1308 0 : } else {
1309 : /* 2. We are reset onto a different slot. If we were leader
1310 : before, we should first end that slot, then begin the new
1311 : one if we are newly leader now. */
1312 0 : if( FD_LIKELY( leader_before_reset ) ) publish_plugin_slot_end( ctx, slot_before_reset, ctx->cus_used );
1313 0 : else publish_plugin_slot_start( ctx, ctx->next_leader_slot, ctx->reset_slot );
1314 0 : }
1315 0 : } else {
1316 0 : if( FD_UNLIKELY( leader_before_reset ) ) publish_plugin_slot_end( ctx, slot_before_reset, ctx->cus_used );
1317 0 : }
1318 :
1319 : /* There is a subset of FD_SHRED_FEATURES_ACTIVATION_... slots that
1320 : the shred tile needs to be aware of. Since their computation
1321 : requires the bank, we are forced (so far) to receive them here
1322 : from the Rust side, before forwarding them to the shred tile as
1323 : POH_PKT_TYPE_FEAT_ACT_SLOT. This is not elegant, and it should
1324 : be revised in the future (TODO), but it provides a "temporary"
1325 : working solution to handle features activation. */
1326 0 : fd_memcpy( ctx->features_activation->slots, features_activation, sizeof(fd_shred_features_activation_t) );
1327 0 : ctx->features_activation_avail = 1UL;
1328 :
1329 0 : fd_ext_poh_write_unlock();
1330 0 : }
1331 :
1332 : /* Since it can't easily return an Option<Pubkey>, return 1 for Some and
1333 : 0 for None. */
1334 : CALLED_FROM_RUST int
1335 : fd_ext_poh_get_leader_after_n_slots( ulong n,
1336 0 : uchar out_pubkey[ static 32 ] ) {
1337 0 : fd_poh_ctx_t * ctx = fd_ext_poh_write_lock();
1338 0 : ulong slot = ctx->slot + n;
1339 0 : fd_pubkey_t const * leader = fd_multi_epoch_leaders_get_leader_for_slot( ctx->mleaders, slot );
1340 :
1341 0 : int copied = 0;
1342 0 : if( FD_LIKELY( leader ) ) {
1343 0 : memcpy( out_pubkey, leader, 32UL );
1344 0 : copied = 1;
1345 0 : }
1346 0 : fd_ext_poh_write_unlock();
1347 0 : return copied;
1348 0 : }
1349 :
1350 : FD_FN_CONST static inline ulong
1351 0 : scratch_align( void ) {
1352 0 : return 128UL;
1353 0 : }
1354 :
1355 : FD_FN_PURE static inline ulong
1356 0 : scratch_footprint( fd_topo_tile_t const * tile ) {
1357 0 : (void)tile;
1358 0 : ulong l = FD_LAYOUT_INIT;
1359 0 : l = FD_LAYOUT_APPEND( l, alignof( fd_poh_ctx_t ), sizeof( fd_poh_ctx_t ) );
1360 0 : l = FD_LAYOUT_APPEND( l, FD_SHA256_ALIGN, FD_SHA256_FOOTPRINT );
1361 0 : return FD_LAYOUT_FINI( l, scratch_align() );
1362 0 : }
1363 :
1364 : static void
1365 : publish_tick( fd_poh_ctx_t * ctx,
1366 : fd_stem_context_t * stem,
1367 : uchar hash[ static 32 ],
1368 0 : int is_skipped ) {
1369 0 : ulong hashcnt = ctx->hashcnt_per_tick*(1UL+(ctx->last_hashcnt/ctx->hashcnt_per_tick));
1370 :
1371 0 : uchar * dst = (uchar *)fd_chunk_to_laddr( ctx->shred_out->mem, ctx->shred_out->chunk );
1372 :
1373 0 : FD_TEST( ctx->last_slot>=ctx->reset_slot );
1374 0 : fd_entry_batch_meta_t * meta = (fd_entry_batch_meta_t *)dst;
1375 0 : if( FD_UNLIKELY( is_skipped ) ) {
1376 : /* We are publishing ticks for a skipped slot, the reference tick
1377 : and block complete flags should always be zero. */
1378 0 : meta->reference_tick = 0UL;
1379 0 : meta->block_complete = 0;
1380 0 : } else {
1381 0 : meta->reference_tick = hashcnt/ctx->hashcnt_per_tick;
1382 0 : meta->block_complete = hashcnt==ctx->hashcnt_per_slot;
1383 0 : }
1384 :
1385 0 : ulong slot = fd_ulong_if( meta->block_complete, ctx->slot-1UL, ctx->slot );
1386 0 : meta->parent_offset = 1UL+slot-ctx->reset_slot;
1387 :
1388 : /* From poh_reset we received the block_id for ctx->parent_slot.
1389 : Now we're telling shred tile to build on parent: (slot-meta->parent_offset).
1390 : The block_id that we're passing is valid iff the two are the same,
1391 : i.e. ctx->parent_slot == (slot-meta->parent_offset). */
1392 0 : meta->parent_block_id_valid = ctx->parent_slot == (slot-meta->parent_offset);
1393 0 : if( FD_LIKELY( meta->parent_block_id_valid ) ) {
1394 0 : fd_memcpy( meta->parent_block_id, ctx->parent_block_id, 32UL );
1395 0 : }
1396 :
1397 0 : FD_TEST( hashcnt>ctx->last_hashcnt );
1398 0 : ulong hash_delta = hashcnt-ctx->last_hashcnt;
1399 :
1400 0 : dst += sizeof(fd_entry_batch_meta_t);
1401 0 : fd_entry_batch_header_t * tick = (fd_entry_batch_header_t *)dst;
1402 0 : tick->hashcnt_delta = hash_delta;
1403 0 : fd_memcpy( tick->hash, hash, 32UL );
1404 0 : tick->txn_cnt = 0UL;
1405 :
1406 0 : ulong tspub = (ulong)fd_frag_meta_ts_comp( fd_tickcount() );
1407 0 : ulong sz = sizeof(fd_entry_batch_meta_t)+sizeof(fd_entry_batch_header_t);
1408 0 : ulong sig = fd_disco_poh_sig( slot, POH_PKT_TYPE_MICROBLOCK, 0UL );
1409 0 : fd_stem_publish( stem, ctx->shred_out->idx, sig, ctx->shred_out->chunk, sz, 0UL, 0UL, tspub );
1410 0 : ctx->shred_seq = stem->seqs[ ctx->shred_out->idx ];
1411 0 : ctx->shred_out->chunk = fd_dcache_compact_next( ctx->shred_out->chunk, sz, ctx->shred_out->chunk0, ctx->shred_out->wmark );
1412 :
1413 0 : if( FD_UNLIKELY( hashcnt==ctx->hashcnt_per_slot ) ) {
1414 0 : ctx->last_slot++;
1415 0 : ctx->last_hashcnt = 0UL;
1416 0 : } else {
1417 0 : ctx->last_hashcnt = hashcnt;
1418 0 : }
1419 0 : }
1420 :
1421 : static inline void
1422 : publish_features_activation( fd_poh_ctx_t * ctx,
1423 0 : fd_stem_context_t * stem ) {
1424 0 : uchar * dst = (uchar *)fd_chunk_to_laddr( ctx->shred_out->mem, ctx->shred_out->chunk );
1425 0 : fd_shred_features_activation_t * act_data = (fd_shred_features_activation_t *)dst;
1426 0 : fd_memcpy( act_data, ctx->features_activation, sizeof(fd_shred_features_activation_t) );
1427 :
1428 0 : ulong tspub = (ulong)fd_frag_meta_ts_comp( fd_tickcount() );
1429 0 : ulong sz = sizeof(fd_shred_features_activation_t);
1430 0 : ulong sig = fd_disco_poh_sig( ctx->slot, POH_PKT_TYPE_FEAT_ACT_SLOT, 0UL );
1431 0 : fd_stem_publish( stem, ctx->shred_out->idx, sig, ctx->shred_out->chunk, sz, 0UL, 0UL, tspub );
1432 0 : ctx->shred_seq = stem->seqs[ ctx->shred_out->idx ];
1433 0 : ctx->shred_out->chunk = fd_dcache_compact_next( ctx->shred_out->chunk, sz, ctx->shred_out->chunk0, ctx->shred_out->wmark );
1434 0 : }
1435 :
1436 : static inline void
1437 : after_credit( fd_poh_ctx_t * ctx,
1438 : fd_stem_context_t * stem,
1439 : int * opt_poll_in,
1440 0 : int * charge_busy ) {
1441 0 : ctx->stem = stem;
1442 :
1443 0 : FD_COMPILER_MFENCE();
1444 0 : if( FD_UNLIKELY( fd_poh_waiting_lock ) ) {
1445 0 : FD_VOLATILE( fd_poh_returned_lock ) = 1UL;
1446 0 : FD_COMPILER_MFENCE();
1447 0 : for(;;) {
1448 0 : if( FD_UNLIKELY( !FD_VOLATILE_CONST( fd_poh_returned_lock ) ) ) break;
1449 0 : FD_SPIN_PAUSE();
1450 0 : }
1451 0 : FD_COMPILER_MFENCE();
1452 0 : FD_VOLATILE( fd_poh_waiting_lock ) = 0UL;
1453 0 : *opt_poll_in = 0;
1454 0 : *charge_busy = 1;
1455 0 : return;
1456 0 : }
1457 0 : FD_COMPILER_MFENCE();
1458 :
1459 0 : if( FD_UNLIKELY( ctx->features_activation_avail ) ) {
1460 : /* If we have received an update on features_activation, then
1461 : forward them to the shred tile. In principle, this should
1462 : happen at most once per slot. */
1463 0 : publish_features_activation( ctx, stem );
1464 0 : ctx->features_activation_avail = 0UL;
1465 0 : }
1466 :
1467 0 : int is_leader = ctx->next_leader_slot!=ULONG_MAX && ctx->slot>=ctx->next_leader_slot;
1468 0 : if( FD_UNLIKELY( is_leader && !ctx->current_leader_bank ) ) {
1469 : /* If we are the leader, but we didn't yet learn what the leader
1470 : bank object is from the replay stage, do not do any hashing.
1471 :
1472 : This is not ideal, but greatly simplifies the control flow. */
1473 0 : return;
1474 0 : }
1475 :
1476 : /* If we have skipped ticks pending because we skipped some slots to
1477 : become leader, register them now one at a time. */
1478 0 : if( FD_UNLIKELY( is_leader && ctx->last_slot<ctx->slot ) ) {
1479 0 : ulong publish_hashcnt = ctx->last_hashcnt+ctx->hashcnt_per_tick;
1480 0 : ulong tick_idx = (ctx->last_slot*ctx->ticks_per_slot+publish_hashcnt/ctx->hashcnt_per_tick)%MAX_SKIPPED_TICKS;
1481 :
1482 0 : fd_ext_poh_register_tick( ctx->current_leader_bank, ctx->skipped_tick_hashes[ tick_idx ] );
1483 0 : publish_tick( ctx, stem, ctx->skipped_tick_hashes[ tick_idx ], 1 );
1484 :
1485 : /* If we are catching up now and publishing a bunch of skipped
1486 : ticks, we do not want to process any incoming microblocks until
1487 : all the skipped ticks have been published out; otherwise we would
1488 : intersperse skipped tick messages with microblocks. */
1489 0 : *opt_poll_in = 0;
1490 0 : *charge_busy = 1;
1491 0 : return;
1492 0 : }
1493 :
1494 0 : int low_power_mode = ctx->hashcnt_per_tick==1UL;
1495 :
1496 : /* If we are the leader, always leave enough capacity in the slot so
1497 : that we can mixin any potential microblocks still coming from the
1498 : pack tile for this slot. */
1499 0 : ulong max_remaining_microblocks = ctx->max_microblocks_per_slot - ctx->microblocks_lower_bound;
1500 : /* With hashcnt_per_tick hashes per tick, we actually get
1501 : hashcnt_per_tick-1 chances to mixin a microblock. For each tick
1502 : span that we need to reserve, we also need to reserve the hashcnt
1503 : for the tick, hence the +
1504 : max_remaining_microblocks/(hashcnt_per_tick-1) rounded up.
1505 :
1506 : However, if hashcnt_per_tick is 1 because we're in low power mode,
1507 : this should probably just be max_remaining_microblocks. */
1508 0 : ulong max_remaining_ticks_or_microblocks = max_remaining_microblocks;
1509 0 : if( FD_LIKELY( !low_power_mode ) ) max_remaining_ticks_or_microblocks += (max_remaining_microblocks+ctx->hashcnt_per_tick-2UL)/(ctx->hashcnt_per_tick-1UL);
1510 :
1511 0 : ulong restricted_hashcnt = fd_ulong_if( ctx->hashcnt_per_slot>=max_remaining_ticks_or_microblocks, ctx->hashcnt_per_slot-max_remaining_ticks_or_microblocks, 0UL );
1512 :
1513 0 : ulong min_hashcnt = ctx->hashcnt;
1514 :
1515 0 : if( FD_LIKELY( !low_power_mode ) ) {
1516 : /* Recall that there are two kinds of events that will get published
1517 : to the shredder,
1518 :
1519 : (a) Ticks. These occur every 62,500 (hashcnt_per_tick) hashcnts,
1520 : and there will be 64 (ticks_per_slot) of them in each slot.
1521 :
1522 : Ticks must not have any transactions mixed into the hash.
1523 : This is not strictly needed in theory, but is required by the
1524 : current consensus protocol. They get published here in
1525 : after_credit.
1526 :
1527 : (b) Microblocks. These can occur at any other hashcnt, as long
1528 : as it is not a tick. Microblocks cannot be empty, and must
1529 : have at least one transactions mixed in. These get
1530 : published in after_frag.
1531 :
1532 : If hashcnt_per_tick is 1, then we are in low power mode and the
1533 : following does not apply, since we can mix in transactions at any
1534 : time.
1535 :
1536 : In the normal, non-low-power mode, though, we have to be careful
1537 : to make sure that we do not publish microblocks on tick
1538 : boundaries. To do that, we need to obey two rules:
1539 : (i) after_credit must not leave hashcnt one before a tick
1540 : boundary
1541 : (ii) if after_credit begins one before a tick boundary, it must
1542 : advance hashcnt and publish the tick
1543 :
1544 : There's some interplay between min_hashcnt and restricted_hashcnt
1545 : here, and we need to show that there's always a value of
1546 : target_hashcnt we can pick such that
1547 : min_hashcnt <= target_hashcnt <= restricted_hashcnt.
1548 : We'll prove this by induction for current_slot==0 and
1549 : is_leader==true, since all other slots should be the same.
1550 :
1551 : Let m_j and r_j be the min_hashcnt and restricted_hashcnt
1552 : (respectively) for the jth call to after_credit in a slot. We
1553 : want to show that for all values of j, it's possible to pick a
1554 : value h_j, the value of target_hashcnt for the jth call to
1555 : after_credit (which is also the value of hashcnt after
1556 : after_credit has completed) such that m_j<=h_j<=r_j.
1557 :
1558 : Additionally, let T be hashcnt_per_tick and N be ticks_per_slot.
1559 :
1560 : Starting with the base case, j==0. m_j=0, and
1561 : r_0 = N*T - max_microblocks_per_slot
1562 : - ceil(max_microblocks_per_slot/(T-1)).
1563 :
1564 : This is monotonic decreasing in max_microblocks_per_slot, so it
1565 : achieves its minimum when max_microblocks_per_slot is its
1566 : maximum.
1567 : r_0 >= N*T - N*(T-1) - ceil( (N*(T-1))/(T-1))
1568 : = N*T - N*(T-1)-N = 0.
1569 : Thus, m_0 <= r_0, as desired.
1570 :
1571 :
1572 :
1573 : Then, for the inductive step, assume there exists h_j such that
1574 : m_j<=h_j<=r_j, and we want to show that there exists h_{j+1},
1575 : which is the same as showing m_{j+1}<=r_{j+1}.
1576 :
1577 : Let a_j be 1 if we had a microblock immediately following the jth
1578 : call to after_credit, and 0 otherwise. Then hashcnt at the start
1579 : of the (j+1)th call to after_frag is h_j+a_j.
1580 : Also, set b_{j+1}=1 if we are in the case covered by rule (ii)
1581 : above during the (j+1)th call to after_credit, i.e. if
1582 : (h_j+a_j)%T==T-1. Thus, m_{j+1} = h_j + a_j + b_{j+1}.
1583 :
1584 : If we received an additional microblock, then
1585 : max_remaining_microblocks goes down by 1, and
1586 : max_remaining_ticks_or_microblocks goes down by either 1 or 2,
1587 : which means restricted_hashcnt goes up by either 1 or 2. In
1588 : particular, it goes up by 2 if the new value of
1589 : max_remaining_microblocks (at the start of the (j+1)th call to
1590 : after_credit) is congruent to 0 mod T-1. Let b'_{j+1} be 1 if
1591 : this condition is met and 0 otherwise. If we receive a
1592 : done_packing message, restricted_hashcnt can go up by more, but
1593 : we can ignore that case, since it is less restrictive.
1594 : Thus, r_{j+1}=r_j+a_j+b'_{j+1}.
1595 :
1596 : If h_j < r_j (strictly less), then h_j+a_j < r_j+a_j. And thus,
1597 : since b_{j+1}<=b'_{j+1}+1, just by virtue of them both being
1598 : binary,
1599 : h_j + a_j + b_{j+1} < r_j + a_j + b'_{j+1} + 1,
1600 : which is the same (for integers) as
1601 : h_j + a_j + b_{j+1} <= r_j + a_j + b'_{j+1},
1602 : m_{j+1} <= r_{j+1}
1603 :
1604 : On the other hand, if h_j==r_j, this is easy unless b_{j+1}==1,
1605 : which can also only happen if a_j==1. Then (h_j+a_j)%T==T-1,
1606 : which means there's an integer k such that
1607 :
1608 : h_j+a_j==(ticks_per_slot-k)*T-1
1609 : h_j ==ticks_per_slot*T - k*(T-1)-1 - k-1
1610 : ==ticks_per_slot*T - (k*(T-1)+1) - ceil( (k*(T-1)+1)/(T-1) )
1611 :
1612 : Since h_j==r_j in this case, and
1613 : r_j==(ticks_per_slot*T) - max_remaining_microblocks_j - ceil(max_remaining_microblocks_j/(T-1)),
1614 : we can see that the value of max_remaining_microblocks at the
1615 : start of the jth call to after_credit is k*(T-1)+1. Again, since
1616 : a_j==1, then the value of max_remaining_microblocks at the start
1617 : of the j+1th call to after_credit decreases by 1 to k*(T-1),
1618 : which means b'_{j+1}=1.
1619 :
1620 : Thus, h_j + a_j + b_{j+1} == r_j + a_j + b'_{j+1}, so, in
1621 : particular, h_{j+1}<=r_{j+1} as desired. */
1622 0 : min_hashcnt += (ulong)(min_hashcnt%ctx->hashcnt_per_tick == (ctx->hashcnt_per_tick-1UL)); /* add b_{j+1}, enforcing rule (ii) */
1623 0 : }
1624 : /* Now figure out how many hashes are needed to "catch up" the hash
1625 : count to the current system clock, and clamp it to the allowed
1626 : range. */
1627 0 : long now = fd_log_wallclock();
1628 0 : ulong target_hashcnt;
1629 0 : if( FD_LIKELY( !is_leader ) ) {
1630 0 : target_hashcnt = (ulong)((double)(now - ctx->reset_slot_start_ns) / ctx->hashcnt_duration_ns) - (ctx->slot-ctx->reset_slot)*ctx->hashcnt_per_slot;
1631 0 : } else {
1632 : /* We might have gotten very behind on hashes, but if we are leader
1633 : we want to catch up gradually over the remainder of our leader
1634 : slot, not all at once right now. This helps keep the tile from
1635 : being oversubscribed and taking a long time to process incoming
1636 : microblocks. */
1637 0 : long expected_slot_start_ns = ctx->reset_slot_start_ns + (long)((double)(ctx->slot-ctx->reset_slot)*ctx->slot_duration_ns);
1638 0 : double actual_slot_duration_ns = ctx->slot_duration_ns<(double)(ctx->leader_bank_start_ns - expected_slot_start_ns) ? 0.0 : ctx->slot_duration_ns - (double)(ctx->leader_bank_start_ns - expected_slot_start_ns);
1639 0 : double actual_hashcnt_duration_ns = actual_slot_duration_ns / (double)ctx->hashcnt_per_slot;
1640 0 : target_hashcnt = fd_ulong_if( actual_hashcnt_duration_ns==0.0, restricted_hashcnt, (ulong)((double)(now - ctx->leader_bank_start_ns) / actual_hashcnt_duration_ns) );
1641 0 : }
1642 : /* Clamp to [min_hashcnt, restricted_hashcnt] as above */
1643 0 : target_hashcnt = fd_ulong_max( fd_ulong_min( target_hashcnt, restricted_hashcnt ), min_hashcnt );
1644 :
1645 : /* The above proof showed that it was always possible to pick a value
1646 : of target_hashcnt, but we still have a lot of freedom in how to
1647 : pick it. It simplifies the code a lot if we don't keep going after
1648 : a tick in this function. In particular, we want to publish at most
1649 : 1 tick in this call, since otherwise we could consume infinite
1650 : credits to publish here. The credits are set so that we should
1651 : only ever publish one tick during this loop. Also, all the extra
1652 : stuff (leader transitions, publishing ticks, etc.) we have to do
1653 : happens at tick boundaries, so this lets us consolidate all those
1654 : cases.
1655 :
1656 : Mathematically, since the current value of hashcnt is h_j+a_j, the
1657 : next tick (advancing a full tick if we're currently at a tick) is
1658 : t_{j+1} = T*(floor( (h_j+a_j)/T )+1). We need to show that if we set
1659 : h'_{j+1} = min( h_{j+1}, t_{j+1} ), it is still valid.
1660 :
1661 : First, h'_{j+1} <= h_{j+1} <= r_{j+1}, so we're okay in that
1662 : direction.
1663 :
1664 : Next, observe that t_{j+1}>=h_j + a_j + 1, and recall that b_{j+1}
1665 : is 0 or 1. So then,
1666 : t_{j+1} >= h_j+a_j+b_{j+1} = m_{j+1}.
1667 :
1668 : We know h_{j+1) >= m_{j+1} from before, so then h'_{j+1} >=
1669 : m_{j+1}, as desired. */
1670 :
1671 0 : ulong next_tick_hashcnt = ctx->hashcnt_per_tick * (1UL+(ctx->hashcnt/ctx->hashcnt_per_tick));
1672 0 : target_hashcnt = fd_ulong_min( target_hashcnt, next_tick_hashcnt );
1673 :
1674 : /* We still need to enforce rule (i). We know that min_hashcnt%T !=
1675 : T-1 because of rule (ii). That means that if target_hashcnt%T ==
1676 : T-1 at this point, target_hashcnt > min_hashcnt (notice the
1677 : strict), so target_hashcnt-1 >= min_hashcnt and is thus still a
1678 : valid choice for target_hashcnt. */
1679 0 : target_hashcnt -= (ulong)( (!low_power_mode) & ((target_hashcnt%ctx->hashcnt_per_tick)==(ctx->hashcnt_per_tick-1UL)) );
1680 :
1681 0 : FD_TEST( target_hashcnt >= ctx->hashcnt );
1682 0 : FD_TEST( target_hashcnt >= min_hashcnt );
1683 0 : FD_TEST( target_hashcnt <= restricted_hashcnt );
1684 :
1685 0 : if( FD_UNLIKELY( ctx->hashcnt==target_hashcnt ) ) return; /* Nothing to do, don't publish a tick twice */
1686 :
1687 0 : *charge_busy = 1;
1688 :
1689 0 : if( FD_LIKELY( ctx->hashcnt<target_hashcnt ) ) {
1690 0 : fd_sha256_hash_32_repeated( ctx->hash, ctx->hash, target_hashcnt-ctx->hashcnt );
1691 0 : ctx->hashcnt = target_hashcnt;
1692 0 : }
1693 :
1694 0 : if( FD_UNLIKELY( ctx->hashcnt==ctx->hashcnt_per_slot ) ) {
1695 0 : ctx->slot++;
1696 0 : ctx->hashcnt = 0UL;
1697 0 : }
1698 :
1699 0 : if( FD_UNLIKELY( !is_leader && !(ctx->hashcnt%ctx->hashcnt_per_tick ) ) ) {
1700 : /* We finished a tick while not leader... save the current hash so
1701 : it can be played back into the bank when we become the leader. */
1702 0 : ulong tick_idx = (ctx->slot*ctx->ticks_per_slot+ctx->hashcnt/ctx->hashcnt_per_tick)%MAX_SKIPPED_TICKS;
1703 0 : fd_memcpy( ctx->skipped_tick_hashes[ tick_idx ], ctx->hash, 32UL );
1704 :
1705 0 : ulong initial_tick_idx = (ctx->last_slot*ctx->ticks_per_slot+ctx->last_hashcnt/ctx->hashcnt_per_tick)%MAX_SKIPPED_TICKS;
1706 0 : if( FD_UNLIKELY( tick_idx==initial_tick_idx ) ) FD_LOG_ERR(( "Too many skipped ticks from slot %lu to slot %lu, chain must halt", ctx->last_slot, ctx->slot ));
1707 0 : }
1708 :
1709 0 : if( FD_UNLIKELY( is_leader && !(ctx->hashcnt%ctx->hashcnt_per_tick) ) ) {
1710 : /* We ticked while leader... tell the leader bank. */
1711 0 : fd_ext_poh_register_tick( ctx->current_leader_bank, ctx->hash );
1712 :
1713 : /* And send an empty microblock (a tick) to the shred tile. */
1714 0 : publish_tick( ctx, stem, ctx->hash, 0 );
1715 0 : }
1716 :
1717 0 : if( FD_UNLIKELY( !is_leader && ctx->slot>=ctx->next_leader_slot ) ) {
1718 : /* We ticked while not leader and are now leader... transition
1719 : the state machine. */
1720 0 : publish_plugin_slot_start( ctx, ctx->next_leader_slot, ctx->reset_slot );
1721 0 : FD_LOG_INFO(( "fd_poh_ticked_into_leader(slot=%lu, reset_slot=%lu)", ctx->next_leader_slot, ctx->reset_slot ));
1722 0 : }
1723 :
1724 0 : if( FD_UNLIKELY( is_leader && ctx->slot>ctx->next_leader_slot ) ) {
1725 : /* We ticked while leader and are no longer leader... transition
1726 : the state machine. */
1727 0 : FD_TEST( !max_remaining_microblocks );
1728 0 : publish_plugin_slot_end( ctx, ctx->next_leader_slot, ctx->cus_used );
1729 0 : FD_LOG_INFO(( "fd_poh_ticked_outof_leader(slot=%lu)", ctx->next_leader_slot ));
1730 :
1731 0 : no_longer_leader( ctx );
1732 0 : ctx->expect_sequential_leader_slot = ctx->slot;
1733 :
1734 0 : double tick_per_ns = fd_tempo_tick_per_ns( NULL );
1735 0 : fd_histf_sample( ctx->slot_done_delay, (ulong)((double)(fd_log_wallclock()-ctx->reset_slot_start_ns)/tick_per_ns) );
1736 0 : ctx->next_leader_slot = next_leader_slot( ctx );
1737 :
1738 0 : if( FD_UNLIKELY( ctx->slot>=ctx->next_leader_slot ) ) {
1739 : /* We finished a leader slot, and are immediately leader for the
1740 : following slot... transition. */
1741 0 : publish_plugin_slot_start( ctx, ctx->next_leader_slot, ctx->next_leader_slot-1UL );
1742 0 : FD_LOG_INFO(( "fd_poh_ticked_into_leader(slot=%lu, reset_slot=%lu)", ctx->next_leader_slot, ctx->next_leader_slot-1UL ));
1743 0 : }
1744 0 : }
1745 0 : }
1746 :
1747 : static inline void
1748 0 : during_housekeeping( fd_poh_ctx_t * ctx ) {
1749 0 : if( FD_UNLIKELY( maybe_change_identity( ctx, 0 ) ) ) {
1750 0 : ctx->next_leader_slot = next_leader_slot( ctx );
1751 0 : FD_LOG_INFO(( "fd_poh_identity_changed(next_leader_slot=%lu)", ctx->next_leader_slot ));
1752 :
1753 : /* Signal replay to check if we are leader again, in-case it's stuck
1754 : because everything already replayed. */
1755 0 : FD_COMPILER_MFENCE();
1756 0 : fd_ext_poh_signal_leader_change( ctx->signal_leader_change );
1757 0 : }
1758 0 : }
1759 :
1760 : static inline void
1761 0 : metrics_write( fd_poh_ctx_t * ctx ) {
1762 0 : FD_MHIST_COPY( POH, BEGIN_LEADER_DELAY_SECONDS, ctx->begin_leader_delay );
1763 0 : FD_MHIST_COPY( POH, FIRST_MICROBLOCK_DELAY_SECONDS, ctx->first_microblock_delay );
1764 0 : FD_MHIST_COPY( POH, SLOT_DONE_DELAY_SECONDS, ctx->slot_done_delay );
1765 0 : FD_MHIST_COPY( POH, BUNDLE_INITIALIZE_DELAY_SECONDS, ctx->bundle_init_delay );
1766 0 : }
1767 :
1768 : static int
1769 : before_frag( fd_poh_ctx_t * ctx,
1770 : ulong in_idx,
1771 : ulong seq,
1772 0 : ulong sig ) {
1773 0 : (void)seq;
1774 :
1775 0 : if( FD_LIKELY( ctx->in_kind[ in_idx ]!=IN_KIND_BANK && ctx->in_kind[ in_idx ]!=IN_KIND_PACK ) ) return 0;
1776 :
1777 0 : uint pack_idx = (uint)fd_disco_bank_sig_pack_idx( sig );
1778 0 : FD_TEST( ((int)(pack_idx-ctx->expect_pack_idx))>=0L );
1779 0 : if( FD_UNLIKELY( pack_idx!=ctx->expect_pack_idx ) ) return -1;
1780 0 : ctx->expect_pack_idx++;
1781 :
1782 0 : return 0;
1783 0 : }
1784 :
1785 : static inline void
1786 : during_frag( fd_poh_ctx_t * ctx,
1787 : ulong in_idx,
1788 : ulong seq FD_PARAM_UNUSED,
1789 : ulong sig,
1790 : ulong chunk,
1791 : ulong sz,
1792 0 : ulong ctl FD_PARAM_UNUSED ) {
1793 0 : ctx->skip_frag = 0;
1794 :
1795 0 : if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_STAKE ) ) {
1796 0 : if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark ) )
1797 0 : FD_LOG_ERR(( "chunk %lu %lu corrupt, not in range [%lu,%lu]", chunk, sz,
1798 0 : ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark ));
1799 :
1800 0 : uchar const * dcache_entry = fd_chunk_to_laddr_const( ctx->in[ in_idx ].mem, chunk );
1801 0 : fd_multi_epoch_leaders_stake_msg_init( ctx->mleaders, fd_type_pun_const( dcache_entry ) );
1802 0 : return;
1803 0 : }
1804 :
1805 0 : ulong slot;
1806 0 : switch( ctx->in_kind[ in_idx ] ) {
1807 0 : case IN_KIND_BANK: {
1808 0 : slot = fd_disco_bank_sig_slot( sig );
1809 0 : break;
1810 0 : }
1811 0 : case IN_KIND_PACK: {
1812 0 : slot = fd_disco_poh_sig_slot( sig );
1813 0 : break;
1814 0 : }
1815 0 : default:
1816 0 : FD_LOG_ERR(( "unexpected in_kind %d", ctx->in_kind[ in_idx ] ));
1817 0 : }
1818 :
1819 : /* The following sequence is possible...
1820 :
1821 : 1. We become leader in slot 10
1822 : 2. While leader, we switch to a fork that is on slot 8, where
1823 : we are leader
1824 : 3. We get the in-flight microblocks for slot 10
1825 :
1826 : These in-flight microblocks need to be dropped, so we check
1827 : against the high water mark (highwater_leader_slot) rather than
1828 : the current hashcnt here when determining what to drop.
1829 :
1830 : We know if the slot is lower than the high water mark it's from a stale
1831 : leader slot, because we will not become leader for the same slot twice
1832 : even if we are reset back in time (to prevent duplicate blocks). */
1833 0 : int is_frag_for_prior_leader_slot = slot<ctx->highwater_leader_slot;
1834 :
1835 0 : if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_PACK ) ) {
1836 : /* We now know the real amount of microblocks published, so set an
1837 : exact bound for once we receive them. */
1838 0 : ctx->skip_frag = 1;
1839 0 : if( FD_UNLIKELY( is_frag_for_prior_leader_slot ) ) return;
1840 :
1841 0 : FD_TEST( ctx->microblocks_lower_bound<=ctx->max_microblocks_per_slot );
1842 0 : fd_done_packing_t const * done_packing = fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk );
1843 0 : FD_LOG_INFO(( "done_packing(slot=%lu,seen_microblocks=%lu,microblocks_in_slot=%lu)",
1844 0 : ctx->slot,
1845 0 : ctx->microblocks_lower_bound,
1846 0 : done_packing->microblocks_in_slot ));
1847 0 : ctx->microblocks_lower_bound += ctx->max_microblocks_per_slot - done_packing->microblocks_in_slot;
1848 0 : return;
1849 0 : } else {
1850 0 : if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz>USHORT_MAX ) )
1851 0 : FD_LOG_ERR(( "chunk %lu %lu corrupt, not in range [%lu,%lu]", chunk, sz, ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark ));
1852 :
1853 0 : uchar * src = (uchar *)fd_chunk_to_laddr( ctx->in[ in_idx ].mem, chunk );
1854 :
1855 0 : fd_memcpy( ctx->_txns, src, sz-sizeof(fd_microblock_trailer_t) );
1856 0 : fd_memcpy( ctx->_microblock_trailer, src+sz-sizeof(fd_microblock_trailer_t), sizeof(fd_microblock_trailer_t) );
1857 :
1858 0 : ctx->skip_frag = is_frag_for_prior_leader_slot;
1859 0 : }
1860 0 : }
1861 :
1862 : static void
1863 : publish_microblock( fd_poh_ctx_t * ctx,
1864 : fd_stem_context_t * stem,
1865 : ulong slot,
1866 : ulong hashcnt_delta,
1867 0 : ulong txn_cnt ) {
1868 0 : uchar * dst = (uchar *)fd_chunk_to_laddr( ctx->shred_out->mem, ctx->shred_out->chunk );
1869 0 : FD_TEST( slot>=ctx->reset_slot );
1870 0 : fd_entry_batch_meta_t * meta = (fd_entry_batch_meta_t *)dst;
1871 0 : meta->parent_offset = 1UL+slot-ctx->reset_slot;
1872 0 : meta->reference_tick = (ctx->hashcnt/ctx->hashcnt_per_tick) % ctx->ticks_per_slot;
1873 0 : meta->block_complete = !ctx->hashcnt;
1874 :
1875 : /* Refer to publish_tick() for details on meta->parent_block_id_valid. */
1876 0 : meta->parent_block_id_valid = ctx->parent_slot == (slot-meta->parent_offset);
1877 0 : if( FD_LIKELY( meta->parent_block_id_valid ) ) {
1878 0 : fd_memcpy( meta->parent_block_id, ctx->parent_block_id, 32UL );
1879 0 : }
1880 :
1881 0 : dst += sizeof(fd_entry_batch_meta_t);
1882 0 : fd_entry_batch_header_t * header = (fd_entry_batch_header_t *)dst;
1883 0 : header->hashcnt_delta = hashcnt_delta;
1884 0 : fd_memcpy( header->hash, ctx->hash, 32UL );
1885 :
1886 0 : dst += sizeof(fd_entry_batch_header_t);
1887 0 : ulong payload_sz = 0UL;
1888 0 : ulong included_txn_cnt = 0UL;
1889 0 : for( ulong i=0UL; i<txn_cnt; i++ ) {
1890 0 : fd_txn_p_t * txn = (fd_txn_p_t *)(ctx->_txns + i*sizeof(fd_txn_p_t));
1891 0 : if( FD_UNLIKELY( !(txn->flags & FD_TXN_P_FLAGS_EXECUTE_SUCCESS) ) ) continue;
1892 :
1893 0 : fd_memcpy( dst, txn->payload, txn->payload_sz );
1894 0 : payload_sz += txn->payload_sz;
1895 0 : dst += txn->payload_sz;
1896 0 : included_txn_cnt++;
1897 0 : }
1898 0 : header->txn_cnt = included_txn_cnt;
1899 :
1900 : /* We always have credits to publish here, because we have a burst
1901 : value of 3 credits, and at most we will publish_tick() once and
1902 : then publish_became_leader() once, leaving one credit here to
1903 : publish the microblock. */
1904 0 : ulong tspub = (ulong)fd_frag_meta_ts_comp( fd_tickcount() );
1905 0 : ulong sz = sizeof(fd_entry_batch_meta_t)+sizeof(fd_entry_batch_header_t)+payload_sz;
1906 0 : ulong new_sig = fd_disco_poh_sig( slot, POH_PKT_TYPE_MICROBLOCK, 0UL );
1907 0 : fd_stem_publish( stem, ctx->shred_out->idx, new_sig, ctx->shred_out->chunk, sz, 0UL, 0UL, tspub );
1908 0 : ctx->shred_seq = stem->seqs[ ctx->shred_out->idx ];
1909 0 : ctx->shred_out->chunk = fd_dcache_compact_next( ctx->shred_out->chunk, sz, ctx->shred_out->chunk0, ctx->shred_out->wmark );
1910 0 : }
1911 :
1912 : static inline void
1913 : after_frag( fd_poh_ctx_t * ctx,
1914 : ulong in_idx,
1915 : ulong seq,
1916 : ulong sig,
1917 : ulong sz,
1918 : ulong tsorig,
1919 : ulong tspub,
1920 0 : fd_stem_context_t * stem ) {
1921 0 : (void)in_idx;
1922 0 : (void)seq;
1923 0 : (void)tsorig;
1924 0 : (void)tspub;
1925 :
1926 0 : if( FD_UNLIKELY( ctx->skip_frag ) ) return;
1927 :
1928 0 : if( FD_UNLIKELY( ctx->in_kind[ in_idx ]==IN_KIND_STAKE ) ) {
1929 0 : fd_multi_epoch_leaders_stake_msg_fini( ctx->mleaders );
1930 : /* It might seem like we do not need to do state transitions in and
1931 : out of being the leader here, since leader schedule updates are
1932 : always one epoch in advance (whether we are leader or not would
1933 : never change for the currently executing slot) but this is not
1934 : true for new ledgers when the validator first boots. We will
1935 : likely be the leader in slot 1, and get notified of the leader
1936 : schedule for that slot while we are still in it.
1937 :
1938 : For safety we just handle both transitions, in and out, although
1939 : the only one possible should be into leader. */
1940 0 : ulong next_leader_slot_after_frag = next_leader_slot( ctx );
1941 :
1942 0 : int currently_leader = ctx->slot>=ctx->next_leader_slot;
1943 0 : int leader_after_frag = ctx->slot>=next_leader_slot_after_frag;
1944 :
1945 0 : FD_LOG_INFO(( "stake_update(before_leader=%lu,after_leader=%lu)",
1946 0 : ctx->next_leader_slot,
1947 0 : next_leader_slot_after_frag ));
1948 :
1949 0 : ctx->next_leader_slot = next_leader_slot_after_frag;
1950 0 : if( FD_UNLIKELY( currently_leader && !leader_after_frag ) ) {
1951 : /* Shouldn't ever happen, otherwise we need to do a state
1952 : transition out of being leader. */
1953 0 : FD_LOG_ERR(( "stake update caused us to no longer be leader in an active slot" ));
1954 0 : }
1955 :
1956 : /* Nothing to do if we transition into being leader, since it
1957 : will just get picked up by the regular tick loop. */
1958 0 : if( FD_UNLIKELY( !currently_leader && leader_after_frag ) ) {
1959 0 : publish_plugin_slot_start( ctx, next_leader_slot_after_frag, ctx->reset_slot );
1960 0 : }
1961 :
1962 0 : return;
1963 0 : }
1964 :
1965 0 : if( FD_UNLIKELY( !ctx->microblocks_lower_bound ) ) {
1966 0 : double tick_per_ns = fd_tempo_tick_per_ns( NULL );
1967 0 : fd_histf_sample( ctx->first_microblock_delay, (ulong)((double)(fd_log_wallclock()-ctx->reset_slot_start_ns)/tick_per_ns) );
1968 0 : }
1969 :
1970 0 : ulong target_slot = fd_disco_bank_sig_slot( sig );
1971 :
1972 0 : if( FD_UNLIKELY( target_slot!=ctx->next_leader_slot || target_slot!=ctx->slot ) ) {
1973 0 : FD_LOG_ERR(( "packed too early or late target_slot=%lu, current_slot=%lu. highwater_leader_slot=%lu",
1974 0 : target_slot, ctx->slot, ctx->highwater_leader_slot ));
1975 0 : }
1976 :
1977 0 : FD_TEST( ctx->current_leader_bank );
1978 0 : FD_TEST( ctx->microblocks_lower_bound<ctx->max_microblocks_per_slot );
1979 0 : ctx->microblocks_lower_bound += 1UL;
1980 :
1981 0 : ulong txn_cnt = (sz-sizeof(fd_microblock_trailer_t))/sizeof(fd_txn_p_t);
1982 0 : fd_txn_p_t * txns = (fd_txn_p_t *)(ctx->_txns);
1983 0 : ulong executed_txn_cnt = 0UL;
1984 0 : ulong cus_used = 0UL;
1985 0 : for( ulong i=0UL; i<txn_cnt; i++ ) {
1986 : /* It's important that we check if a transaction is included in the
1987 : block with FD_TXN_P_FLAGS_EXECUTE_SUCCESS since
1988 : actual_consumed_cus may have a nonzero value for excluded
1989 : transactions used for monitoring purposes */
1990 0 : if( FD_LIKELY( txns[ i ].flags & FD_TXN_P_FLAGS_EXECUTE_SUCCESS ) ) {
1991 0 : executed_txn_cnt++;
1992 0 : cus_used += txns[ i ].bank_cu.actual_consumed_cus;
1993 0 : }
1994 0 : }
1995 :
1996 : /* We don't publish transactions that fail to execute. If all the
1997 : transactions failed to execute, the microblock would be empty,
1998 : causing agave to think it's a tick and complain. Instead, we just
1999 : skip the microblock and don't hash or update the hashcnt. */
2000 0 : if( FD_UNLIKELY( !executed_txn_cnt ) ) return;
2001 :
2002 0 : uchar data[ 64 ];
2003 0 : fd_memcpy( data, ctx->hash, 32UL );
2004 0 : fd_memcpy( data+32UL, ctx->_microblock_trailer->hash, 32UL );
2005 0 : fd_sha256_hash( data, 64UL, ctx->hash );
2006 :
2007 0 : ctx->hashcnt++;
2008 0 : FD_TEST( ctx->hashcnt>ctx->last_hashcnt );
2009 0 : ulong hashcnt_delta = ctx->hashcnt - ctx->last_hashcnt;
2010 :
2011 : /* The hashing loop above will never leave us exactly one away from
2012 : crossing a tick boundary, so this increment will never cause the
2013 : current tick (or the slot) to change, except in low power mode
2014 : for development, in which case we do need to register the tick
2015 : with the leader bank. We don't need to publish the tick since
2016 : sending the microblock below is the publishing action. */
2017 0 : if( FD_UNLIKELY( !(ctx->hashcnt%ctx->hashcnt_per_slot ) ) ) {
2018 0 : ctx->slot++;
2019 0 : ctx->hashcnt = 0UL;
2020 0 : }
2021 :
2022 0 : ctx->last_slot = ctx->slot;
2023 0 : ctx->last_hashcnt = ctx->hashcnt;
2024 :
2025 0 : ctx->cus_used += cus_used;
2026 :
2027 0 : if( FD_UNLIKELY( !(ctx->hashcnt%ctx->hashcnt_per_tick ) ) ) {
2028 0 : fd_ext_poh_register_tick( ctx->current_leader_bank, ctx->hash );
2029 0 : if( FD_UNLIKELY( ctx->slot>ctx->next_leader_slot ) ) {
2030 : /* We ticked while leader and are no longer leader... transition
2031 : the state machine. */
2032 0 : publish_plugin_slot_end( ctx, ctx->next_leader_slot, ctx->cus_used );
2033 :
2034 0 : no_longer_leader( ctx );
2035 :
2036 0 : if( FD_UNLIKELY( ctx->slot>=ctx->next_leader_slot ) ) {
2037 : /* We finished a leader slot, and are immediately leader for the
2038 : following slot... transition. */
2039 0 : publish_plugin_slot_start( ctx, ctx->next_leader_slot, ctx->next_leader_slot-1UL );
2040 0 : }
2041 0 : }
2042 0 : }
2043 :
2044 0 : publish_microblock( ctx, stem, target_slot, hashcnt_delta, txn_cnt );
2045 0 : }
2046 :
2047 : static void
2048 : privileged_init( fd_topo_t * topo,
2049 0 : fd_topo_tile_t * tile ) {
2050 0 : void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
2051 :
2052 0 : FD_SCRATCH_ALLOC_INIT( l, scratch );
2053 0 : fd_poh_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_poh_ctx_t ), sizeof( fd_poh_ctx_t ) );
2054 :
2055 0 : if( FD_UNLIKELY( !strcmp( tile->poh.identity_key_path, "" ) ) )
2056 0 : FD_LOG_ERR(( "identity_key_path not set" ));
2057 :
2058 0 : const uchar * identity_key = fd_keyload_load( tile->poh.identity_key_path, /* pubkey only: */ 1 );
2059 0 : fd_memcpy( ctx->identity_key.uc, identity_key, 32UL );
2060 :
2061 0 : if( FD_UNLIKELY( !tile->poh.bundle.vote_account_path[0] ) ) {
2062 0 : tile->poh.bundle.enabled = 0;
2063 0 : }
2064 0 : if( FD_UNLIKELY( tile->poh.bundle.enabled ) ) {
2065 0 : if( FD_UNLIKELY( !fd_base58_decode_32( tile->poh.bundle.vote_account_path, ctx->bundle.vote_account.uc ) ) ) {
2066 0 : const uchar * vote_key = fd_keyload_load( tile->poh.bundle.vote_account_path, /* pubkey only: */ 1 );
2067 0 : fd_memcpy( ctx->bundle.vote_account.uc, vote_key, 32UL );
2068 0 : }
2069 0 : }
2070 0 : }
2071 :
2072 : /* The Agave client needs to communicate to the shred tile what
2073 : the shred version is on boot, but shred tile does not live in the
2074 : same address space, so have the PoH tile pass the value through
2075 : via. a shared memory ulong. */
2076 :
2077 : static volatile ulong * fd_shred_version;
2078 :
2079 : void
2080 0 : fd_ext_shred_set_shred_version( ulong shred_version ) {
2081 0 : while( FD_UNLIKELY( !fd_shred_version ) ) FD_SPIN_PAUSE();
2082 0 : *fd_shred_version = shred_version;
2083 0 : }
2084 :
2085 : void
2086 : fd_ext_poh_publish_gossip_vote( uchar * data,
2087 0 : ulong data_len ) {
2088 0 : poh_link_publish( &gossip_dedup, 1UL, data, data_len );
2089 0 : }
2090 :
2091 : void
2092 : fd_ext_poh_publish_leader_schedule( uchar * data,
2093 0 : ulong data_len ) {
2094 0 : poh_link_publish( &stake_out, 2UL, data, data_len );
2095 0 : }
2096 :
2097 : void
2098 : fd_ext_poh_publish_cluster_info( uchar * data,
2099 0 : ulong data_len ) {
2100 0 : poh_link_publish( &crds_shred, 2UL, data, data_len );
2101 0 : }
2102 :
2103 : void
2104 0 : fd_ext_poh_publish_executed_txn( uchar const * data ) {
2105 0 : static int lock = 0;
2106 :
2107 : /* Need to lock since the link publisher is not concurrent, and replay
2108 : happens on a thread pool. */
2109 0 : for(;;) {
2110 0 : if( FD_LIKELY( FD_ATOMIC_CAS( &lock, 0, 1 )==0 ) ) break;
2111 0 : FD_SPIN_PAUSE();
2112 0 : }
2113 :
2114 0 : FD_COMPILER_MFENCE();
2115 0 : poh_link_publish( &executed_txn, 0UL, data, 64UL );
2116 0 : FD_COMPILER_MFENCE();
2117 :
2118 0 : FD_VOLATILE(lock) = 0;
2119 0 : }
2120 :
2121 : void
2122 : fd_ext_plugin_publish_replay_stage( ulong sig,
2123 : uchar * data,
2124 0 : ulong data_len ) {
2125 0 : poh_link_publish( &replay_plugin, sig, data, data_len );
2126 0 : }
2127 :
2128 : void
2129 : fd_ext_plugin_publish_genesis_hash( ulong sig,
2130 : uchar * data,
2131 0 : ulong data_len ) {
2132 0 : poh_link_publish( &replay_plugin, sig, data, data_len );
2133 0 : }
2134 :
2135 : void
2136 : fd_ext_plugin_publish_start_progress( ulong sig,
2137 : uchar * data,
2138 0 : ulong data_len ) {
2139 0 : poh_link_publish( &start_progress_plugin, sig, data, data_len );
2140 0 : }
2141 :
2142 : void
2143 : fd_ext_plugin_publish_vote_listener( ulong sig,
2144 : uchar * data,
2145 0 : ulong data_len ) {
2146 0 : poh_link_publish( &vote_listener_plugin, sig, data, data_len );
2147 0 : }
2148 :
2149 : void
2150 : fd_ext_plugin_publish_validator_info( ulong sig,
2151 : uchar * data,
2152 0 : ulong data_len ) {
2153 0 : poh_link_publish( &validator_info_plugin, sig, data, data_len );
2154 0 : }
2155 :
2156 : void
2157 : fd_ext_plugin_publish_periodic( ulong sig,
2158 : uchar * data,
2159 0 : ulong data_len ) {
2160 0 : poh_link_publish( &gossip_plugin, sig, data, data_len );
2161 0 : }
2162 :
2163 : void
2164 : fd_ext_resolv_publish_root_bank( uchar * data,
2165 0 : ulong data_len ) {
2166 0 : poh_link_publish( &replay_resolv, 0UL, data, data_len );
2167 0 : }
2168 :
2169 : void
2170 : fd_ext_resolv_publish_completed_blockhash( uchar * data,
2171 0 : ulong data_len ) {
2172 0 : poh_link_publish( &replay_resolv, 1UL, data, data_len );
2173 0 : }
2174 :
2175 : static inline fd_poh_out_ctx_t
2176 : out1( fd_topo_t const * topo,
2177 : fd_topo_tile_t const * tile,
2178 0 : char const * name ) {
2179 0 : ulong idx = ULONG_MAX;
2180 :
2181 0 : for( ulong i=0UL; i<tile->out_cnt; i++ ) {
2182 0 : fd_topo_link_t const * link = &topo->links[ tile->out_link_id[ i ] ];
2183 0 : if( !strcmp( link->name, name ) ) {
2184 0 : if( FD_UNLIKELY( idx!=ULONG_MAX ) ) FD_LOG_ERR(( "tile %s:%lu had multiple output links named %s but expected one", tile->name, tile->kind_id, name ));
2185 0 : idx = i;
2186 0 : }
2187 0 : }
2188 :
2189 0 : if( FD_UNLIKELY( idx==ULONG_MAX ) ) FD_LOG_ERR(( "tile %s:%lu had no output link named %s", tile->name, tile->kind_id, name ));
2190 :
2191 0 : void * mem = topo->workspaces[ topo->objs[ topo->links[ tile->out_link_id[ idx ] ].dcache_obj_id ].wksp_id ].wksp;
2192 0 : ulong chunk0 = fd_dcache_compact_chunk0( mem, topo->links[ tile->out_link_id[ idx ] ].dcache );
2193 0 : ulong wmark = fd_dcache_compact_wmark ( mem, topo->links[ tile->out_link_id[ idx ] ].dcache, topo->links[ tile->out_link_id[ idx ] ].mtu );
2194 :
2195 0 : return (fd_poh_out_ctx_t){ .idx = idx, .mem = mem, .chunk0 = chunk0, .wmark = wmark, .chunk = chunk0 };
2196 0 : }
2197 :
2198 : static void
2199 : unprivileged_init( fd_topo_t * topo,
2200 0 : fd_topo_tile_t * tile ) {
2201 0 : void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
2202 :
2203 0 : FD_SCRATCH_ALLOC_INIT( l, scratch );
2204 0 : fd_poh_ctx_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof( fd_poh_ctx_t ), sizeof( fd_poh_ctx_t ) );
2205 0 : void * sha256 = FD_SCRATCH_ALLOC_APPEND( l, FD_SHA256_ALIGN, FD_SHA256_FOOTPRINT );
2206 :
2207 0 : #define NONNULL( x ) (__extension__({ \
2208 0 : __typeof__((x)) __x = (x); \
2209 0 : if( FD_UNLIKELY( !__x ) ) FD_LOG_ERR(( #x " was unexpectedly NULL" )); \
2210 0 : __x; }))
2211 :
2212 0 : ctx->mleaders = NONNULL( fd_multi_epoch_leaders_join( fd_multi_epoch_leaders_new( ctx->mleaders_mem ) ) );
2213 0 : ctx->sha256 = NONNULL( fd_sha256_join( fd_sha256_new( sha256 ) ) );
2214 0 : ctx->current_leader_bank = NULL;
2215 0 : ctx->signal_leader_change = NULL;
2216 :
2217 0 : ctx->shred_seq = ULONG_MAX;
2218 0 : ctx->halted_switching_key = 0;
2219 0 : ctx->keyswitch = fd_keyswitch_join( fd_topo_obj_laddr( topo, tile->keyswitch_obj_id ) );
2220 0 : FD_TEST( ctx->keyswitch );
2221 :
2222 0 : ctx->slot = 0UL;
2223 0 : ctx->hashcnt = 0UL;
2224 0 : ctx->last_hashcnt = 0UL;
2225 0 : ctx->highwater_leader_slot = ULONG_MAX;
2226 0 : ctx->next_leader_slot = ULONG_MAX;
2227 0 : ctx->reset_slot = ULONG_MAX;
2228 :
2229 0 : ctx->lagged_consecutive_leader_start = tile->poh.lagged_consecutive_leader_start;
2230 0 : ctx->expect_sequential_leader_slot = ULONG_MAX;
2231 :
2232 0 : ctx->expect_pack_idx = 0U;
2233 0 : ctx->microblocks_lower_bound = 0UL;
2234 :
2235 0 : ctx->max_active_descendant = 0UL;
2236 :
2237 0 : if( FD_UNLIKELY( tile->poh.bundle.enabled ) ) {
2238 0 : ctx->bundle.enabled = 1;
2239 0 : NONNULL( fd_bundle_crank_gen_init( ctx->bundle.gen, (fd_acct_addr_t const *)tile->poh.bundle.tip_distribution_program_addr,
2240 0 : (fd_acct_addr_t const *)tile->poh.bundle.tip_payment_program_addr,
2241 0 : (fd_acct_addr_t const *)ctx->bundle.vote_account.uc,
2242 0 : (fd_acct_addr_t const *)ctx->bundle.vote_account.uc, "NAN", 0UL ) ); /* last three arguments are properly bogus */
2243 0 : } else {
2244 0 : ctx->bundle.enabled = 0;
2245 0 : }
2246 :
2247 0 : ulong poh_shred_obj_id = fd_pod_query_ulong( topo->props, "poh_shred", ULONG_MAX );
2248 0 : FD_TEST( poh_shred_obj_id!=ULONG_MAX );
2249 :
2250 0 : fd_shred_version = fd_fseq_join( fd_topo_obj_laddr( topo, poh_shred_obj_id ) );
2251 0 : FD_TEST( fd_shred_version );
2252 :
2253 0 : poh_link_init( &gossip_dedup, topo, tile, out1( topo, tile, "gossip_dedup" ).idx );
2254 0 : poh_link_init( &stake_out, topo, tile, out1( topo, tile, "stake_out" ).idx );
2255 0 : poh_link_init( &crds_shred, topo, tile, out1( topo, tile, "crds_shred" ).idx );
2256 0 : poh_link_init( &replay_resolv, topo, tile, out1( topo, tile, "replay_resol" ).idx );
2257 0 : poh_link_init( &executed_txn, topo, tile, out1( topo, tile, "executed_txn" ).idx );
2258 :
2259 0 : if( FD_LIKELY( tile->poh.plugins_enabled ) ) {
2260 0 : poh_link_init( &replay_plugin, topo, tile, out1( topo, tile, "replay_plugi" ).idx );
2261 0 : poh_link_init( &gossip_plugin, topo, tile, out1( topo, tile, "gossip_plugi" ).idx );
2262 0 : poh_link_init( &start_progress_plugin, topo, tile, out1( topo, tile, "startp_plugi" ).idx );
2263 0 : poh_link_init( &vote_listener_plugin, topo, tile, out1( topo, tile, "votel_plugin" ).idx );
2264 0 : poh_link_init( &validator_info_plugin, topo, tile, out1( topo, tile, "valcfg_plugi" ).idx );
2265 0 : } else {
2266 : /* Mark these mcaches as "available", so the system boots, but the
2267 : memory is not set so nothing will actually get published via.
2268 : the links. */
2269 0 : FD_COMPILER_MFENCE();
2270 0 : replay_plugin.mcache = (fd_frag_meta_t*)1;
2271 0 : gossip_plugin.mcache = (fd_frag_meta_t*)1;
2272 0 : start_progress_plugin.mcache = (fd_frag_meta_t*)1;
2273 0 : vote_listener_plugin.mcache = (fd_frag_meta_t*)1;
2274 0 : validator_info_plugin.mcache = (fd_frag_meta_t*)1;
2275 0 : FD_COMPILER_MFENCE();
2276 0 : }
2277 :
2278 0 : FD_LOG_INFO(( "PoH waiting to be initialized by Agave client... %lu %lu", fd_poh_waiting_lock, fd_poh_returned_lock ));
2279 0 : FD_VOLATILE( fd_poh_global_ctx ) = ctx;
2280 0 : FD_COMPILER_MFENCE();
2281 0 : for(;;) {
2282 0 : if( FD_LIKELY( FD_VOLATILE_CONST( fd_poh_waiting_lock ) ) ) break;
2283 0 : FD_SPIN_PAUSE();
2284 0 : }
2285 0 : FD_VOLATILE( fd_poh_waiting_lock ) = 0UL;
2286 0 : FD_VOLATILE( fd_poh_returned_lock ) = 1UL;
2287 0 : FD_COMPILER_MFENCE();
2288 0 : for(;;) {
2289 0 : if( FD_UNLIKELY( !FD_VOLATILE_CONST( fd_poh_returned_lock ) ) ) break;
2290 0 : FD_SPIN_PAUSE();
2291 0 : }
2292 0 : FD_COMPILER_MFENCE();
2293 :
2294 0 : if( FD_UNLIKELY( ctx->reset_slot==ULONG_MAX ) ) FD_LOG_ERR(( "PoH was not initialized by Agave client" ));
2295 :
2296 0 : fd_histf_join( fd_histf_new( ctx->begin_leader_delay, FD_MHIST_SECONDS_MIN( POH, BEGIN_LEADER_DELAY_SECONDS ),
2297 0 : FD_MHIST_SECONDS_MAX( POH, BEGIN_LEADER_DELAY_SECONDS ) ) );
2298 0 : fd_histf_join( fd_histf_new( ctx->first_microblock_delay, FD_MHIST_SECONDS_MIN( POH, FIRST_MICROBLOCK_DELAY_SECONDS ),
2299 0 : FD_MHIST_SECONDS_MAX( POH, FIRST_MICROBLOCK_DELAY_SECONDS ) ) );
2300 0 : fd_histf_join( fd_histf_new( ctx->slot_done_delay, FD_MHIST_SECONDS_MIN( POH, SLOT_DONE_DELAY_SECONDS ),
2301 0 : FD_MHIST_SECONDS_MAX( POH, SLOT_DONE_DELAY_SECONDS ) ) );
2302 :
2303 0 : fd_histf_join( fd_histf_new( ctx->bundle_init_delay, FD_MHIST_SECONDS_MIN( POH, BUNDLE_INITIALIZE_DELAY_SECONDS ),
2304 0 : FD_MHIST_SECONDS_MAX( POH, BUNDLE_INITIALIZE_DELAY_SECONDS ) ) );
2305 :
2306 0 : for( ulong i=0UL; i<tile->in_cnt; i++ ) {
2307 0 : fd_topo_link_t * link = &topo->links[ tile->in_link_id[ i ] ];
2308 0 : fd_topo_wksp_t * link_wksp = &topo->workspaces[ topo->objs[ link->dcache_obj_id ].wksp_id ];
2309 :
2310 0 : ctx->in[ i ].mem = link_wksp->wksp;
2311 0 : ctx->in[ i ].chunk0 = fd_dcache_compact_chunk0( ctx->in[ i ].mem, link->dcache );
2312 0 : ctx->in[ i ].wmark = fd_dcache_compact_wmark ( ctx->in[ i ].mem, link->dcache, link->mtu );
2313 :
2314 0 : if( !strcmp( link->name, "stake_out" ) ) {
2315 0 : ctx->in_kind[ i ] = IN_KIND_STAKE;
2316 0 : } else if( !strcmp( link->name, "pack_poh" ) ) {
2317 0 : ctx->in_kind[ i ] = IN_KIND_PACK;
2318 0 : } else if( !strcmp( link->name, "bank_poh" ) ) {
2319 0 : ctx->in_kind[ i ] = IN_KIND_BANK;
2320 0 : } else {
2321 0 : FD_LOG_ERR(( "unexpected input link name %s", link->name ));
2322 0 : }
2323 0 : }
2324 :
2325 0 : *ctx->shred_out = out1( topo, tile, "poh_shred" );
2326 0 : *ctx->pack_out = out1( topo, tile, "poh_pack" );
2327 0 : ctx->plugin_out->mem = NULL;
2328 0 : if( FD_LIKELY( tile->poh.plugins_enabled ) ) {
2329 0 : *ctx->plugin_out = out1( topo, tile, "poh_plugin" );
2330 0 : }
2331 :
2332 0 : ctx->features_activation_avail = 0UL;
2333 0 : for( ulong i=0UL; i<FD_SHRED_FEATURES_ACTIVATION_SLOT_CNT; i++ )
2334 0 : ctx->features_activation->slots[i] = FD_SHRED_FEATURES_ACTIVATION_SLOT_DISABLED;
2335 :
2336 0 : ulong scratch_top = FD_SCRATCH_ALLOC_FINI( l, 1UL );
2337 0 : if( FD_UNLIKELY( scratch_top > (ulong)scratch + scratch_footprint( tile ) ) )
2338 0 : FD_LOG_ERR(( "scratch overflow %lu %lu %lu", scratch_top - (ulong)scratch - scratch_footprint( tile ), scratch_top, (ulong)scratch + scratch_footprint( tile ) ));
2339 0 : }
2340 :
2341 : /* One tick, one microblock, one plugin slot end, one plugin slot start,
2342 : one leader update, and one features activation. */
2343 0 : #define STEM_BURST (6UL)
2344 :
2345 : /* See explanation in fd_pack */
2346 0 : #define STEM_LAZY (128L*3000L)
2347 :
2348 0 : #define STEM_CALLBACK_CONTEXT_TYPE fd_poh_ctx_t
2349 0 : #define STEM_CALLBACK_CONTEXT_ALIGN alignof(fd_poh_ctx_t)
2350 :
2351 0 : #define STEM_CALLBACK_DURING_HOUSEKEEPING during_housekeeping
2352 0 : #define STEM_CALLBACK_METRICS_WRITE metrics_write
2353 0 : #define STEM_CALLBACK_AFTER_CREDIT after_credit
2354 0 : #define STEM_CALLBACK_BEFORE_FRAG before_frag
2355 0 : #define STEM_CALLBACK_DURING_FRAG during_frag
2356 0 : #define STEM_CALLBACK_AFTER_FRAG after_frag
2357 :
2358 : #include "../../disco/stem/fd_stem.c"
2359 :
2360 : fd_topo_run_tile_t fd_tile_poh = {
2361 : .name = "poh",
2362 : .populate_allowed_seccomp = NULL,
2363 : .populate_allowed_fds = NULL,
2364 : .scratch_align = scratch_align,
2365 : .scratch_footprint = scratch_footprint,
2366 : .privileged_init = privileged_init,
2367 : .unprivileged_init = unprivileged_init,
2368 : .run = stem_run,
2369 : };
|