Line data Source code
1 : #define _GNU_SOURCE
2 : #include "utils/fd_ssctrl.h"
3 : #include "utils/fd_ssload.h"
4 : #include "utils/fd_ssmsg.h"
5 : #include "utils/fd_ssparse.h"
6 : #include "utils/fd_ssmanifest_parser.h"
7 : #include "utils/fd_wfs.h"
8 : #include "utils/fd_slot_delta_parser.h"
9 : #include "../../util/fd_hash32.h"
10 : #include "../../util/bits/fd_float.h"
11 : #include "../../util/bits/fd_uwide.h"
12 :
13 : #include "../../disco/topo/fd_topo.h"
14 : #include "../../disco/metrics/fd_metrics.h"
15 : #include "../../disco/gui/fd_gui_config_parse.h"
16 : #include "../../flamenco/runtime/fd_txncache.h"
17 : #include "../../flamenco/runtime/fd_system_ids.h"
18 : #include "../../flamenco/runtime/fd_hashes.h"
19 : #include "../../flamenco/runtime/sysvar/fd_sysvar_cache.h"
20 : #include "../../flamenco/runtime/sysvar/fd_sysvar_epoch_schedule.h"
21 : #include "../../flamenco/runtime/sysvar/fd_sysvar_slot_history.h"
22 : #include "../../flamenco/rewards/fd_rewards_base.h"
23 :
24 : #include "../../flamenco/runtime/fd_bank.h"
25 : #include "../../flamenco/features/fd_features.h"
26 : #include "../../flamenco/stakes/fd_stake_types.h"
27 : #include "../../disco/stem/fd_stem.h"
28 : #include "../../flamenco/accdb/fd_accdb.h"
29 : #include "../../disco/events/generated/fd_event_gen.h"
30 :
31 : #include <linux/futex.h>
32 : #include "generated/fd_snapin_tile_seccomp.h"
33 :
34 : #include <errno.h>
35 : #include <fcntl.h>
36 : #include <unistd.h>
37 :
38 : #define NAME "snapin"
39 :
40 0 : #define FD_SNAPIN_WRITE_BUF_SZ (16UL<<20)
41 : #define FD_SNAPIN_WRITE_ACCOUNT_MAX (FD_SNAPIN_WRITE_BUF_SZ/sizeof(fd_accdb_disk_meta_t))
42 : /* Accounts are written with O_DIRECT so that snapin tiles do not
43 : serialize on the inode lock taken by buffered writes. Each flush is
44 : padded to FD_SNAPIN_DIRECT_ALIGN with a dead record header. The
45 : buffer fills only to FD_SNAPIN_WRITE_BUF_MAX so the header always
46 : fits. */
47 0 : #define FD_SNAPIN_DIRECT_ALIGN (4096UL)
48 0 : #define FD_SNAPIN_WRITE_BUF_MAX (FD_SNAPIN_WRITE_BUF_SZ-sizeof(fd_accdb_disk_meta_t))
49 :
50 : FD_STATIC_ASSERT( FD_SNAPIN_WRITE_BUF_SZ%FD_SNAPIN_DIRECT_ALIGN==0UL, write_buf_align );
51 :
52 : /* Raw state values exported by the metrics (states= enums) */
53 : FD_STATIC_ASSERT( FD_SNAPSHOT_STATE_IDLE==FD_METRICS_ENUM_SNAPSHOT_STREAM_STATE_V_IDLE_IDX, metrics_state );
54 : FD_STATIC_ASSERT( FD_SNAPSHOT_STATE_PROCESSING==FD_METRICS_ENUM_SNAPSHOT_STREAM_STATE_V_PROCESSING_IDX, metrics_state );
55 : FD_STATIC_ASSERT( FD_SNAPSHOT_STATE_FINISHING==FD_METRICS_ENUM_SNAPSHOT_STREAM_STATE_V_FINISHING_IDX, metrics_state );
56 : FD_STATIC_ASSERT( FD_SNAPSHOT_STATE_ERROR==FD_METRICS_ENUM_SNAPSHOT_STREAM_STATE_V_ERROR_IDX, metrics_state );
57 : FD_STATIC_ASSERT( FD_SNAPSHOT_STATE_SHUTDOWN==FD_METRICS_ENUM_SNAPSHOT_STREAM_STATE_V_SHUTDOWN_IDX, metrics_state );
58 : FD_STATIC_ASSERT( FD_SNAPSHOT_DATA_MTU<FD_SNAPIN_WRITE_BUF_MAX, write_buf );
59 : FD_STATIC_ASSERT( sizeof(fd_accdb_disk_meta_t)+FD_RUNTIME_ACC_SZ_MAX<=FD_SNAPIN_WRITE_BUF_MAX, max_account );
60 :
61 : /* The snapin tiles are state machines that parse and load a full and
62 : optionally an incremental snapshot. They are responsible for loading
63 : accounts into the accounts database and writing their records to
64 : disk. */
65 :
66 : struct fd_blockhash_entry {
67 : fd_hash_t blockhash;
68 :
69 : struct {
70 : ulong prev;
71 : ulong next;
72 : } map;
73 : };
74 :
75 : typedef struct fd_blockhash_entry fd_blockhash_entry_t;
76 :
77 : #define MAP_NAME blockhash_map
78 0 : #define MAP_KEY blockhash
79 : #define MAP_KEY_T fd_hash_t
80 : #define MAP_ELE_T fd_blockhash_entry_t
81 0 : #define MAP_KEY_EQ(k0,k1) (!memcmp((k0),(k1), sizeof(fd_hash_t)))
82 0 : #define MAP_KEY_HASH(key,seed) (fd_hash32( (key)->uc, (seed) ))
83 0 : #define MAP_PREV map.prev
84 0 : #define MAP_NEXT map.next
85 : #define MAP_OPTIMIZE_RANDOM_ACCESS_REMOVAL 1
86 : #include "../../util/tmpl/fd_map_chain.c"
87 :
88 : /* One link of the txncache chain rebuilt by populate_txncache, from one
89 : entry of the snapshot's blockhash queue. */
90 :
91 : struct fd_snapin_bank {
92 : ulong hash_index;
93 : uchar blockhash[ 32UL ];
94 : fd_txncache_fork_id_t fork_id;
95 : ulong txnhash_offset;
96 : };
97 :
98 : typedef struct fd_snapin_bank fd_snapin_bank_t;
99 :
100 : #define SORT_NAME fd_snapin_bank_sort_newest_first
101 0 : #define SORT_KEY_T fd_snapin_bank_t
102 0 : #define SORT_BEFORE(a,b) ((a).hash_index>(b).hash_index)
103 : #include "../../util/tmpl/fd_sort.c"
104 :
105 : /* For a transaction to be valid to be inserted into the txncache, it
106 : must reference a blockhash that is in the set of recent blockhashes.
107 : This means that only transactions executed in the latest 151 rooted
108 : blocks can be in the txncache. The remaining entries can be ignored.
109 :
110 : A slot delta holds the transactions of one block, each twice ,once as
111 : signature and once as message hash. When slot deltas are ingested,
112 : their entries are staged in a grid of FD_TXNCACHE_MAX_SLOT_DELTAS
113 : rows of txncache_max_entries_per_slot entries per row, one row per
114 : retained slot delta. */
115 :
116 : FD_STATIC_ASSERT( FD_TXNCACHE_MAX_SLOT_DELTAS<=FD_SLOT_DELTA_MAX_ENTRIES, txncache_staging_slot_cnt );
117 :
118 : /* A blockhash group is one (slot, blockhash) pair in the status cache,
119 : holding the txnhash offset for that blockhash and the entries of the
120 : transactions executed in that slot which referenced the blockhash.
121 : Agave inserts every processed transaction into the status cache twice
122 : (once with message hash and once with signature), both times under
123 : the same blockhash and slot. Groups can reference any blockhash,
124 : including durable nonces that are not in the recent blockhash queue.
125 : So an honest slot has at most txncache_max_groups_per_slot groups
126 : (config->limits.max_txn_per_slot). Snapshots exceeding this are
127 : rejected as malformed. */
128 :
129 : struct blockhash_group {
130 : uchar blockhash[ 32UL ];
131 : uint txnhash_offset;
132 : uint txncache_entry_cnt;
133 : };
134 :
135 : typedef struct blockhash_group blockhash_group_t;
136 :
137 : FD_STATIC_ASSERT( sizeof(blockhash_group_t)==40UL, blockhash_group );
138 :
139 : /* After filtering with the recent blockhash queue, there is at most one
140 : group per retained (slot, recent blockhash) pair. Filtering can only
141 : happen after we receive the manifest, hence we still need
142 : FD_TXNCACHE_MAX_SLOT_DELTAS*txncache_max_groups_per_slot worst case
143 : slot deltas buffered. */
144 0 : #define FD_SNAPIN_MAX_RECENT_GROUPS (FD_TXNCACHE_MAX_SLOT_DELTAS*FD_TXNCACHE_MAX_SLOT_DELTAS)
145 :
146 : struct recent_blockhash_group {
147 : ulong blockhash_bank_i;
148 : ulong execution_slot;
149 : ulong execution_bank_i;
150 : ulong txnhash_offset;
151 : ulong txncache_entry_idx;
152 : ulong txncache_entry_cnt;
153 : };
154 :
155 : typedef struct recent_blockhash_group recent_blockhash_group_t;
156 :
157 : struct txncache_staging_slot {
158 : ulong slot;
159 : ulong entry_cnt;
160 : ulong group_cnt;
161 : };
162 :
163 : typedef struct txncache_staging_slot txncache_staging_slot_t;
164 :
165 : struct fd_snapin_out_link {
166 : ulong idx;
167 : fd_wksp_t * mem;
168 : ulong chunk0;
169 : ulong wmark;
170 : ulong chunk;
171 : ulong mtu;
172 : };
173 : typedef struct fd_snapin_out_link fd_snapin_out_link_t;
174 :
175 : struct fd_snapin_account_batch {
176 : ulong cnt;
177 : ulong lamports [ FD_SNAPIN_WRITE_ACCOUNT_MAX ];
178 : uint slots [ FD_SNAPIN_WRITE_ACCOUNT_MAX ];
179 : uint data_lens [ FD_SNAPIN_WRITE_ACCOUNT_MAX ];
180 : int executables [ FD_SNAPIN_WRITE_ACCOUNT_MAX ];
181 : };
182 :
183 : typedef struct fd_snapin_account_batch fd_snapin_account_batch_t;
184 :
185 : /* Only tile 0 uses this state. */
186 : struct fd_snapin_lead {
187 : uint init_completed : 1; /* did INIT complete for this attempt? */
188 :
189 : ulong seed;
190 : long boot_timestamp;
191 :
192 : fd_txncache_t * txncache;
193 : fd_bank_t * bank;
194 :
195 : fd_ssmanifest_parser_t * manifest_parser;
196 : fd_slot_delta_parser_t * slot_delta_parser;
197 :
198 : struct {
199 : int manifest_done;
200 : int status_cache_done;
201 : int manifest_processed;
202 : } flags;
203 :
204 : ulong advertised_slot;
205 : ulong bank_slot;
206 : ulong epoch;
207 :
208 : fd_epoch_schedule_t epoch_schedule;
209 :
210 : ulong full_genesis_creation_time_seconds;
211 : uchar advertised_hash[ FD_HASH_FOOTPRINT ];
212 :
213 : ulong manifest_capitalization; /* capitalization according to the current snapshot manifest */
214 :
215 : struct {
216 : ulong loaded;
217 : ulong duplicates;
218 : } account_counts;
219 :
220 : struct {
221 : ulong capitalization;
222 : fd_accdb_snapshot_recovery_t accdb_metadata;
223 : } recovery; /* stores state from the last full snapshot for incremental revert */
224 :
225 : fd_sysvar_cache_t sysvar_cache[1]; /* verify_sysvars scratch */
226 :
227 : blockhash_group_t * blockhash_groups;
228 : ulong blockhash_groups_cnt; /* every group parsed, including those from dropped slots */
229 : recent_blockhash_group_t * recent_groups;
230 : ulong recent_groups_len;
231 :
232 : fd_sstxncache_hash_t * txncache_entries;
233 : txncache_staging_slot_t txncache_slots[ FD_TXNCACHE_MAX_SLOT_DELTAS ];
234 : ulong txncache_slots_len;
235 : ulong txncache_current_slot_idx;
236 : ulong txncache_current_slot_group_cnt;
237 : ulong txncache_current_slot_entry_cnt; /* entries of the slot delta being parsed, retained or not */
238 : ulong txncache_max_groups_per_slot; /* config->limits.max_txn_per_slot */
239 : ulong txncache_max_entries_per_slot; /* 2x, signature and message hash entries */
240 :
241 : fd_accdb_fork_id_t accdb_root_fork_id;
242 : fd_accdb_fork_id_t accdb_incr_fork_id; /* child fork for incremental writes (purge on failure) */
243 : fd_txncache_fork_id_t txncache_root_fork_id;
244 :
245 : fd_snapin_out_link_t manifest_out;
246 :
247 : /* Roll back a failure at the next INIT. */
248 : struct {
249 : int pending;
250 : int full; /* failed attempt type */
251 : fd_accdb_fork_id_t fork; /* failed incremental fork */
252 : } rollback;
253 : };
254 :
255 : typedef struct fd_snapin_lead fd_snapin_lead_t;
256 :
257 : /* Shared state for parallel snapin tiles. */
258 : struct fd_snapin_shmem {
259 : /* Tile 0 publishes the accdb fork before acknowledging INIT. */
260 : ulong fork_id;
261 :
262 : /* Stake delegations fork for incremental writes, USHORT_MAX for full. */
263 : ushort stake_fork;
264 :
265 : /* Per-tile attempt values. Lamport totals are 128-bit <*_hi,*>:
266 : they count every account version, which can pass 2^64. */
267 : struct __attribute__((aligned(128))) {
268 : ulong loaded;
269 : ulong duplicates;
270 : ulong input_lamports;
271 : ulong duplicate_lamports;
272 : ulong input_lamports_hi;
273 : ulong duplicate_lamports_hi;
274 : } values[ FD_TOPO_MAX_TILE_IN_LINKS ];
275 :
276 : /* Atomic index of the next unclaimed appendvec. */
277 : ulong next_appendvec_ticket __attribute__((aligned(128)));
278 : };
279 :
280 : typedef struct fd_snapin_shmem fd_snapin_shmem_t;
281 :
282 : struct fd_snapin_tile {
283 : int state;
284 : uint full : 1; /* loading a full snapshot? */
285 : int alpenglow;
286 :
287 : fd_snapin_lead_t lead;
288 :
289 : ulong tile_idx; /* tile kind ID */
290 : ulong lane_cnt;
291 : ulong expected_frame;
292 : ulong pending_control; /* control message expected from snapdc tiles */
293 : uchar control_seen[ FD_TOPO_MAX_TILE_IN_LINKS ];
294 :
295 : fd_accdb_t * accdb;
296 :
297 : /* Shared stake data updated by every tile. */
298 : fd_stake_delegations_t * stake_delegations;
299 :
300 : fd_ssparse_t ssparse[1];
301 :
302 : struct {
303 : ulong full_bytes_read;
304 : ulong incremental_bytes_read;
305 :
306 : /* Account counters (full + incremental) */
307 : ulong accounts_loaded;
308 : ulong accounts_replaced;
309 : ulong accounts_ignored;
310 :
311 : /* Account counters (snapshot taken for full snapshot only) */
312 : ulong full_accounts_loaded;
313 : ulong full_accounts_replaced;
314 : ulong full_accounts_ignored;
315 :
316 : /* Persistent counters */
317 : ulong total_accounts_processed;
318 : ulong total_account_batches_processed;
319 : ulong disk_bytes_written;
320 : } metrics;
321 :
322 : struct {
323 : fd_wksp_t * wksp;
324 : ulong chunk0;
325 : ulong wmark;
326 : ulong mtu;
327 : ulong pos;
328 : } in[ FD_TOPO_MAX_TILE_IN_LINKS ];
329 :
330 : fd_snapin_out_link_t ct_out;
331 : fd_snapin_out_link_t gui_out;
332 :
333 : /* Shared snapshot state. */
334 : fd_snapin_shmem_t * shmem;
335 :
336 : /* Parse state for one attempt. */
337 : ulong appendvec_seq; /* next appendvec number */
338 : ulong claimed_appendvec; /* current claim */
339 : ulong incr_fork; /* insert fork; USHORT_MAX for full */
340 :
341 : struct {
342 : uchar buf[ FD_SNAPIN_WRITE_BUF_SZ ] __attribute__((aligned(FD_SNAPIN_DIRECT_ALIGN)));
343 : ulong buf_used;
344 : int accdb_direct_fd; /* O_DIRECT fd to accounts.db */
345 : fd_snapin_account_batch_t batch;
346 : } writer;
347 :
348 : /* Buffer streamed account data before inserting. */
349 : struct {
350 : int executable;
351 : ulong slot;
352 : ulong lamports;
353 : ulong data_len;
354 : ulong bytes_received;
355 : uchar pubkey[ 32UL ];
356 : uchar owner [ 32UL ];
357 : uchar data[ FD_RUNTIME_ACC_SZ_MAX ] __attribute__((aligned(64)));
358 : } staged;
359 :
360 : ulong wfs_slot;
361 : fd_hash_t wfs_bank_hash;
362 : ushort wfs_shred_version;
363 : int wfs_hash_is_zero;
364 : };
365 :
366 : typedef struct fd_snapin_tile fd_snapin_tile_t;
367 :
368 : static inline int
369 0 : is_lead( fd_snapin_tile_t const * ctx ) {
370 0 : return ctx->tile_idx==0UL;
371 0 : }
372 :
373 : static void
374 0 : format_count( char * out, ulong out_sz, ulong n ) {
375 0 : if( n>=1000000UL ) FD_TEST( fd_cstr_printf_check( out, out_sz, NULL, "%.1fM", (double)n/1e6 ) );
376 0 : else if( n>=1000UL ) FD_TEST( fd_cstr_printf_check( out, out_sz, NULL, "%.1fK", (double)n/1e3 ) );
377 0 : else FD_TEST( fd_cstr_printf_check( out, out_sz, NULL, "%lu", n ) );
378 0 : }
379 :
380 : static inline int
381 0 : should_shutdown( fd_snapin_tile_t * ctx ) {
382 0 : if( FD_UNLIKELY( ctx->state==FD_SNAPSHOT_STATE_SHUTDOWN && is_lead( ctx ) ) ) {
383 0 : long elapsed_ns = fd_log_wallclock() - ctx->lead.boot_timestamp;
384 0 : char loaded_buf[ 32 ];
385 0 : char dup_buf [ 32 ];
386 0 : format_count( loaded_buf, sizeof(loaded_buf), ctx->lead.account_counts.loaded );
387 0 : format_count( dup_buf, sizeof(dup_buf), ctx->lead.account_counts.duplicates );
388 0 : FD_LOG_NOTICE(( "loaded %s accounts %s(%s dups)%s from snapshot in %.3f seconds",
389 0 : loaded_buf, fd_log_style_dim(), dup_buf, fd_log_style_normal(), (double)elapsed_ns/1e9 ));
390 0 : }
391 0 : return ctx->state==FD_SNAPSHOT_STATE_SHUTDOWN;
392 0 : }
393 :
394 : static ulong
395 0 : scratch_align( void ) {
396 0 : return FD_SNAPIN_DIRECT_ALIGN;
397 0 : }
398 :
399 : static ulong
400 0 : scratch_footprint( fd_topo_tile_t const * tile ) {
401 0 : ulong l = FD_LAYOUT_INIT;
402 0 : l = FD_LAYOUT_APPEND( l, alignof(fd_snapin_tile_t), sizeof(fd_snapin_tile_t) );
403 0 : l = FD_LAYOUT_APPEND( l, fd_accdb_align(), fd_accdb_footprint( tile->snapin.max_live_slots, 0 ) );
404 :
405 : /* Only tile 0 publishes the manifest */
406 0 : if( FD_LIKELY( !tile->kind_id ) ) {
407 0 : l = FD_LAYOUT_APPEND( l, fd_txncache_align(), fd_txncache_footprint( tile->snapin.max_live_slots ) );
408 0 : l = FD_LAYOUT_APPEND( l, fd_ssmanifest_parser_align(), fd_ssmanifest_parser_footprint() );
409 0 : l = FD_LAYOUT_APPEND( l, fd_slot_delta_parser_align(), fd_slot_delta_parser_footprint() );
410 0 : l = FD_LAYOUT_APPEND( l, alignof(recent_blockhash_group_t), sizeof(recent_blockhash_group_t)*FD_SNAPIN_MAX_RECENT_GROUPS );
411 0 : l = FD_LAYOUT_APPEND( l, alignof(fd_sstxncache_hash_t), sizeof(fd_sstxncache_hash_t)*FD_TXNCACHE_MAX_SLOT_DELTAS*2UL*tile->snapin.max_txn_per_slot );
412 0 : }
413 0 : return FD_LAYOUT_FINI( l, scratch_align() );
414 0 : }
415 :
416 : static void
417 0 : metrics_write( fd_snapin_tile_t * ctx ) {
418 0 : fd_accdb_flush_metrics( ctx->accdb );
419 :
420 0 : FD_MGAUGE_SET( SNAPIN, STREAM_STATE, (ulong)ctx->state );
421 0 : FD_MGAUGE_SET( SNAPIN, PARSE_PROGRESS_BYTES_FULL, ctx->metrics.full_bytes_read );
422 0 : FD_MGAUGE_SET( SNAPIN, PARSE_PROGRESS_BYTES_INCREMENTAL, ctx->metrics.incremental_bytes_read );
423 0 : FD_MCNT_SET ( SNAPIN, DISK_WRITTEN_BYTES, ctx->metrics.disk_bytes_written );
424 0 : FD_MGAUGE_SET( SNAPIN, ACCOUNT_PROGRESS_NEW, ctx->metrics.accounts_loaded );
425 0 : FD_MGAUGE_SET( SNAPIN, ACCOUNT_PROGRESS_REPLACED, ctx->metrics.accounts_replaced );
426 0 : FD_MGAUGE_SET( SNAPIN, ACCOUNT_PROGRESS_IGNORED, ctx->metrics.accounts_ignored );
427 0 : FD_MCNT_SET ( SNAPIN, ACCOUNT_PROCESSED, ctx->metrics.total_accounts_processed );
428 0 : FD_MCNT_SET ( SNAPIN, ACCOUNT_BATCH_PROCESSED, ctx->metrics.total_account_batches_processed );
429 0 : }
430 :
431 : /* verify_slot_deltas_with_slot_history verifies the 'SlotHistory'
432 : sysvar account (data, data_len) after loading a snapshot. Returns 0
433 : if verification passed, -1 if not. */
434 :
435 : static int
436 : verify_slot_deltas_with_slot_history( fd_snapin_tile_t * ctx,
437 : uchar const * data,
438 0 : ulong data_len ) {
439 0 : if( FD_UNLIKELY( data_len!=FD_SYSVAR_SLOT_HISTORY_BINCODE_SZ ) ) {
440 0 : FD_LOG_WARNING(( "SlotHistory sysvar account data size is %lu, expected %lu", data_len, FD_SYSVAR_SLOT_HISTORY_BINCODE_SZ ));
441 0 : return -1;
442 0 : }
443 :
444 0 : fd_slot_history_view_t view[1];
445 0 : if( FD_UNLIKELY( !fd_sysvar_slot_history_view( view, data, data_len ) ) ) {
446 0 : FD_LOG_WARNING(( "SlotHistory sysvar account data is corrupt" ));
447 0 : return -1;
448 0 : }
449 :
450 : /* Sanity checks for slot history:
451 : https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/snapshot_bank_utils.rs#L586 */
452 :
453 0 : ulong newest_slot = view->next_slot - 1UL;
454 0 : if( FD_UNLIKELY( newest_slot!=ctx->lead.bank_slot ) ) {
455 : /* VerifySlotHistoryError::InvalidNewestSlot
456 : https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/snapshot_bank_utils.rs#L621 */
457 0 : FD_LOG_WARNING(( "SlotHistory sysvar has an invalid newest slot: %lu != bank slot: %lu", newest_slot, ctx->lead.bank_slot ));
458 0 : return -1;
459 0 : }
460 :
461 0 : if( FD_UNLIKELY( view->bits_len!=FD_SLOT_HISTORY_MAX_ENTRIES ) ) {
462 : /* VerifySlotHistoryError::InvalidNumEntries
463 : https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/snapshot_bank_utils.rs#L625 */
464 0 : FD_LOG_WARNING(( "SlotHistory sysvar has invalid number of entries: %lu != expected: %lu", view->bits_len, FD_SLOT_HISTORY_MAX_ENTRIES ));
465 0 : return -1;
466 0 : }
467 :
468 : /* Stricter than Agave, which only checks bits_len (the bv crate
469 : merely requires bits_len<=blocks_len*64). An exact block count is
470 : what makes fd_sysvar_slot_history_find_slot's (slot/64)%blocks_len
471 : indexing agree with Agave's bits.get(slot%MAX_ENTRIES); the runtime
472 : always writes exactly this many blocks. */
473 0 : if( FD_UNLIKELY( view->blocks_len!=FD_SLOT_HISTORY_MAX_ENTRIES/64UL ) ) {
474 0 : FD_LOG_WARNING(( "SlotHistory sysvar has invalid bitvec block count: %lu != expected: %lu", view->blocks_len, FD_SLOT_HISTORY_MAX_ENTRIES/64UL ));
475 0 : return -1;
476 0 : }
477 :
478 : /* All slots in slot deltas should be present in the slot history */
479 0 : fd_slot_delta_slot_set_t slot_set = fd_slot_delta_parser_slot_set( ctx->lead.slot_delta_parser );
480 0 : for( ulong i=0UL; i<slot_set.ele_cnt; i++ ) {
481 0 : ulong slot = slot_set.pool[ i ].slot;
482 0 : if( FD_UNLIKELY( fd_sysvar_slot_history_find_slot( view, slot )!=FD_SLOT_HISTORY_SLOT_FOUND ) ) {
483 : /* VerifySlotDeltasError::SlotNotFoundInHistory
484 : https://github.com/anza-xyz/agave/blob/v3.1.8/snapshots/src/error.rs#L144
485 : https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/snapshot_bank_utils.rs#L593 */
486 0 : FD_LOG_WARNING(( "slot %lu missing from SlotHistory sysvar account", slot ));
487 0 : return -1;
488 0 : }
489 0 : }
490 :
491 0 : ulong scan_cnt = fd_ulong_min( view->next_slot, FD_SLOT_HISTORY_MAX_ENTRIES );
492 0 : ulong found_cnt = 0UL;
493 0 : for( ulong i=0UL; i<scan_cnt && found_cnt<FD_SLOT_DELTA_MAX_ENTRIES; i++ ) {
494 0 : ulong slot = newest_slot - i;
495 0 : if( FD_UNLIKELY( fd_sysvar_slot_history_find_slot( view, slot )!=FD_SLOT_HISTORY_SLOT_FOUND ) ) continue;
496 0 : found_cnt++;
497 0 : if( FD_UNLIKELY( slot_set_ele_query( slot_set.map, &slot, NULL, slot_set.pool )==NULL ) ) {
498 : /* VerifySlotDeltasError::SlotNotFoundInDeltas
499 : https://github.com/anza-xyz/agave/blob/v3.1.8/snapshots/src/error.rs#L147
500 : https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/snapshot_bank_utils.rs#L609 */
501 0 : FD_LOG_WARNING(( "slot %lu missing from slot deltas but present in SlotHistory", slot ));
502 0 : return -1;
503 0 : }
504 0 : }
505 :
506 0 : return 0;
507 0 : }
508 :
509 : /* Sysvar accounts checked by verify_sysvars. Agave requires Rent at
510 : restore; Firedancer also needs Clock and SlotHistory. The rest are
511 : recreated by the runtime if absent. */
512 :
513 : struct snapin_sysvar {
514 : fd_pubkey_t const * id;
515 : char const * name;
516 : int required;
517 : };
518 : typedef struct snapin_sysvar snapin_sysvar_t;
519 :
520 : static snapin_sysvar_t const snapin_sysvar_tbl[ FD_SYSVAR_CACHE_ENTRY_CNT ] = {
521 : [ FD_SYSVAR_clock_IDX ] = { &fd_sysvar_clock_id, "Clock", 1 },
522 : [ FD_SYSVAR_epoch_rewards_IDX ] = { &fd_sysvar_epoch_rewards_id, "EpochRewards", 0 },
523 : [ FD_SYSVAR_epoch_schedule_IDX ] = { &fd_sysvar_epoch_schedule_id, "EpochSchedule", 0 },
524 : [ FD_SYSVAR_last_restart_slot_IDX ] = { &fd_sysvar_last_restart_slot_id, "LastRestartSlot", 0 },
525 : [ FD_SYSVAR_recent_hashes_IDX ] = { &fd_sysvar_recent_block_hashes_id, "RecentBlockhashes", 0 },
526 : [ FD_SYSVAR_rent_IDX ] = { &fd_sysvar_rent_id, "Rent", 1 },
527 : [ FD_SYSVAR_slot_hashes_IDX ] = { &fd_sysvar_slot_hashes_id, "SlotHashes", 0 },
528 : [ FD_SYSVAR_slot_history_IDX ] = { &fd_sysvar_slot_history_id, "SlotHistory", 1 },
529 : [ FD_SYSVAR_stake_history_IDX ] = { &fd_sysvar_stake_history_id, "StakeHistory", 0 },
530 : };
531 :
532 : /* Rent::try_minimum_balance bounds
533 : https://github.com/anza-xyz/solana-sdk/blob/rent%40v4.4.0/rent/src/lib.rs#L187-L204 */
534 :
535 : #define SNAPIN_RENT_MAX_LAMPORTS_PER_BYTE_THRESHOLD_1 (1759197129867UL)
536 : #define SNAPIN_RENT_MAX_LAMPORTS_PER_BYTE_THRESHOLD_2 ( 879598564933UL)
537 :
538 : static int
539 0 : verify_rent( fd_sysvar_cache_t const * cache ) {
540 0 : fd_rent_t rent[1];
541 0 : fd_sysvar_cache_rent_read( cache, rent ); /* required */
542 0 : ulong threshold_bits = fd_dblbits( rent->exemption_threshold );
543 0 : if( FD_UNLIKELY( ( threshold_bits==fd_dblbits( 1.0 ) && rent->lamports_per_uint8_year>SNAPIN_RENT_MAX_LAMPORTS_PER_BYTE_THRESHOLD_1 ) ||
544 0 : ( threshold_bits==fd_dblbits( 2.0 ) && rent->lamports_per_uint8_year>SNAPIN_RENT_MAX_LAMPORTS_PER_BYTE_THRESHOLD_2 ) ) ) {
545 0 : FD_LOG_WARNING(( "Rent sysvar lamports_per_byte %lu overflows minimum_balance for exemption_threshold %g",
546 0 : rent->lamports_per_uint8_year, rent->exemption_threshold ));
547 0 : return -1;
548 0 : }
549 0 : return 0;
550 0 : }
551 :
552 : /* fd_sysvar_slot_hashes_update needs the full-size account */
553 :
554 : static int
555 : verify_slot_hashes( fd_sysvar_cache_t const * cache,
556 0 : ulong data_len ) {
557 0 : if( FD_UNLIKELY( fd_sysvar_cache_slot_hashes_is_valid( cache ) && data_len<FD_SYSVAR_SLOT_HASHES_BINCODE_SZ ) ) {
558 0 : FD_LOG_WARNING(( "SlotHashes sysvar account data size is %lu, expected at least %lu",
559 0 : data_len, FD_SYSVAR_SLOT_HASHES_BINCODE_SZ ));
560 0 : return -1;
561 0 : }
562 0 : return 0;
563 0 : }
564 :
565 : /* An active EpochRewards sysvar drives fd_rewards_recalculate_partitioned_rewards
566 : at boot; check what that path asserts. */
567 :
568 : static int
569 : verify_epoch_rewards( fd_snapin_tile_t const * ctx,
570 : fd_sysvar_cache_t const * cache,
571 0 : ulong data_len ) {
572 0 : fd_sysvar_epoch_rewards_t rewards[1];
573 0 : if( !fd_sysvar_cache_epoch_rewards_read( cache, rewards ) || !rewards->active ) return 0;
574 :
575 : /* fd_sysvar_epoch_rewards_read requires the exact size */
576 0 : if( FD_UNLIKELY( data_len!=FD_SYSVAR_EPOCH_REWARDS_BINCODE_SZ ) ) {
577 0 : FD_LOG_WARNING(( "EpochRewards sysvar account data size is %lu, expected %lu",
578 0 : data_len, FD_SYSVAR_EPOCH_REWARDS_BINCODE_SZ ));
579 0 : return -1;
580 0 : }
581 : /* https://github.com/anza-xyz/agave/blob/v4.4.0-alpha.4/runtime/src/bank/partitioned_epoch_rewards/sysvar.rs#L117 */
582 0 : if( FD_UNLIKELY( rewards->distributed_rewards>rewards->total_rewards ) ) {
583 0 : FD_LOG_WARNING(( "EpochRewards sysvar distributed rewards %lu exceed total rewards %lu",
584 0 : rewards->distributed_rewards, rewards->total_rewards ));
585 0 : return -1;
586 0 : }
587 : /* Bounds asserted by fd_stake_rewards_init and
588 : fd_distribute_partitioned_epoch_rewards */
589 0 : ulong epoch_slot_cnt = fd_epoch_slot_cnt( &ctx->lead.epoch_schedule, ctx->lead.epoch );
590 0 : if( FD_UNLIKELY( !rewards->num_partitions ||
591 0 : rewards->num_partitions>MAX_PARTITIONS_PER_EPOCH ||
592 0 : rewards->num_partitions>=epoch_slot_cnt ) ) {
593 0 : FD_LOG_WARNING(( "EpochRewards sysvar has invalid partition count %lu (epoch has %lu slots)",
594 0 : rewards->num_partitions, epoch_slot_cnt ));
595 0 : return -1;
596 0 : }
597 0 : if( FD_UNLIKELY( rewards->distribution_starting_block_height>ULONG_MAX-rewards->num_partitions ) ) {
598 0 : FD_LOG_WARNING(( "EpochRewards sysvar distribution starting block height %lu overflows with %lu partitions",
599 0 : rewards->distribution_starting_block_height, rewards->num_partitions ));
600 0 : return -1;
601 0 : }
602 : /* read_stake_history in fd_rewards.c aborts without it */
603 0 : if( FD_UNLIKELY( !fd_sysvar_cache_stake_history_is_valid( cache ) ) ) {
604 0 : FD_LOG_WARNING(( "EpochRewards sysvar is active but the StakeHistory sysvar account is not present" ));
605 0 : return -1;
606 0 : }
607 0 : return 0;
608 0 : }
609 :
610 : /* verify_sysvars reads the sysvar accounts back from the accounts
611 : database and checks they decode and satisfy the invariants replay
612 : asserts at boot. Call after all FINI acks. Returns 0 on success,
613 : -1 on failure. */
614 :
615 : static int
616 0 : verify_sysvars( fd_snapin_tile_t * ctx ) {
617 0 : fd_accdb_fork_id_t fork_id = ctx->full ? ctx->lead.accdb_root_fork_id
618 0 : : ctx->lead.accdb_incr_fork_id;
619 0 : fd_sysvar_cache_t * cache = fd_sysvar_cache_join( fd_sysvar_cache_new( ctx->lead.sysvar_cache ) );
620 :
621 0 : ulong data_lens[ FD_SYSVAR_CACHE_ENTRY_CNT ] = {0}; /* untruncated */
622 :
623 0 : for( ulong i=0UL; i<FD_SYSVAR_CACHE_ENTRY_CNT; i++ ) {
624 0 : snapin_sysvar_t const * sysvar = &snapin_sysvar_tbl[ i ];
625 :
626 0 : ulong lamports;
627 0 : ulong data_len;
628 0 : int executable;
629 0 : uchar owner[ 32UL ];
630 0 : int source = fd_accdb_read_one_nocache( ctx->accdb, fork_id, sysvar->id->uc,
631 0 : &lamports, &executable, owner,
632 0 : ctx->staged.data, &data_len );
633 0 : if( source==FD_ACCDB_READ_ONE_NOCACHE_MISS ) {
634 0 : if( FD_UNLIKELY( sysvar->required ) ) {
635 0 : FD_LOG_WARNING(( "%s sysvar account was not present in the accounts database", sysvar->name ));
636 0 : return -1;
637 0 : }
638 0 : continue;
639 0 : }
640 :
641 0 : if( FD_UNLIKELY( !fd_memeq( owner, fd_sysvar_owner_id.uc, sizeof(fd_pubkey_t) ) ) ) {
642 0 : FD_BASE58_ENCODE_32_BYTES( owner, owner_b58 );
643 0 : FD_LOG_WARNING(( "%s sysvar owner is invalid: %s != sysvar_owner_id", sysvar->name, owner_b58 ));
644 0 : return -1;
645 0 : }
646 :
647 : /* Same decode as fd_sysvar_cache_restore at boot */
648 0 : fd_sysvar_cache_restore_one( cache, sysvar->id, lamports, ctx->staged.data, data_len );
649 0 : ulong cached_sz;
650 0 : if( FD_UNLIKELY( !fd_sysvar_cache_data_query( cache, sysvar->id->uc, &cached_sz ) ) ) {
651 0 : FD_LOG_WARNING(( "%s sysvar account data is corrupt (data_len=%lu)", sysvar->name, data_len ));
652 0 : return -1;
653 0 : }
654 :
655 0 : data_lens[ i ] = data_len;
656 0 : }
657 :
658 0 : if( FD_UNLIKELY( verify_rent ( cache ) ) ) return -1;
659 0 : if( FD_UNLIKELY( verify_slot_hashes ( cache, data_lens[ FD_SYSVAR_slot_hashes_IDX ] ) ) ) return -1;
660 0 : if( FD_UNLIKELY( verify_epoch_rewards( ctx, cache, data_lens[ FD_SYSVAR_epoch_rewards_IDX ] ) ) ) return -1;
661 :
662 0 : ulong slot_history_sz;
663 0 : uchar const * slot_history = fd_sysvar_cache_data_query( cache, fd_sysvar_slot_history_id.uc, &slot_history_sz );
664 0 : return verify_slot_deltas_with_slot_history( ctx, slot_history, data_lens[ FD_SYSVAR_slot_history_IDX ] );
665 0 : }
666 :
667 : /* verification of epoch stakes from manifest
668 : https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/snapshot_bank_utils.rs#L632 */
669 : static int
670 0 : verify_epoch_stakes( fd_snapshot_manifest_t const * manifest ) {
671 0 : fd_epoch_schedule_t epoch_schedule = (fd_epoch_schedule_t){
672 0 : .slots_per_epoch = manifest->epoch_schedule_params.slots_per_epoch,
673 0 : .leader_schedule_slot_offset = manifest->epoch_schedule_params.leader_schedule_slot_offset,
674 0 : .warmup = manifest->epoch_schedule_params.warmup,
675 0 : .first_normal_epoch = manifest->epoch_schedule_params.first_normal_epoch,
676 0 : .first_normal_slot = manifest->epoch_schedule_params.first_normal_slot,
677 0 : };
678 :
679 0 : ulong min_required_epoch = fd_slot_to_epoch( &epoch_schedule, manifest->slot, NULL );
680 0 : ulong max_required_epoch = fd_slot_to_leader_schedule_epoch( &epoch_schedule, manifest->slot );
681 :
682 : /* ensure all required epochs are present in epoch stakes */
683 0 : for( ulong i=min_required_epoch; i<=max_required_epoch; i++ ) {
684 0 : int found = 0;
685 0 : for( ulong j=0UL; j<FD_RUNTIME_MANIFEST_EPOCH_STAKES_LEN; j++ ) {
686 0 : if( manifest->epoch_stakes[j].epoch==i ) {
687 0 : found = 1;
688 0 : break;
689 0 : }
690 0 : }
691 :
692 0 : if( FD_UNLIKELY( !found ) ) {
693 : /* VerifyEpochStakesError::StakesNotFound
694 : https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/snapshot_bank_utils.rs#L667 */
695 0 : FD_LOG_WARNING(( "stakes not found for epoch %lu in manifest", i ));
696 0 : return -1;
697 0 : }
698 0 : }
699 :
700 0 : return 0;
701 0 : }
702 :
703 : static int
704 : verify_slot_deltas_with_bank_slot( fd_snapin_tile_t * ctx,
705 0 : ulong bank_slot ) {
706 0 : fd_slot_delta_slot_set_t slot_set = fd_slot_delta_parser_slot_set( ctx->lead.slot_delta_parser );
707 0 : for( ulong i=0UL; i<slot_set.ele_cnt; i++ ) {
708 0 : ulong slot = slot_set.pool[ i ].slot;
709 : /* VerifySlotDeltasError::SlotGreaterThanMaxRoot
710 : https://github.com/anza-xyz/agave/blob/v3.1.8/snapshots/src/error.rs#L138
711 : https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/snapshot_bank_utils.rs#L550 */
712 0 : if( FD_UNLIKELY( slot>bank_slot ) ) {
713 0 : FD_LOG_WARNING(( "entry slot %lu is greater than bank slot %lu", slot, bank_slot ));
714 0 : return -1;
715 0 : }
716 0 : }
717 0 : return 0;
718 0 : }
719 :
720 : static int
721 : verify_bank_hash( fd_snapin_tile_t const * ctx,
722 0 : fd_snapshot_manifest_t const * manifest ) {
723 0 : if( FD_UNLIKELY( manifest->blockhashes_len==0UL ) ) {
724 0 : FD_LOG_WARNING(( "%s manifest for epoch %lu and slot %lu has no blockhashes",
725 0 : ctx->full?"full":"incr", ctx->lead.epoch, manifest->slot ));
726 0 : return -1;
727 0 : }
728 :
729 0 : if( FD_UNLIKELY( !manifest->has_accounts_lthash ) ) {
730 0 : FD_LOG_WARNING(( "%s manifest for epoch %lu and slot %lu is missing accounts lthash",
731 0 : ctx->full?"full":"incr", ctx->lead.epoch, manifest->slot ));
732 0 : return -1;
733 0 : }
734 :
735 : /* find the last blockhash */
736 0 : ulong max_hash_idx = 0UL;
737 0 : ulong last_bh_idx = 0UL;
738 0 : for( ulong i=0UL; i<manifest->blockhashes_len; i++ ) {
739 0 : if( FD_LIKELY( manifest->blockhashes[ i ].hash_index > max_hash_idx ) ) {
740 0 : max_hash_idx = manifest->blockhashes[ i ].hash_index;
741 0 : last_bh_idx = i;
742 0 : }
743 0 : }
744 :
745 : /* fd_lthash_value_t is aligned to 64B but the accounts_lthash in the
746 : manifest may not be because its simply a uchar array. Copy is
747 : needed to avoid undefined behavior. */
748 0 : fd_lthash_value_t accounts_lthash[ 1UL ];
749 0 : fd_memcpy( accounts_lthash, manifest->accounts_lthash, sizeof(fd_lthash_value_t) );
750 :
751 0 : fd_hash_t const * parent_bank_hash = (fd_hash_t const *)fd_type_pun_const( manifest->parent_bank_hash );
752 0 : fd_hash_t const * last_blockhash = (fd_hash_t const *)fd_type_pun_const( manifest->blockhashes[ last_bh_idx ].hash );
753 0 : fd_hash_t computed_bank_hash[ 1UL ];
754 0 : fd_hashes_hash_bank( accounts_lthash, parent_bank_hash, last_blockhash, manifest->signature_count, computed_bank_hash );
755 0 : fd_hashes_apply_hard_forks(
756 0 : computed_bank_hash,
757 0 : manifest->slot,
758 0 : manifest->parent_slot,
759 0 : manifest->hard_forks,
760 0 : manifest->hard_fork_cnt );
761 :
762 0 : if( FD_UNLIKELY( memcmp( computed_bank_hash, manifest->bank_hash, FD_HASH_FOOTPRINT ) ) ) {
763 0 : FD_BASE58_ENCODE_32_BYTES( computed_bank_hash->hash, computed_bank_hash_enc );
764 0 : FD_BASE58_ENCODE_32_BYTES( manifest->bank_hash, manifest_bank_hash_enc );
765 0 : FD_LOG_WARNING(( "%s manifest for epoch %lu and slot %lu bank hash verification failed: computed %s does not match manifest %s",
766 0 : ctx->full?"full":"incr", ctx->lead.epoch, manifest->slot,
767 0 : computed_bank_hash_enc, manifest_bank_hash_enc ));
768 0 : return -1;
769 0 : }
770 :
771 0 : return 0;
772 0 : }
773 :
774 : static inline void
775 0 : clear_control_barrier( fd_snapin_tile_t * ctx ) {
776 0 : ctx->pending_control = ULONG_MAX;
777 0 : fd_memset( ctx->control_seen, 0, sizeof(ctx->control_seen) );
778 0 : }
779 :
780 : static void
781 : transition_malformed( fd_snapin_tile_t * ctx,
782 0 : fd_stem_context_t * stem ) {
783 0 : if( FD_UNLIKELY( ctx->state==FD_SNAPSHOT_STATE_ERROR ) ) return;
784 0 : ctx->state = FD_SNAPSHOT_STATE_ERROR;
785 0 : fd_stem_publish( stem, ctx->ct_out.idx, FD_SNAPSHOT_MSG_CTRL_ERROR, 0UL, 0UL, 0UL, 0UL, 0UL );
786 0 : }
787 :
788 : static blockhash_group_t *
789 : txncache_staging_groups_join( void * scratch,
790 : ulong scratch_sz,
791 0 : ulong groups_max ) {
792 0 : ulong start = fd_ulong_align_up( (ulong)scratch, alignof(blockhash_group_t) );
793 0 : ulong pad = start-(ulong)scratch;
794 0 : if( FD_UNLIKELY( pad>scratch_sz ) ) return NULL;
795 0 : if( FD_UNLIKELY( scratch_sz-pad<groups_max*sizeof(blockhash_group_t) ) ) return NULL;
796 0 : return (blockhash_group_t *)start;
797 0 : }
798 :
799 : static blockhash_group_t *
800 0 : txncache_staging_scratch( fd_snapin_tile_t * ctx ) {
801 0 : ulong scratch_sz;
802 0 : void * scratch = fd_txncache_snapin_scratch( ctx->lead.txncache, &scratch_sz );
803 0 : ulong groups_max = FD_TXNCACHE_MAX_SLOT_DELTAS*ctx->lead.txncache_max_groups_per_slot;
804 0 : blockhash_group_t * groups = txncache_staging_groups_join( scratch, scratch_sz, groups_max );
805 0 : if( FD_UNLIKELY( !groups ) ) FD_LOG_ERR(( "txncache scratch (%lu bytes) too small to stage %lu blockhash groups (%lu bytes)", scratch_sz, groups_max, groups_max*sizeof(blockhash_group_t) ));
806 0 : return groups;
807 0 : }
808 :
809 : static void
810 0 : txncache_staging_reset( fd_snapin_tile_t * ctx ) {
811 0 : ctx->lead.blockhash_groups_cnt = 0UL;
812 0 : ctx->lead.recent_groups_len = 0UL;
813 0 : ctx->lead.txncache_slots_len = 0UL;
814 0 : ctx->lead.txncache_current_slot_entry_cnt = 0UL;
815 0 : ctx->lead.txncache_current_slot_idx = ULONG_MAX;
816 0 : ctx->lead.txncache_current_slot_group_cnt = 0UL;
817 0 : }
818 :
819 : static ulong
820 : txncache_staging_slot_begin( fd_snapin_tile_t * ctx,
821 0 : ulong slot ) {
822 0 : ulong candidate_idx;
823 0 : if( FD_LIKELY( ctx->lead.txncache_slots_len<FD_TXNCACHE_MAX_SLOT_DELTAS ) ) {
824 0 : candidate_idx = ctx->lead.txncache_slots_len++;
825 0 : } else {
826 0 : candidate_idx = 0UL;
827 0 : for( ulong i=1UL; i<FD_TXNCACHE_MAX_SLOT_DELTAS; i++ ) {
828 0 : if( ctx->lead.txncache_slots[ i ].slot<ctx->lead.txncache_slots[ candidate_idx ].slot ) candidate_idx = i;
829 0 : }
830 0 : if( FD_UNLIKELY( slot<ctx->lead.txncache_slots[ candidate_idx ].slot ) ) candidate_idx = ULONG_MAX;
831 0 : }
832 :
833 0 : if( FD_LIKELY( candidate_idx!=ULONG_MAX ) ) {
834 0 : ctx->lead.txncache_slots[ candidate_idx ].slot = slot;
835 0 : ctx->lead.txncache_slots[ candidate_idx ].entry_cnt = 0UL;
836 0 : ctx->lead.txncache_slots[ candidate_idx ].group_cnt = 0UL;
837 0 : }
838 0 : ctx->lead.txncache_current_slot_idx = candidate_idx;
839 0 : ctx->lead.txncache_current_slot_entry_cnt = 0UL;
840 0 : ctx->lead.txncache_current_slot_group_cnt = 0UL;
841 0 : return candidate_idx;
842 0 : }
843 :
844 : static int
845 : txncache_staging_group_begin( fd_snapin_tile_t * ctx,
846 : uchar const * blockhash,
847 0 : ulong txnhash_offset ) {
848 0 : if( FD_UNLIKELY( ctx->lead.txncache_current_slot_group_cnt>=ctx->lead.txncache_max_groups_per_slot ) ) return -1;
849 0 : ctx->lead.txncache_current_slot_group_cnt++;
850 0 : ctx->lead.blockhash_groups_cnt++;
851 :
852 0 : ulong slot_idx = ctx->lead.txncache_current_slot_idx;
853 0 : if( FD_UNLIKELY( slot_idx==ULONG_MAX ) ) return 0;
854 :
855 0 : FD_TEST( slot_idx<ctx->lead.txncache_slots_len );
856 0 : txncache_staging_slot_t * staging_slot = &ctx->lead.txncache_slots[ slot_idx ];
857 0 : FD_TEST( staging_slot->group_cnt<ctx->lead.txncache_max_groups_per_slot );
858 0 : blockhash_group_t * group = &ctx->lead.blockhash_groups[ slot_idx*ctx->lead.txncache_max_groups_per_slot+staging_slot->group_cnt ];
859 0 : memcpy( group->blockhash, blockhash, 32UL );
860 0 : group->txnhash_offset = (uint)txnhash_offset;
861 0 : group->txncache_entry_cnt = 0U;
862 0 : staging_slot->group_cnt++;
863 0 : return 0;
864 0 : }
865 :
866 : static int
867 : txncache_staging_entry_add( fd_snapin_tile_t * ctx,
868 : ulong slot,
869 0 : uchar const * txnhash ) {
870 0 : if( FD_UNLIKELY( ctx->lead.txncache_current_slot_entry_cnt>=ctx->lead.txncache_max_entries_per_slot ) ) return -1;
871 0 : ctx->lead.txncache_current_slot_entry_cnt++;
872 :
873 0 : ulong slot_idx = ctx->lead.txncache_current_slot_idx;
874 0 : if( FD_UNLIKELY( slot_idx==ULONG_MAX ) ) return 0; /* discarded older delta */
875 :
876 0 : FD_TEST( slot_idx<ctx->lead.txncache_slots_len );
877 0 : txncache_staging_slot_t * staging_slot = &ctx->lead.txncache_slots[ slot_idx ];
878 0 : FD_TEST( staging_slot->slot==slot );
879 0 : FD_TEST( staging_slot->group_cnt );
880 0 : FD_TEST( staging_slot->entry_cnt<ctx->lead.txncache_max_entries_per_slot );
881 0 : blockhash_group_t * group = &ctx->lead.blockhash_groups[ slot_idx*ctx->lead.txncache_max_groups_per_slot+staging_slot->group_cnt-1UL ];
882 0 : memcpy( ctx->lead.txncache_entries[ slot_idx*ctx->lead.txncache_max_entries_per_slot+staging_slot->entry_cnt ].txnhash, txnhash, sizeof(fd_sstxncache_hash_t) );
883 0 : staging_slot->entry_cnt++;
884 0 : group->txncache_entry_cnt++;
885 0 : return 0;
886 0 : }
887 :
888 : static ulong
889 : txncache_staging_rank_slots( fd_snapin_tile_t const * ctx,
890 0 : ulong execution_bank_i_by_staging_idx[ static FD_TXNCACHE_MAX_SLOT_DELTAS ] ) {
891 0 : ulong staging_slot_cnt = ctx->lead.txncache_slots_len;
892 0 : ulong staging_idx_by_bank_i[ FD_TXNCACHE_MAX_SLOT_DELTAS ];
893 0 : for( ulong staging_idx=0UL; staging_idx<staging_slot_cnt; staging_idx++ ) {
894 0 : ulong bank_i = staging_idx;
895 0 : while( bank_i>0UL && ctx->lead.txncache_slots[ staging_idx_by_bank_i[ bank_i-1UL ] ].slot<ctx->lead.txncache_slots[ staging_idx ].slot ) {
896 0 : staging_idx_by_bank_i[ bank_i ] = staging_idx_by_bank_i[ bank_i-1UL ];
897 0 : bank_i--;
898 0 : }
899 0 : staging_idx_by_bank_i[ bank_i ] = staging_idx;
900 0 : }
901 0 : for( ulong bank_i=0UL; bank_i<staging_slot_cnt; bank_i++ ) {
902 0 : execution_bank_i_by_staging_idx[ staging_idx_by_bank_i[ bank_i ] ] = bank_i;
903 0 : }
904 0 : return staging_slot_cnt ? ctx->lead.txncache_slots[ staging_idx_by_bank_i[ 0UL ] ].slot : ULONG_MAX;
905 0 : }
906 :
907 : static int
908 : txncache_staging_filter_groups( fd_snapin_tile_t * ctx,
909 : blockhash_map_t const * blockhash_map,
910 : fd_blockhash_entry_t const * blockhash_pool,
911 0 : ulong snapshot_slot ) {
912 0 : ulong execution_bank_i_by_staging_idx[ FD_TXNCACHE_MAX_SLOT_DELTAS ];
913 0 : ulong newest_staged_slot = txncache_staging_rank_slots( ctx, execution_bank_i_by_staging_idx );
914 0 : if( FD_UNLIKELY( newest_staged_slot!=ULONG_MAX && newest_staged_slot!=snapshot_slot ) ) {
915 0 : FD_LOG_WARNING(( "corrupt snapshot: newest slot delta is for slot %lu, not the snapshot slot %lu", newest_staged_slot, snapshot_slot ));
916 0 : return 1;
917 0 : }
918 :
919 0 : ctx->lead.recent_groups_len = 0UL;
920 0 : for( ulong staging_idx=0UL; staging_idx<ctx->lead.txncache_slots_len; staging_idx++ ) {
921 0 : txncache_staging_slot_t const * staging_slot = &ctx->lead.txncache_slots[ staging_idx ];
922 0 : blockhash_group_t const * groups = &ctx->lead.blockhash_groups[ staging_idx*ctx->lead.txncache_max_groups_per_slot ];
923 0 : ulong entry_idx = staging_idx*ctx->lead.txncache_max_entries_per_slot;
924 :
925 0 : for( ulong i=0UL; i<staging_slot->group_cnt; i++ ) {
926 0 : blockhash_group_t const * group = &groups[ i ];
927 0 : fd_hash_t key;
928 0 : fd_memcpy( key.uc, group->blockhash, 32UL );
929 0 : fd_blockhash_entry_t const * entry = blockhash_map_ele_query_const( blockhash_map, &key, NULL, blockhash_pool );
930 0 : if( FD_LIKELY( entry ) ) {
931 0 : if( FD_UNLIKELY( ctx->lead.recent_groups_len>=FD_SNAPIN_MAX_RECENT_GROUPS ) ) {
932 0 : FD_LOG_WARNING(( "corrupt snapshot: more than %lu blockhash groups reference recent blockhashes", FD_SNAPIN_MAX_RECENT_GROUPS ));
933 0 : return -1;
934 0 : }
935 0 : recent_blockhash_group_t * recent = &ctx->lead.recent_groups[ ctx->lead.recent_groups_len++ ];
936 0 : recent->blockhash_bank_i = (ulong)(entry-blockhash_pool);
937 0 : recent->execution_slot = staging_slot->slot;
938 0 : recent->execution_bank_i = execution_bank_i_by_staging_idx[ staging_idx ];
939 0 : recent->txnhash_offset = group->txnhash_offset;
940 0 : recent->txncache_entry_idx = entry_idx;
941 0 : recent->txncache_entry_cnt = group->txncache_entry_cnt;
942 0 : }
943 0 : entry_idx += group->txncache_entry_cnt;
944 0 : }
945 0 : FD_TEST( entry_idx==staging_idx*ctx->lead.txncache_max_entries_per_slot+staging_slot->entry_cnt );
946 0 : }
947 0 : return 0;
948 0 : }
949 :
950 : static int
951 : populate_txncache( fd_snapin_tile_t * ctx,
952 : fd_snapshot_manifest_blockhash_t const blockhashes[ static FD_BLOCKHASHES_MAX ],
953 : ulong blockhashes_len,
954 0 : ulong snapshot_slot ) {
955 : /* Our txncache internally contains the fork structure for the chain,
956 : which we need to recreate here. Because snapshots are only served
957 : for rooted slots, there is actually no forking, and the bank forks
958 : are just a single bank, the root, like
959 :
960 : _root
961 :
962 : But the txncache also must contain the 150 more recent banks prior
963 : to the root (151 rooted banks total), looking like,
964 :
965 :
966 : _root_150 -> _root_149 -> ... -> _root_2 -> _root_1 -> _root
967 :
968 : Our txncache is "slot agnostic" meaning there is no concept of a
969 : slot number in it. It just has a fork tree structure. So long as
970 : the fork tree is isomorphic to the actual bank forks, and each bank
971 : has the correct blockhash, it works.
972 :
973 : So the challenge is simply to create this chain of 151 forks in the
974 : txncache, with correct blockhashes, and then insert all the
975 : transactions into it.
976 :
977 : Constructing the chain of blockhashes is easy. It is just the
978 : BLOCKHASH_QUEUE array in the manifest. This array is unfortunately
979 : not sorted and appears in random order, but it has a hash_index
980 : field, starting at some arbitrary offset, so we can back out the
981 : blockhashes we need from this, by first finding the max hash_index
982 : as _max and then collecting hash entries via,
983 :
984 : _root_150 -> _root_149 -> ... -> _root_2 -> _root_1 -> _root
985 : _max-150 -> _max-149 -> ... -> _max-2 -> _max-1 -> _max
986 :
987 : Usually the index is gapless and this is exactly 151 links. An
988 : index can be missing, though: a hole (see fd_blockhashes.h), left
989 : when the same blockhash was registered again and Agave's queue kept
990 : only the newer index. A hole has no blockhash of its own, so it is
991 : not a link. The chain is the live entries in descending hash_index
992 : order, and the recent window is still bounded by index distance, so
993 : it is the live entries within _max-150 ... _max, which may be fewer
994 : than 151 links.
995 :
996 : Now the remaining problem is inserting transactions into this
997 : chain. Remember each transaction needs to be inserted with:
998 :
999 : (a) The fork ID (position of the bank in the chain) it was executed in.
1000 : (b) The blockhash of the bank it referenced.
1001 :
1002 : (b) is trivial to retrieve, as it's in the actual slot_deltas entry
1003 : in the manifest served by Agave. But (a) is mildly annoying. Agave
1004 : serves slot_deltas based on slot, so we need an additional mapping
1005 : from slot to position in our banks chain. It turns out we have to
1006 : go to yet another structure in the manifest to retrieve this, the
1007 : ancestors array. This is just an array of slot values, so we need
1008 : to sort it, and line it up against our banks chain like so (shown
1009 : for the usual gapless case),
1010 :
1011 : _root_150 -> _root_149 -> ... -> _root_2 -> _root_1 -> _root
1012 : _max-150 -> _max-149 -> ... -> _max-2 -> _max-1 -> _max
1013 : _slots_150 -> _slots_149 -> ... -> _slots_2 -> _slots_1 -> _slots
1014 :
1015 : That is what populate does, with one shortcut. Every rooted slot
1016 : with a block has a slot delta, and every rooted block registered
1017 : exactly one blockhash, consuming one hash_index. Both sequences end
1018 : at the snapshot slot, so the slot delta of rank r (newest first)
1019 : executed in the block that registered hash_index _max-r, without
1020 : consulting the ancestors array. That index is turned into a chain
1021 : position through the queue: a live index is its own link, and a
1022 : hole (see fd_blockhashes.h) maps to the nearest newer live link,
1023 : since the block that registered it shares that link's blockhash.
1024 :
1025 : From there we are done.
1026 :
1027 : Well almost ... The Agave status cache decided to only store 20
1028 : bytes for 32 byte transaction hashes to save on memory. That's OK,
1029 : but they didn't just take the first 20 bytes. They instead, for
1030 : each blockhash, take a random offset between 0 and 11, and store
1031 : bytes [ offset, offset+20 ) of the transaction hash. We need to
1032 : know this offset to be able to query the txncache later, so we
1033 : retrieve it from the slot_deltas groups and key it into the bank of
1034 : the referenced blockhash in our chain, checking that every group for
1035 : a blockhash agrees on it. */
1036 :
1037 0 : if( FD_UNLIKELY( blockhashes_len>FD_BLOCKHASHES_MAX ) ) {
1038 0 : FD_LOG_WARNING(( "corrupt snapshot: blockhash queue length %lu exceeds maximum %lu", blockhashes_len, FD_BLOCKHASHES_MAX ));
1039 0 : return 1;
1040 0 : }
1041 0 : if( FD_UNLIKELY( !blockhashes_len ) ) {
1042 0 : FD_LOG_WARNING(( "corrupt snapshot: blockhash queue is empty" ));
1043 0 : return 1;
1044 0 : }
1045 :
1046 : /* hash_index values may skip (see fd_blockhashes.h). A skipped index
1047 : has no blockhash of its own, so it is not a link: the chain is the
1048 : entries in descending hash_index order, so copy them out and sort.
1049 : The manifest buffer is shared with other tiles, so it is not
1050 : reordered in place. The newest index is seq_max, and the recent
1051 : window is still bounded by index distance, so it is the entries
1052 : within seq_max-150 ... seq_max. */
1053 :
1054 0 : fd_snapin_bank_t banks[ FD_BLOCKHASHES_MAX ];
1055 0 : for( ulong i=0UL; i<blockhashes_len; i++ ) {
1056 0 : banks[ i ].hash_index = blockhashes[ i ].hash_index;
1057 0 : banks[ i ].fork_id.val = USHORT_MAX;
1058 0 : banks[ i ].txnhash_offset = ULONG_MAX;
1059 0 : memcpy( banks[ i ].blockhash, blockhashes[ i ].hash, 32UL );
1060 0 : }
1061 0 : fd_snapin_bank_sort_newest_first_inplace( banks, blockhashes_len );
1062 :
1063 0 : ulong chain_cnt = blockhashes_len;
1064 0 : ulong seq_max = banks[ 0UL ].hash_index;
1065 0 : ulong recent_cnt = 0UL;
1066 0 : for( ulong i=0UL; i<chain_cnt; i++ ) {
1067 0 : if( FD_UNLIKELY( i && banks[ i ].hash_index==banks[ i-1UL ].hash_index ) ) {
1068 0 : FD_LOG_WARNING(( "corrupt snapshot: duplicate blockhash queue hash_index %lu", banks[ i ].hash_index ));
1069 0 : return 1;
1070 0 : }
1071 0 : if( FD_LIKELY( seq_max-banks[ i ].hash_index<151UL ) ) recent_cnt++;
1072 0 : }
1073 0 : FD_TEST( chain_cnt==blockhashes_len );
1074 0 : FD_TEST( recent_cnt<=151UL );
1075 :
1076 0 : ulong chain_len = recent_cnt;
1077 :
1078 : /* Chain position of the block that registered each hash_index, by
1079 : slot delta rank r (hash_index seq_max-r): the newest link whose
1080 : hash_index is at most seq_max-r. For a present index that is its
1081 : own link; for a skipped one it is the nearest newer link, since the
1082 : block that registered it shares that link's blockhash. Ranks past
1083 : the oldest entry cannot reference a recent blockhash; they map past
1084 : the chain so that the age check below rejects them if they try. */
1085 :
1086 0 : ulong seq_span = seq_max - banks[ chain_cnt-1UL ].hash_index; /* oldest entry is the last link */
1087 0 : ulong exec_pos_by_rank[ FD_TXNCACHE_MAX_SLOT_DELTAS ];
1088 0 : ulong link = 0UL;
1089 0 : for( ulong r=0UL; r<FD_TXNCACHE_MAX_SLOT_DELTAS; r++ ) {
1090 0 : if( FD_UNLIKELY( r>seq_span ) ) { exec_pos_by_rank[ r ] = chain_cnt; continue; }
1091 0 : ulong target = seq_max-r; /* in [oldest,seq_max], so the walk stops before chain_cnt */
1092 0 : while( banks[ link ].hash_index>target ) link++;
1093 0 : exec_pos_by_rank[ r ] = fd_ulong_if( banks[ link ].hash_index==target, link, link-1UL ); /* link>0 when skipped: seq_max is link 0 */
1094 0 : }
1095 :
1096 : /* Now we need a hashset of just the 151 most recent blockhashes,
1097 : anything else is a nonce transaction which we do not insert, or an
1098 : already expired transaction which can also be discarded. */
1099 :
1100 0 : uchar __attribute__((aligned(alignof(blockhash_map_t)))) _map[ blockhash_map_footprint( 1024UL ) ];
1101 0 : blockhash_map_t * blockhash_map = blockhash_map_join( blockhash_map_new( _map, 1024UL, ctx->lead.seed ) );
1102 0 : if( FD_UNLIKELY( !blockhash_map ) ) FD_LOG_ERR(( "failed to create blockhash map" ));
1103 :
1104 0 : fd_blockhash_entry_t blockhash_pool[ 151UL ];
1105 0 : for( ulong i=0UL; i<chain_len; i++ ) {
1106 0 : fd_memcpy( blockhash_pool[ i ].blockhash.uc, banks[ i ].blockhash, 32UL );
1107 :
1108 0 : if( FD_UNLIKELY( blockhash_map_ele_query_const( blockhash_map, &blockhash_pool[ i ].blockhash, NULL, blockhash_pool ) ) ) {
1109 0 : FD_BASE58_ENCODE_32_BYTES( banks[ i ].blockhash, blockhash_b58 );
1110 0 : FD_LOG_WARNING(( "corrupt snapshot: duplicate blockhash %s in 151 most recent blockhashes", blockhash_b58 ));
1111 0 : return 1;
1112 0 : }
1113 :
1114 0 : blockhash_map_ele_insert( blockhash_map, &blockhash_pool[ i ], blockhash_pool );
1115 0 : }
1116 :
1117 : /* blockhash_groups aliases txncache memory, so filtering must finish
1118 : before the first txncache insert. */
1119 0 : if( FD_UNLIKELY( txncache_staging_filter_groups( ctx, blockhash_map, blockhash_pool, snapshot_slot ) ) ) return 1;
1120 0 : for( ulong i=0UL; i<ctx->lead.recent_groups_len; i++ ) {
1121 0 : recent_blockhash_group_t * group = &ctx->lead.recent_groups[ i ];
1122 0 : FD_TEST( group->execution_bank_i<FD_TXNCACHE_MAX_SLOT_DELTAS );
1123 0 : group->execution_bank_i = exec_pos_by_rank[ group->execution_bank_i ];
1124 0 : }
1125 :
1126 : /* Now load the blockhash offsets for these blockhashes ... */
1127 0 : if( FD_UNLIKELY( !ctx->lead.blockhash_groups_cnt ) ) {
1128 0 : fd_slot_delta_slot_set_t ss = fd_slot_delta_parser_slot_set( ctx->lead.slot_delta_parser );
1129 : /* Rooted slots with no groups represent an empty status cache.
1130 : No restored entry needs a hash offset, so finalization uses zero. */
1131 0 : if( FD_UNLIKELY( !ss.ele_cnt ) ) {
1132 0 : FD_LOG_WARNING(( "corrupt snapshot: no blockhash offsets found (rooted_slots=%lu)", ss.ele_cnt ));
1133 0 : return 1;
1134 0 : }
1135 0 : FD_LOG_WARNING(( "status cache has no blockhash groups (rooted_slots=%lu); defaulting transaction hash offsets to zero", ss.ele_cnt ));
1136 0 : }
1137 0 : for( ulong i=0UL; i<ctx->lead.recent_groups_len; i++ ) {
1138 0 : recent_blockhash_group_t const * group = &ctx->lead.recent_groups[ i ];
1139 0 : ulong blockhash_bank_i = group->blockhash_bank_i;
1140 0 : FD_TEST( blockhash_bank_i<chain_len );
1141 :
1142 0 : if( FD_UNLIKELY( banks[ blockhash_bank_i ].txnhash_offset!=ULONG_MAX && banks[ blockhash_bank_i ].txnhash_offset!=group->txnhash_offset ) ) {
1143 0 : FD_BASE58_ENCODE_32_BYTES( banks[ blockhash_bank_i ].blockhash, blockhash_b58 );
1144 0 : FD_LOG_WARNING(( "corrupt snapshot: conflicting txnhash offsets for blockhash %s", blockhash_b58 ));
1145 0 : return 1;
1146 0 : }
1147 :
1148 0 : if( FD_UNLIKELY( group->txncache_entry_cnt && blockhash_bank_i<=group->execution_bank_i ) ) {
1149 0 : FD_BASE58_ENCODE_32_BYTES( banks[ blockhash_bank_i ].blockhash, blockhash_b58 );
1150 0 : FD_LOG_WARNING(( "corrupt snapshot: %lu status cache entries of slot %lu reference blockhash %s, which is not older than that slot", group->txncache_entry_cnt, group->execution_slot, blockhash_b58 ));
1151 0 : return 1;
1152 0 : }
1153 :
1154 0 : banks[ blockhash_bank_i ].txnhash_offset = group->txnhash_offset;
1155 0 : }
1156 :
1157 : /* Construct the linear fork chain in the txncache. */
1158 :
1159 0 : fd_txncache_fork_id_t parent = { .val = USHORT_MAX };
1160 0 : for( ulong i=0UL; i<chain_len; i++ ) banks[ chain_len-1UL-i ].fork_id = parent = fd_txncache_attach_child( ctx->lead.txncache, parent );
1161 0 : for( ulong i=0UL; i<chain_len; i++ ) fd_txncache_attach_blockhash( ctx->lead.txncache, banks[ i ].fork_id, banks[ i ].blockhash );
1162 :
1163 0 : for( ulong i=0UL; i<ctx->lead.recent_groups_len; i++ ) {
1164 0 : recent_blockhash_group_t const * group = &ctx->lead.recent_groups[ i ];
1165 0 : fd_sstxncache_hash_t const * entries = &ctx->lead.txncache_entries[ group->txncache_entry_idx ];
1166 0 : for( ulong j=0UL; j<group->txncache_entry_cnt; j++ ) {
1167 0 : fd_txncache_insert( ctx->lead.txncache, banks[ group->execution_bank_i ].fork_id, banks[ group->blockhash_bank_i ].blockhash, entries[ j ].txnhash );
1168 0 : }
1169 0 : }
1170 :
1171 : /* Then finalize all the banks (freezing them) and setting the txnhash
1172 : offset so future queries use the correct offset. If the offset is
1173 : ULONG_MAX this is valid, it means the blockhash had no transactions
1174 : in it, so there's nothing in the status cache under that blockhash.
1175 :
1176 : Just set the offset to 0 in this case, it doesn't matter, but
1177 : should be valid between 0 and 11 inclusive. */
1178 0 : for( ulong i=0UL; i<chain_len; i++ ) {
1179 0 : ulong txnhash_offset = banks[ chain_len-1UL-i ].txnhash_offset==ULONG_MAX ? 0UL : banks[ chain_len-1UL-i ].txnhash_offset;
1180 0 : fd_txncache_finalize_fork( ctx->lead.txncache, banks[ chain_len-1UL-i ].fork_id, txnhash_offset, banks[ chain_len-1UL-i ].blockhash );
1181 0 : }
1182 :
1183 0 : for( ulong i=1UL; i<chain_len; i++ ) fd_txncache_advance_root( ctx->lead.txncache, banks[ chain_len-1UL-i ].fork_id );
1184 :
1185 0 : ctx->lead.txncache_root_fork_id = parent;
1186 :
1187 0 : return 0;
1188 0 : }
1189 :
1190 : static void
1191 : process_manifest( fd_snapin_tile_t * ctx,
1192 0 : fd_stem_context_t * stem ) {
1193 0 : fd_snapshot_manifest_t * manifest = fd_chunk_to_laddr( ctx->lead.manifest_out.mem, ctx->lead.manifest_out.chunk );
1194 :
1195 0 : if( FD_UNLIKELY( ctx->lead.advertised_slot!=manifest->slot ) ) {
1196 : /* SnapshotError::MismatchedSlot
1197 : https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/snapshot_bank_utils.rs#L472 */
1198 0 : FD_LOG_WARNING(( "snapshot manifest bank slot %lu does not match advertised slot %lu from snapshot peer",
1199 0 : manifest->slot, ctx->lead.advertised_slot ));
1200 0 : transition_malformed( ctx, stem );
1201 0 : return;
1202 0 : }
1203 :
1204 0 : if( FD_UNLIKELY( !manifest->has_accounts_lthash ) ) {
1205 : /* The manifest must contain accounts lthash, irrespective of
1206 : whether lthash verification is disabled or not.
1207 : https://github.com/anza-xyz/agave/blob/v3.1.9/runtime/src/serde_snapshot.rs#L482 */
1208 0 : FD_LOG_WARNING(( "snapshot manifest missing accounts lthash" ));
1209 0 : transition_malformed( ctx, stem );
1210 0 : return;
1211 0 : }
1212 :
1213 0 : if( FD_UNLIKELY( ctx->alpenglow && !manifest->has_block_id ) ) {
1214 0 : FD_LOG_WARNING(( "snapshot manifest missing block id" ));
1215 0 : transition_malformed( ctx, stem );
1216 0 : return;
1217 0 : }
1218 :
1219 0 : uchar const * sum = manifest->accounts_lthash;
1220 0 : uchar hash32[32]; fd_blake3_hash( sum, FD_LTHASH_LEN_BYTES, hash32 );
1221 0 : FD_BASE58_ENCODE_32_BYTES( sum, sum_enc );
1222 0 : FD_BASE58_ENCODE_32_BYTES( hash32, hash32_enc );
1223 0 : FD_LOG_INFO(( "snapshot manifest slot=%lu indicates lthash[..32]=%s blake3(lthash)=%s",
1224 0 : manifest->slot, sum_enc, hash32_enc ));
1225 :
1226 0 : if( FD_UNLIKELY( memcmp( ctx->lead.advertised_hash, hash32, FD_HASH_FOOTPRINT ) ) ) {
1227 : /* SnapshotError::MismatchedHash
1228 : https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/snapshot_bank_utils.rs#L479 */
1229 0 : FD_BASE58_ENCODE_32_BYTES( ctx->lead.advertised_hash, advertised_hash_enc );
1230 0 : FD_LOG_WARNING(( "snapshot manifest accounts lthash %s does not match advertised hash from snapshot peer %s",
1231 0 : hash32_enc, advertised_hash_enc ));
1232 0 : transition_malformed( ctx, stem );
1233 0 : return;
1234 0 : }
1235 :
1236 0 : ctx->lead.bank_slot = manifest->slot;
1237 0 : ctx->lead.manifest_capitalization = manifest->capitalization;
1238 0 : if( FD_UNLIKELY( ctx->lead.manifest_capitalization>LONG_MAX ) ) {
1239 : /* Calculations downstream require capitalization to be treated
1240 : as long (to handle addition and subtraction). */
1241 0 : FD_LOG_WARNING(( "snapshot manifest capitalization %lu exceeds LONG_MAX", ctx->lead.manifest_capitalization ));
1242 0 : transition_malformed( ctx, stem );
1243 0 : return;
1244 0 : }
1245 :
1246 0 : if( FD_UNLIKELY( fd_ssload_manifest_validate( manifest, FD_RUNTIME_MAX_VAT_VOTE_ACCOUNTS, FD_RUNTIME_MAX_STAKE_ACCOUNTS ) ) ) {
1247 0 : FD_LOG_WARNING(( "snapshot manifest validation failed" ));
1248 0 : transition_malformed( ctx, stem );
1249 0 : return;
1250 0 : }
1251 :
1252 0 : fd_epoch_schedule_t epoch_schedule = (fd_epoch_schedule_t){
1253 0 : .slots_per_epoch = manifest->epoch_schedule_params.slots_per_epoch,
1254 0 : .leader_schedule_slot_offset = manifest->epoch_schedule_params.leader_schedule_slot_offset,
1255 0 : .warmup = manifest->epoch_schedule_params.warmup,
1256 0 : .first_normal_epoch = manifest->epoch_schedule_params.first_normal_epoch,
1257 0 : .first_normal_slot = manifest->epoch_schedule_params.first_normal_slot,
1258 0 : };
1259 0 : ctx->lead.epoch = fd_slot_to_epoch( &epoch_schedule, manifest->slot, NULL );
1260 0 : ctx->lead.epoch_schedule = epoch_schedule;
1261 :
1262 0 : if( FD_UNLIKELY( verify_bank_hash( ctx, manifest ) ) ) {
1263 : /* https://github.com/anza-xyz/agave/blob/v3.1.9/runtime/src/bank.rs#L4682 */
1264 0 : transition_malformed( ctx, stem );
1265 0 : return;
1266 0 : }
1267 :
1268 : /* Classify this manifest against WFS (see fd_wfs.h). A verdict on a
1269 : full is provisional (an incremental may supersede it); only on an
1270 : incremental is it final, so ERROR rejects only an incremental. */
1271 0 : int wfs_mode = fd_wfs_mode( ctx->wfs_slot, ctx->wfs_hash_is_zero, (ulong)ctx->wfs_shred_version, manifest->slot );
1272 0 : switch( wfs_mode ) {
1273 0 : case FD_WFS_MODE_ERROR: {
1274 0 : if( FD_UNLIKELY( !ctx->full ) ) {
1275 0 : FD_LOG_WARNING(( "incremental snapshot manifest slot %lu is behind "
1276 0 : "[consensus.wait_for_supermajority_at_slot] %lu; rejecting this snapshot",
1277 0 : manifest->slot, ctx->wfs_slot ));
1278 0 : transition_malformed( ctx, stem );
1279 0 : return;
1280 0 : }
1281 0 : FD_LOG_NOTICE(( "full snapshot manifest slot %lu is behind "
1282 0 : "[consensus.wait_for_supermajority_at_slot] %lu; an incremental snapshot must "
1283 0 : "bridge the gap or the boot will be rejected",
1284 0 : manifest->slot, ctx->wfs_slot ));
1285 0 : break;
1286 0 : }
1287 0 : case FD_WFS_MODE_NOOP: {
1288 0 : FD_BASE58_ENCODE_32_BYTES( ctx->wfs_bank_hash.uc, expected_hash_enc );
1289 0 : FD_LOG_WARNING(( "%s snapshot manifest slot %lu is ahead of [consensus.wait_for_supermajority_at_slot] %lu "
1290 0 : "(wait_for_supermajority_with_bank_hash=%s, expected_shred_version=%lu); configured slot and bank hash not verified",
1291 0 : ctx->full ? "full" : "incremental",
1292 0 : manifest->slot, ctx->wfs_slot, expected_hash_enc, (ulong)ctx->wfs_shred_version ));
1293 0 : break;
1294 0 : }
1295 0 : case FD_WFS_MODE_MATCH:
1296 : /* Replay verifies the bank hash of the slot we boot at. */
1297 0 : case FD_WFS_MODE_DISABLED:
1298 0 : case FD_WFS_MODE_UNRESOLVED:
1299 0 : break;
1300 0 : default:
1301 0 : FD_LOG_CRIT(( "unexpected WFS mode %d (%s) at manifest slot %lu",
1302 0 : wfs_mode, fd_wfs_mode_str( wfs_mode ), manifest->slot ));
1303 0 : }
1304 :
1305 0 : if( FD_UNLIKELY( verify_slot_deltas_with_bank_slot( ctx, manifest->slot ) ) ) {
1306 0 : FD_LOG_WARNING(( "slot deltas verification failed" ));
1307 0 : transition_malformed( ctx, stem );
1308 0 : return;
1309 0 : }
1310 :
1311 0 : if( FD_UNLIKELY( verify_epoch_stakes( manifest ) ) ) {
1312 0 : FD_LOG_WARNING(( "epoch stakes verification failed" ));
1313 0 : transition_malformed( ctx, stem );
1314 0 : return;
1315 0 : }
1316 :
1317 0 : if( FD_UNLIKELY( populate_txncache( ctx, manifest->blockhashes, manifest->blockhashes_len, manifest->slot ) ) ) {
1318 0 : FD_LOG_WARNING(( "populating txncache failed" ));
1319 0 : transition_malformed( ctx, stem );
1320 0 : return;
1321 0 : }
1322 :
1323 0 : if( ctx->full ) {
1324 0 : ctx->lead.full_genesis_creation_time_seconds = manifest->creation_time_seconds;
1325 0 : } else {
1326 0 : if( FD_UNLIKELY( manifest->creation_time_seconds!=ctx->lead.full_genesis_creation_time_seconds ) ) {
1327 0 : FD_LOG_WARNING(( "snapshot manifest genesis creation time seconds %lu does not match full snapshot genesis creation time seconds %lu",
1328 0 : manifest->creation_time_seconds, ctx->lead.full_genesis_creation_time_seconds ));
1329 0 : transition_malformed( ctx, stem );
1330 0 : return;
1331 0 : }
1332 0 : }
1333 :
1334 0 : manifest->accdb_fork_id = fd_ushort_if( ctx->full, ctx->lead.accdb_root_fork_id.val, ctx->lead.accdb_incr_fork_id.val );
1335 0 : manifest->txncache_fork_id = ctx->lead.txncache_root_fork_id.val;
1336 :
1337 0 : ulong sig = ctx->full ? fd_ssmsg_sig( FD_SSMSG_MANIFEST_FULL ) :
1338 0 : fd_ssmsg_sig( FD_SSMSG_MANIFEST_INCREMENTAL );
1339 0 : fd_stem_publish( stem, ctx->lead.manifest_out.idx, sig, ctx->lead.manifest_out.chunk, sizeof(fd_snapshot_manifest_t), 0UL, 0UL, 0UL );
1340 0 : ctx->lead.manifest_out.chunk = fd_dcache_compact_next( ctx->lead.manifest_out.chunk, sizeof(fd_snapshot_manifest_t), ctx->lead.manifest_out.chunk0, ctx->lead.manifest_out.wmark );
1341 0 : }
1342 :
1343 : static void
1344 : snoop_stake_delegation( fd_snapin_tile_t * ctx,
1345 : ushort stake_fork,
1346 : ulong slot,
1347 : fd_pubkey_t const * stake_account,
1348 : ulong lamports,
1349 : fd_stake_state_t const * stake_state,
1350 0 : ulong data_sz ) {
1351 0 : fd_delegation_t const * delegation = &stake_state->stake.stake.delegation;
1352 0 : FD_CHECK_ERR( delegation->activation_epoch ==ULONG_MAX || delegation->activation_epoch <(ulong)USHORT_MAX, "activation_epoch overflow" );
1353 0 : FD_CHECK_ERR( delegation->deactivation_epoch==ULONG_MAX || delegation->deactivation_epoch<(ulong)USHORT_MAX, "deactivation_epoch overflow" );
1354 :
1355 0 : fd_stake_delegations_fork_update(
1356 0 : ctx->stake_delegations,
1357 0 : stake_fork,
1358 0 : slot,
1359 0 : stake_account,
1360 0 : &delegation->voter_pubkey,
1361 0 : delegation->stake,
1362 0 : delegation->activation_epoch,
1363 0 : delegation->deactivation_epoch,
1364 0 : stake_state->stake.stake.credits_observed,
1365 0 : lamports,
1366 0 : (uint)data_sz );
1367 0 : }
1368 :
1369 : /* Write engine */
1370 :
1371 : static void
1372 : writer_pwrite( fd_snapin_tile_t * ctx,
1373 : uchar const * buf,
1374 : ulong sz,
1375 0 : ulong off ) {
1376 0 : ulong done = 0UL;
1377 0 : while( done<sz ) {
1378 0 : long res = pwrite( ctx->writer.accdb_direct_fd, buf+done, sz-done, (long)(off+done) );
1379 0 : if( FD_UNLIKELY( res<=0L ) ) {
1380 0 : int err = res<0L ? errno : EIO;
1381 0 : if( res<0L && err==EINTR ) continue;
1382 0 : FD_LOG_ERR(( "snapshot write failed at offset %lu (%d-%s)", off+done, err, fd_io_strerror( err ) ));
1383 0 : }
1384 0 : done += (ulong)res;
1385 0 : ctx->metrics.disk_bytes_written += (ulong)res;
1386 0 : }
1387 0 : }
1388 :
1389 : static int
1390 0 : writer_flush( fd_snapin_tile_t * ctx ) {
1391 0 : if( FD_UNLIKELY( !ctx->writer.buf_used ) ) return 0;
1392 :
1393 : /* Pad the range to FD_SNAPIN_DIRECT_ALIGN for O_DIRECT. The padding
1394 : is a dead record so compaction reclaims it after snapshot loading
1395 : finishes. */
1396 0 : ulong used = ctx->writer.buf_used;
1397 0 : ulong padded = fd_ulong_align_up( used+sizeof(fd_accdb_disk_meta_t), FD_SNAPIN_DIRECT_ALIGN );
1398 0 : FD_TEST( padded<=FD_SNAPIN_WRITE_BUF_SZ );
1399 0 : fd_memset( ctx->writer.buf+used, 0, padded-used );
1400 0 : fd_accdb_disk_meta_t * dummy_record = (fd_accdb_disk_meta_t *)( ctx->writer.buf+used );
1401 0 : dummy_record->size = (uint)( padded-used-sizeof(fd_accdb_disk_meta_t) );
1402 :
1403 : /* The offset is aligned because partition sizes are multiples of
1404 : FD_SNAPIN_DIRECT_ALIGN (whole GiB), the snapin tiles are the only
1405 : layer-0 writers during the load, and every reservation they make
1406 : is a multiple of FD_SNAPIN_DIRECT_ALIGN. */
1407 0 : ulong base_off = fd_accdb_snapshot_reserve_write( ctx->accdb, padded, padded-used );
1408 0 : FD_TEST( fd_ulong_is_aligned( base_off, FD_SNAPIN_DIRECT_ALIGN ) );
1409 0 : writer_pwrite( ctx, ctx->writer.buf, padded, base_off );
1410 :
1411 0 : fd_accdb_fork_id_t fork_id = { .val = ctx->full ? USHORT_MAX : (ushort)ctx->incr_fork };
1412 0 : ushort stake_fork = FD_VOLATILE_CONST( ctx->shmem->stake_fork );
1413 0 : fd_snapin_account_batch_t * batch = &ctx->writer.batch;
1414 0 : ulong tile_idx = ctx->tile_idx;
1415 :
1416 0 : uchar const * pubkeys[ FD_SSPARSE_ACC_BATCH_MAX ];
1417 0 : ulong slots [ FD_SSPARSE_ACC_BATCH_MAX ];
1418 0 : ulong data_lens [ FD_SSPARSE_ACC_BATCH_MAX ];
1419 0 : ulong file_offsets [ FD_SSPARSE_ACC_BATCH_MAX ];
1420 0 : uchar results [ FD_SSPARSE_ACC_BATCH_MAX ];
1421 0 : ulong buf_off = 0UL;
1422 :
1423 : /* Flush accounts in batches of 8 */
1424 0 : for( ulong batch_off=0UL; batch_off<batch->cnt; batch_off+=FD_SSPARSE_ACC_BATCH_MAX ) {
1425 0 : ulong cnt = fd_ulong_min( FD_SSPARSE_ACC_BATCH_MAX, batch->cnt-batch_off );
1426 0 : ulong input_lamports_hi = 0UL;
1427 0 : ulong input_lamports = 0UL;
1428 :
1429 0 : for( ulong i=0UL; i<cnt; i++ ) {
1430 0 : ulong idx = batch_off+i;
1431 :
1432 0 : pubkeys [ i ] = ctx->writer.buf+buf_off;
1433 0 : slots [ i ] = (ulong)batch->slots [ idx ];
1434 0 : data_lens [ i ] = (ulong)batch->data_lens[ idx ];
1435 0 : file_offsets[ i ] = base_off+buf_off;
1436 :
1437 0 : buf_off += sizeof(fd_accdb_disk_meta_t)+data_lens[ i ];
1438 0 : fd_uwide_inc( &input_lamports_hi, &input_lamports, input_lamports_hi, input_lamports, batch->lamports[ idx ] );
1439 0 : }
1440 :
1441 0 : ulong accounts_ignored, accounts_replaced, accounts_loaded, replaced_lamports, ignored_lamports;
1442 0 : if( FD_UNLIKELY( fd_accdb_snapshot_write_batch( ctx->accdb, fork_id, cnt, pubkeys,
1443 0 : slots, batch->lamports+batch_off,
1444 0 : data_lens, batch->executables+batch_off,
1445 0 : file_offsets, &accounts_ignored, &accounts_replaced,
1446 0 : &accounts_loaded, &replaced_lamports, &ignored_lamports, results ) ) ) {
1447 0 : return 1;
1448 0 : }
1449 :
1450 : /* Update the snooped stake delegations. Anything that is not a
1451 : delegation and replaced a funded version tombstones it, so a tile
1452 : still holding the older version cannot leave it behind. */
1453 0 : for( ulong i=0UL; i<cnt; i++ ) {
1454 0 : if( FD_UNLIKELY( results[ i ]==FD_ACCDB_SNAPSHOT_WRITE_IGNORED ) ) continue;
1455 :
1456 0 : ulong lamports = batch->lamports[ batch_off+i ];
1457 0 : fd_pubkey_t const * pubkey = (fd_pubkey_t const *)pubkeys[ i ];
1458 0 : uchar const * owner = pubkeys[ i ]+offsetof(fd_accdb_disk_meta_t, owner);
1459 0 : uchar const * data = pubkeys[ i ]+sizeof(fd_accdb_disk_meta_t);
1460 :
1461 0 : if( lamports && !memcmp( owner, fd_solana_stake_program_id.uc, 32UL ) ) {
1462 0 : fd_stake_state_t const * stake_state = fd_stake_state_view( data, data_lens[ i ] );
1463 0 : if( stake_state && stake_state->stake_type==FD_STAKE_STATE_STAKE ) {
1464 0 : snoop_stake_delegation( ctx, stake_fork, slots[ i ], pubkey, lamports, stake_state, data_lens[ i ] );
1465 0 : continue;
1466 0 : }
1467 0 : }
1468 :
1469 0 : int replacing_full_entry = results[ i ]==FD_ACCDB_SNAPSHOT_WRITE_REPLACED_CROSS;
1470 0 : if( FD_UNLIKELY( replacing_full_entry || results[ i ]==FD_ACCDB_SNAPSHOT_WRITE_REPLACED ) ) {
1471 0 : fd_stake_delegations_fork_remove( ctx->stake_delegations, stake_fork, slots[ i ], pubkey, replacing_full_entry );
1472 0 : }
1473 0 : }
1474 :
1475 0 : ctx->metrics.accounts_ignored += accounts_ignored;
1476 0 : ctx->metrics.accounts_replaced += accounts_replaced;
1477 0 : ctx->metrics.accounts_loaded += accounts_loaded;
1478 0 : ctx->shmem->values[ tile_idx ].loaded += accounts_loaded;
1479 0 : ctx->shmem->values[ tile_idx ].duplicates += accounts_ignored + accounts_replaced;
1480 0 : ulong duplicate_lamports_hi, duplicate_lamports;
1481 0 : fd_uwide_inc( &duplicate_lamports_hi, &duplicate_lamports, 0UL, replaced_lamports, ignored_lamports );
1482 0 : ulong * in_hi = &ctx->shmem->values[ tile_idx ].input_lamports_hi; ulong * in_lo = &ctx->shmem->values[ tile_idx ].input_lamports;
1483 0 : ulong * dup_hi = &ctx->shmem->values[ tile_idx ].duplicate_lamports_hi; ulong * dup_lo = &ctx->shmem->values[ tile_idx ].duplicate_lamports;
1484 0 : fd_uwide_add( in_hi, in_lo, *in_hi, *in_lo, input_lamports_hi, input_lamports, 0UL );
1485 0 : fd_uwide_add( dup_hi, dup_lo, *dup_hi, *dup_lo, duplicate_lamports_hi, duplicate_lamports, 0UL );
1486 0 : }
1487 :
1488 0 : FD_TEST( buf_off==ctx->writer.buf_used );
1489 0 : ctx->writer.buf_used = 0UL;
1490 0 : ctx->writer.batch.cnt = 0UL;
1491 0 : return 0;
1492 0 : }
1493 :
1494 : static int
1495 : writer_append_account( fd_snapin_tile_t * ctx,
1496 : uchar const * pubkey,
1497 : uchar const * owner,
1498 : uchar const * data,
1499 : ulong slot,
1500 : ulong lamports,
1501 : ulong data_len,
1502 0 : int executable ) {
1503 0 : FD_TEST( slot<=UINT_MAX );
1504 0 : ulong account_sz = sizeof(fd_accdb_disk_meta_t)+data_len;
1505 0 : FD_TEST( account_sz<=FD_SNAPIN_WRITE_BUF_MAX );
1506 :
1507 0 : if( FD_UNLIKELY( account_sz>FD_SNAPIN_WRITE_BUF_MAX-ctx->writer.buf_used && writer_flush( ctx ) ) ) {
1508 0 : return 1;
1509 0 : }
1510 :
1511 0 : FD_TEST( ctx->writer.batch.cnt<FD_SNAPIN_WRITE_ACCOUNT_MAX );
1512 :
1513 0 : ulong idx = ctx->writer.batch.cnt++;
1514 0 : ulong buf_off = ctx->writer.buf_used;
1515 :
1516 : /* Serialize the account metadata into the buffer */
1517 0 : fd_accdb_disk_meta_t meta = {
1518 0 : .size = (uint)data_len,
1519 0 : .generation = 0U,
1520 0 : };
1521 0 : uchar * meta_ptr = ctx->writer.buf+buf_off;
1522 0 : uchar * data_ptr = meta_ptr+sizeof(fd_accdb_disk_meta_t);
1523 0 : fd_memcpy( meta.pubkey, pubkey, 32UL );
1524 0 : fd_memcpy( meta.owner, owner, 32UL );
1525 0 : fd_memcpy( meta_ptr, meta.b, sizeof(fd_accdb_disk_meta_t) );
1526 0 : fd_memcpy( data_ptr, data, data_len );
1527 0 : ctx->writer.buf_used += account_sz;
1528 :
1529 : /* Stage fields needed for index publication after pwrite. */
1530 0 : ctx->writer.batch.lamports [ idx ] = lamports;
1531 0 : ctx->writer.batch.slots [ idx ] = (uint)slot;
1532 0 : ctx->writer.batch.data_lens [ idx ] = (uint)data_len;
1533 0 : ctx->writer.batch.executables [ idx ] = executable;
1534 0 : ctx->metrics.total_accounts_processed++;
1535 0 : return 0;
1536 0 : }
1537 :
1538 : static int
1539 0 : writer_append_staged_account( fd_snapin_tile_t * ctx ) {
1540 0 : if( FD_UNLIKELY( writer_append_account( ctx, ctx->staged.pubkey, ctx->staged.owner, ctx->staged.data,
1541 0 : ctx->staged.slot, ctx->staged.lamports, ctx->staged.data_len,
1542 0 : ctx->staged.executable ) ) ) {
1543 0 : return 1;
1544 0 : }
1545 0 : ctx->metrics.total_account_batches_processed++;
1546 0 : return 0;
1547 0 : }
1548 :
1549 : static int
1550 : process_account_batch( fd_snapin_tile_t * ctx,
1551 0 : fd_ssparse_advance_result_t * result ) {
1552 0 : uchar const * const * entries = result->account_batch.batch;
1553 0 : ulong cnt = result->account_batch.batch_cnt;
1554 0 : ulong batch_slot = result->account_batch.slot;
1555 :
1556 0 : for( ulong i=0UL; i<cnt; i++ ) {
1557 0 : uchar const * e = entries[ i ];
1558 0 : if( FD_UNLIKELY( writer_append_account( ctx, e+16UL, e+64UL, e+136UL, batch_slot,
1559 0 : fd_ulong_load_8_fast( e+48UL ), fd_ulong_load_8_fast( e+8UL ),
1560 0 : (int)e[ 96UL ] ) ) ) {
1561 0 : return 1;
1562 0 : }
1563 0 : }
1564 0 : ctx->metrics.total_account_batches_processed++;
1565 0 : return 0;
1566 0 : }
1567 :
1568 : static int
1569 : process_account_header( fd_snapin_tile_t * ctx,
1570 0 : fd_ssparse_advance_result_t * result ) {
1571 0 : FD_TEST( ctx->staged.bytes_received==ctx->staged.data_len );
1572 0 : FD_TEST( result->account_header.data_len<=FD_RUNTIME_ACC_SZ_MAX );
1573 :
1574 0 : ctx->staged.executable = result->account_header.executable;
1575 0 : ctx->staged.slot = result->account_header.slot;
1576 0 : ctx->staged.lamports = result->account_header.lamports;
1577 0 : ctx->staged.data_len = result->account_header.data_len;
1578 0 : ctx->staged.bytes_received = 0UL;
1579 0 : fd_memcpy( ctx->staged.pubkey, result->account_header.pubkey, 32UL );
1580 0 : fd_memcpy( ctx->staged.owner, result->account_header.owner, 32UL );
1581 :
1582 0 : if( FD_LIKELY( ctx->staged.data_len ) ) {
1583 0 : return 0;
1584 0 : }
1585 :
1586 : /* No account data to receive, so we can just publish the account now. */
1587 0 : return writer_append_staged_account( ctx );
1588 0 : }
1589 :
1590 : static int
1591 : process_account_data( fd_snapin_tile_t * ctx,
1592 0 : fd_ssparse_advance_result_t * result ) {
1593 0 : FD_TEST( ctx->staged.bytes_received<ctx->staged.data_len );
1594 0 : FD_TEST( result->account_data.data_sz<=ctx->staged.data_len-ctx->staged.bytes_received );
1595 :
1596 0 : fd_memcpy( ctx->staged.data+ctx->staged.bytes_received, result->account_data.data, result->account_data.data_sz );
1597 0 : ctx->staged.bytes_received += result->account_data.data_sz;
1598 :
1599 : /* More bytes remain in account data, don't publish yet */
1600 0 : if( FD_LIKELY( ctx->staged.bytes_received<ctx->staged.data_len ) ) {
1601 0 : return 0;
1602 0 : }
1603 :
1604 0 : return writer_append_staged_account( ctx );
1605 0 : }
1606 :
1607 : static int
1608 : handle_data_frag( fd_snapin_tile_t * ctx,
1609 : ulong in_idx,
1610 : ulong chunk,
1611 : ulong sz,
1612 0 : fd_stem_context_t * stem ) {
1613 0 : if( FD_UNLIKELY( ctx->state==FD_SNAPSHOT_STATE_FINISHING ) ) {
1614 0 : FD_LOG_WARNING(( "received unexpected data frag while in state %s (%lu)",
1615 0 : fd_ssctrl_state_str( (ulong)ctx->state ), (ulong)ctx->state ));
1616 0 : transition_malformed( ctx, stem );
1617 0 : return 0;
1618 0 : }
1619 0 : if( FD_UNLIKELY( ctx->state==FD_SNAPSHOT_STATE_ERROR ) ) {
1620 : /* Ignore all data frags after observing an error in the stream until
1621 : we receive fail & init control messages to restart processing. */
1622 0 : return 0;
1623 0 : }
1624 0 : if( FD_UNLIKELY( ctx->state!=FD_SNAPSHOT_STATE_PROCESSING ) ) {
1625 0 : FD_LOG_ERR(( "received data frag during invalid state %s (%lu)",
1626 0 : fd_ssctrl_state_str( (ulong)ctx->state ), (ulong)ctx->state ));
1627 0 : }
1628 :
1629 0 : if( FD_UNLIKELY( chunk<ctx->in[ in_idx ].chunk0 || chunk>ctx->in[ in_idx ].wmark || sz>ctx->in[ in_idx ].mtu ) ) {
1630 0 : FD_LOG_ERR(( "invalid data frag bounds (chunk=%lu chunk0=%lu wmark=%lu sz=%lu mtu=%lu)", chunk, ctx->in[ in_idx ].chunk0, ctx->in[ in_idx ].wmark, sz, ctx->in[ in_idx ].mtu ));
1631 0 : }
1632 :
1633 0 : for(;;) {
1634 0 : if( FD_UNLIKELY( sz-ctx->in[ in_idx ].pos==0UL ) ) break;
1635 :
1636 0 : uchar const * data = (uchar const *)fd_chunk_to_laddr_const( ctx->in[ in_idx ].wksp, chunk ) + ctx->in[ in_idx ].pos;
1637 :
1638 0 : int early_exit = 0;
1639 0 : fd_ssparse_advance_result_t result[1];
1640 0 : int res = fd_ssparse_advance( ctx->ssparse, data, sz-ctx->in[ in_idx ].pos, result );
1641 0 : switch( res ) {
1642 0 : case FD_SSPARSE_ADVANCE_ERROR:
1643 0 : FD_LOG_WARNING(( "error while parsing snapshot stream" ));
1644 0 : transition_malformed( ctx, stem );
1645 0 : return 0;
1646 0 : case FD_SSPARSE_ADVANCE_AGAIN:
1647 0 : break;
1648 0 : case FD_SSPARSE_ADVANCE_APPENDVEC: {
1649 : /* Parse only this tile's claimed appendvecs. */
1650 0 : ulong appendvec_idx = ctx->appendvec_seq++;
1651 0 : if( FD_UNLIKELY( appendvec_idx==ctx->claimed_appendvec ) ) {
1652 0 : ctx->claimed_appendvec = FD_ATOMIC_FETCH_AND_ADD( &ctx->shmem->next_appendvec_ticket, 1UL );
1653 0 : fd_ssparse_appendvec_parse( ctx->ssparse );
1654 0 : }
1655 0 : break;
1656 0 : }
1657 0 : case FD_SSPARSE_ADVANCE_MANIFEST:
1658 0 : case FD_SSPARSE_ADVANCE_MANIFEST_DONE: {
1659 : /* Tile 0 only. */
1660 0 : if( FD_LIKELY( !is_lead( ctx ) ) ) break;
1661 :
1662 0 : if( FD_UNLIKELY( ctx->lead.flags.manifest_done ) ) {
1663 0 : FD_LOG_WARNING(( "excess data after manifest" ));
1664 0 : transition_malformed( ctx, stem );
1665 0 : return 0;
1666 0 : }
1667 0 : int parser_res = fd_ssmanifest_parser_consume( ctx->lead.manifest_parser,
1668 0 : result->manifest.data,
1669 0 : result->manifest.data_sz );
1670 0 : if( FD_UNLIKELY( parser_res==FD_SSMANIFEST_PARSER_ADVANCE_ERROR ) ) {
1671 0 : FD_LOG_WARNING(( "error while parsing snapshot manifest" ));
1672 0 : transition_malformed( ctx, stem );
1673 0 : return 0;
1674 0 : }
1675 0 : if( res==FD_SSPARSE_ADVANCE_MANIFEST_DONE ) {
1676 0 : if( FD_UNLIKELY( fd_ssmanifest_parser_fini( ctx->lead.manifest_parser )!=FD_SSMANIFEST_PARSER_ADVANCE_DONE ) ) {
1677 0 : FD_LOG_WARNING(( "manifest stream ended before parser was done" ));
1678 0 : transition_malformed( ctx, stem );
1679 0 : return 0;
1680 0 : }
1681 0 : ctx->lead.flags.manifest_done = 1;
1682 0 : }
1683 0 : break;
1684 0 : }
1685 0 : case FD_SSPARSE_ADVANCE_STATUS_CACHE: {
1686 : /* Tile 0 only. */
1687 0 : if( FD_LIKELY( !is_lead( ctx ) ) ) break;
1688 :
1689 0 : fd_slot_delta_parser_advance_result_t sd_result[1];
1690 0 : ulong bytes_remaining = result->status_cache.data_sz;
1691 :
1692 0 : while( bytes_remaining ) {
1693 0 : int res = fd_slot_delta_parser_consume( ctx->lead.slot_delta_parser,
1694 0 : result->status_cache.data,
1695 0 : bytes_remaining,
1696 0 : sd_result );
1697 0 : if( FD_UNLIKELY( res<0 ) ) {
1698 0 : FD_LOG_WARNING(( "error while parsing slot deltas in status cache" ));
1699 0 : transition_malformed( ctx, stem );
1700 0 : return 0;
1701 0 : } else if( FD_LIKELY( res==FD_SLOT_DELTA_PARSER_ADVANCE_SLOT ) ) {
1702 0 : txncache_staging_slot_begin( ctx, sd_result->slot );
1703 0 : } else if( FD_LIKELY( res==FD_SLOT_DELTA_PARSER_ADVANCE_GROUP ) ) {
1704 0 : if( FD_UNLIKELY( txncache_staging_group_begin( ctx, sd_result->group.blockhash, sd_result->group.txnhash_offset ) ) ) {
1705 0 : FD_LOG_WARNING(( "blockhash groups overflow for slot %lu, max is %lu", sd_result->group.slot, ctx->lead.txncache_max_groups_per_slot ));
1706 0 : transition_malformed( ctx, stem );
1707 0 : return 0;
1708 0 : }
1709 0 : } else if( FD_LIKELY( res==FD_SLOT_DELTA_PARSER_ADVANCE_ENTRY ) ) {
1710 0 : if( FD_UNLIKELY( txncache_staging_entry_add( ctx, sd_result->entry->slot, sd_result->entry->txnhash ) ) ) {
1711 0 : FD_LOG_WARNING(( "status cache slot %lu has more than %lu entries", sd_result->entry->slot, ctx->lead.txncache_max_entries_per_slot ));
1712 0 : transition_malformed( ctx, stem );
1713 0 : return 0;
1714 0 : }
1715 0 : }
1716 :
1717 0 : bytes_remaining -= sd_result->bytes_consumed;
1718 0 : result->status_cache.data += sd_result->bytes_consumed;
1719 0 : }
1720 :
1721 0 : if( FD_UNLIKELY( result->status_cache.done ) ) {
1722 0 : int fini_res = fd_slot_delta_parser_consume( ctx->lead.slot_delta_parser, result->status_cache.data, 0UL, sd_result );
1723 0 : if( FD_UNLIKELY( fini_res<0 ) ) {
1724 0 : FD_LOG_WARNING(( "error while finalizing slot deltas in status cache" ));
1725 0 : transition_malformed( ctx, stem );
1726 0 : return 0;
1727 0 : }
1728 0 : ctx->lead.flags.status_cache_done = fini_res==FD_SLOT_DELTA_PARSER_ADVANCE_DONE;
1729 0 : }
1730 0 : break;
1731 0 : }
1732 0 : case FD_SSPARSE_ADVANCE_ACCOUNT_HEADER:
1733 0 : early_exit = process_account_header( ctx, result );
1734 0 : if( FD_UNLIKELY( early_exit ) ) {
1735 0 : transition_malformed( ctx, stem );
1736 0 : return 0;
1737 0 : }
1738 0 : break;
1739 0 : case FD_SSPARSE_ADVANCE_ACCOUNT_DATA:
1740 0 : if( FD_UNLIKELY( process_account_data( ctx, result ) ) ) {
1741 0 : transition_malformed( ctx, stem );
1742 0 : return 0;
1743 0 : }
1744 :
1745 : /* Account data may span multiple input chunks. Once complete,
1746 : copy the staged account into gui_out and publish it once.
1747 :
1748 : We expect ConfigKeys Vec to be length 2 (checked via the
1749 : first byte of the accumulated data). We expect the size of
1750 : ConfigProgram-owned accounts to be at most
1751 : FD_GUI_CONFIG_PARSE_MAX_VALID_ACCT_SZ, since this is the
1752 : size that the Solana CLI allocates for them. Although the
1753 : ConfigProgram itself does not enforce these invariants, the
1754 : vast majority of accounts (with a tiny number of exceptions
1755 : on devnet) are maintained with the Solana CLI. */
1756 0 : if( FD_UNLIKELY( ctx->staged.bytes_received==ctx->staged.data_len
1757 0 : && ctx->gui_out.idx!=ULONG_MAX
1758 0 : && !memcmp( ctx->staged.owner, fd_solana_config_program_id.key, sizeof(fd_hash_t) )
1759 0 : && ctx->staged.data_len
1760 0 : && ctx->staged.data_len<=FD_GUI_CONFIG_PARSE_MAX_VALID_ACCT_SZ
1761 0 : && ctx->staged.data[ 0 ]==2UL ) ) {
1762 0 : uchar * acct = fd_chunk_to_laddr( ctx->gui_out.mem, ctx->gui_out.chunk );
1763 0 : fd_memcpy( acct, ctx->staged.data, ctx->staged.data_len );
1764 0 : fd_stem_publish( stem, ctx->gui_out.idx, ctx->staged.slot, ctx->gui_out.chunk, ctx->staged.data_len, 0UL, 0UL, 0UL ); /* sig is the account slot */
1765 0 : ctx->gui_out.chunk = fd_dcache_compact_next( ctx->gui_out.chunk, ctx->staged.data_len, ctx->gui_out.chunk0, ctx->gui_out.wmark );
1766 0 : early_exit = 1;
1767 0 : }
1768 0 : break;
1769 0 : case FD_SSPARSE_ADVANCE_ACCOUNT_BATCH:
1770 0 : if( FD_UNLIKELY( process_account_batch( ctx, result ) ) ) {
1771 0 : transition_malformed( ctx, stem );
1772 0 : return 0;
1773 0 : }
1774 0 : break;
1775 0 : case FD_SSPARSE_ADVANCE_DONE:
1776 0 : ctx->state = FD_SNAPSHOT_STATE_FINISHING;
1777 0 : break;
1778 0 : default:
1779 0 : FD_LOG_ERR(( "unexpected fd_ssparse_advance result %d", res ));
1780 0 : break;
1781 0 : }
1782 :
1783 0 : if( FD_UNLIKELY( is_lead( ctx ) && !ctx->lead.flags.manifest_processed && ctx->lead.flags.manifest_done && ctx->lead.flags.status_cache_done ) ) {
1784 0 : process_manifest( ctx, stem );
1785 0 : if( FD_UNLIKELY( ctx->state==FD_SNAPSHOT_STATE_ERROR ) ) break;
1786 0 : ctx->lead.flags.manifest_processed = 1;
1787 0 : }
1788 :
1789 0 : ctx->in[ in_idx ].pos += result->bytes_consumed;
1790 0 : if( FD_LIKELY( ctx->full ) ) ctx->metrics.full_bytes_read += result->bytes_consumed;
1791 0 : else ctx->metrics.incremental_bytes_read += result->bytes_consumed;
1792 :
1793 0 : if( FD_UNLIKELY( early_exit ) ) break;
1794 0 : }
1795 :
1796 0 : int reprocess_frag = ctx->in[ in_idx ].pos<sz;
1797 0 : if( FD_LIKELY( !reprocess_frag ) ) ctx->in[ in_idx ].pos = 0UL;
1798 0 : return reprocess_frag;
1799 0 : }
1800 :
1801 : /* Resets local worker state */
1802 :
1803 : static void
1804 0 : reset_attempt_state( fd_snapin_tile_t * ctx ) {
1805 0 : for( ulong lane=0UL; lane<ctx->lane_cnt; lane++ ) {
1806 0 : ctx->in[ lane ].pos = 0UL;
1807 0 : }
1808 0 : ctx->expected_frame = 0UL;
1809 0 : ctx->appendvec_seq = 0UL;
1810 0 : ctx->incr_fork = ULONG_MAX;
1811 0 : ctx->writer.buf_used = 0UL;
1812 0 : ctx->writer.batch.cnt = 0UL;
1813 0 : ctx->staged.data_len = 0UL;
1814 0 : ctx->staged.bytes_received = 0UL;
1815 :
1816 0 : fd_ssparse_init( ctx->ssparse );
1817 0 : fd_ssparse_batch_enable( ctx->ssparse, 1 );
1818 0 : }
1819 :
1820 : static void
1821 0 : start_processing_attempt( fd_snapin_tile_t * ctx ) {
1822 0 : FD_COMPILER_MFENCE();
1823 0 : ctx->incr_fork = FD_VOLATILE_CONST( ctx->shmem->fork_id );
1824 0 : FD_TEST( ctx->full ? ctx->incr_fork==(ulong)USHORT_MAX : ctx->incr_fork<(ulong)USHORT_MAX );
1825 :
1826 : /* Claim before the first data fragment. */
1827 0 : ctx->claimed_appendvec = FD_ATOMIC_FETCH_AND_ADD( &ctx->shmem->next_appendvec_ticket, 1UL );
1828 0 : }
1829 :
1830 : static int
1831 0 : validate_capitalization( fd_snapin_tile_t * ctx ) {
1832 : /* Sum exactly: saturating at 2^64 computed 0 for an honest snapshot
1833 : and could accept a wrong one. */
1834 0 : ulong input_hi = 0UL, input_lo = 0UL;
1835 0 : ulong dup_hi = 0UL, dup_lo = 0UL;
1836 0 : FD_COMPILER_MFENCE();
1837 0 : for( ulong i=0UL; i<FD_TOPO_MAX_TILE_IN_LINKS; i++ ) {
1838 0 : fd_uwide_add( &input_hi, &input_lo, input_hi, input_lo, ctx->shmem->values[ i ].input_lamports_hi, ctx->shmem->values[ i ].input_lamports, 0UL );
1839 0 : fd_uwide_add( &dup_hi, &dup_lo, dup_hi, dup_lo, ctx->shmem->values[ i ].duplicate_lamports_hi, ctx->shmem->values[ i ].duplicate_lamports, 0UL );
1840 0 : }
1841 :
1842 0 : ulong cap_hi = 0UL;
1843 0 : ulong cap_lo = fd_ulong_if( ctx->full, 0UL, ctx->lead.recovery.capitalization );
1844 0 : fd_uwide_add( &cap_hi, &cap_lo, cap_hi, cap_lo, input_hi, input_lo, 0UL );
1845 0 : ulong borrow = fd_uwide_sub( &cap_hi, &cap_lo, cap_hi, cap_lo, dup_hi, dup_lo, 0UL );
1846 0 : if( FD_UNLIKELY( borrow || cap_hi || cap_lo!=ctx->lead.manifest_capitalization ) ) {
1847 : /* SnapshotError::MismatchedCapitalization
1848 : https://github.com/anza-xyz/agave/blob/v4.0.0-beta.2/runtime/src/snapshot_bank_utils.rs#L217 */
1849 0 : if( FD_LIKELY( !borrow && !cap_hi ) ) {
1850 0 : FD_LOG_WARNING(( "%s snapshot manifest capitalization %lu does not match computed capitalization %lu",
1851 0 : ctx->full?"full":"incr", ctx->lead.manifest_capitalization, cap_lo ));
1852 0 : } else {
1853 0 : FD_LOG_WARNING(( "%s snapshot manifest capitalization %lu does not match computed capitalization, which is out of range "
1854 0 : "(input lamports %lu*2^64+%lu, duplicate lamports %lu*2^64+%lu)",
1855 0 : ctx->full?"full":"incr", ctx->lead.manifest_capitalization, input_hi, input_lo, dup_hi, dup_lo ));
1856 0 : }
1857 0 : return -1;
1858 0 : }
1859 0 : return 0;
1860 0 : }
1861 :
1862 : static void
1863 0 : fold_account_counts( fd_snapin_tile_t * ctx ) {
1864 0 : for( ulong i=0UL; i<FD_TOPO_MAX_TILE_IN_LINKS; i++ ) {
1865 0 : ctx->lead.account_counts.loaded += ctx->shmem->values[ i ].loaded;
1866 0 : ctx->lead.account_counts.duplicates += ctx->shmem->values[ i ].duplicates;
1867 0 : }
1868 0 : }
1869 :
1870 : static void
1871 : handle_control_frag( fd_snapin_tile_t * ctx,
1872 : fd_stem_context_t * stem,
1873 : ulong in_idx,
1874 : ulong sig,
1875 : ulong chunk,
1876 0 : ulong sz ) {
1877 0 : if( ctx->state==FD_SNAPSHOT_STATE_ERROR && sig!=FD_SNAPSHOT_MSG_CTRL_FAIL ) {
1878 : /* Control messages move along the snapshot load pipeline. Since
1879 : error conditions can be triggered by any tile in the pipeline,
1880 : it is possible to be in error state and still receive otherwise
1881 : valid messages. Only a fail message can revert this. */
1882 0 : return;
1883 0 : };
1884 :
1885 0 : int forward_msg = 1;
1886 :
1887 0 : switch( sig ) {
1888 0 : case FD_SNAPSHOT_MSG_CTRL_INIT_FULL:
1889 0 : case FD_SNAPSHOT_MSG_CTRL_INIT_INCR: {
1890 0 : FD_TEST( ctx->state==FD_SNAPSHOT_STATE_IDLE );
1891 0 : ctx->state = FD_SNAPSHOT_STATE_PROCESSING;
1892 0 : ctx->full = sig==FD_SNAPSHOT_MSG_CTRL_INIT_FULL;
1893 :
1894 0 : reset_attempt_state( ctx );
1895 :
1896 : /* Rewind metric counters (no-op unless recovering from a fail) */
1897 0 : if( sig==FD_SNAPSHOT_MSG_CTRL_INIT_FULL ) {
1898 0 : ctx->metrics.accounts_loaded = ctx->metrics.full_accounts_loaded = 0;
1899 0 : ctx->metrics.accounts_replaced = ctx->metrics.full_accounts_replaced = 0;
1900 0 : ctx->metrics.accounts_ignored = ctx->metrics.full_accounts_ignored = 0;
1901 0 : ctx->metrics.full_bytes_read = 0UL;
1902 0 : ctx->metrics.incremental_bytes_read = 0UL;
1903 0 : } else {
1904 0 : ctx->metrics.accounts_loaded = ctx->metrics.full_accounts_loaded;
1905 0 : ctx->metrics.accounts_replaced = ctx->metrics.full_accounts_replaced;
1906 0 : ctx->metrics.accounts_ignored = ctx->metrics.full_accounts_ignored;
1907 0 : ctx->metrics.incremental_bytes_read = 0UL;
1908 0 : }
1909 :
1910 0 : if( FD_LIKELY( !is_lead( ctx ) ) ) break;
1911 :
1912 : /* Roll back before publishing this attempt. */
1913 0 : if( FD_UNLIKELY( ctx->lead.rollback.pending ) ) {
1914 0 : ctx->lead.rollback.pending = 0;
1915 : /* Purge failed incremental state unless a full reset follows. */
1916 0 : if( !ctx->lead.rollback.full && FD_LIKELY( !ctx->full ) ) {
1917 0 : fd_accdb_purge( ctx->accdb, ctx->lead.rollback.fork );
1918 0 : fd_accdb_snapshot_revert_whead( ctx->accdb, &ctx->lead.recovery.accdb_metadata );
1919 0 : fd_stake_delegations_evict_fork( ctx->stake_delegations, FD_VOLATILE_CONST( ctx->shmem->stake_fork ) );
1920 0 : }
1921 0 : }
1922 :
1923 0 : ctx->lead.manifest_capitalization = 0UL;
1924 :
1925 0 : fd_txncache_reset( ctx->lead.txncache );
1926 0 : txncache_staging_reset( ctx );
1927 0 : ctx->lead.blockhash_groups = txncache_staging_scratch( ctx );
1928 0 : fd_ssmanifest_parser_init( ctx->lead.manifest_parser, fd_chunk_to_laddr( ctx->lead.manifest_out.mem, ctx->lead.manifest_out.chunk ) );
1929 0 : fd_slot_delta_parser_init( ctx->lead.slot_delta_parser );
1930 0 : fd_memset( &ctx->lead.flags, 0, sizeof(ctx->lead.flags) );
1931 :
1932 0 : ushort stake_fork = USHORT_MAX;
1933 0 : if( sig==FD_SNAPSHOT_MSG_CTRL_INIT_FULL ) {
1934 0 : ctx->lead.full_genesis_creation_time_seconds = 0UL;
1935 0 : ctx->lead.recovery.capitalization = 0UL;
1936 0 : fd_memset( &ctx->lead.account_counts, 0, sizeof(ctx->lead.account_counts) );
1937 :
1938 0 : fd_stake_delegations_reset( ctx->stake_delegations );
1939 0 : fd_accdb_reset( ctx->accdb );
1940 0 : fd_accdb_fork_id_t null_fork_id = (fd_accdb_fork_id_t){ .val = USHORT_MAX };
1941 0 : ctx->lead.accdb_root_fork_id = fd_accdb_attach_child( ctx->accdb, null_fork_id );
1942 :
1943 0 : fd_accdb_snapshot_load_begin( ctx->accdb );
1944 0 : } else {
1945 : /* Create a child fork for incremental writes. On failure,
1946 : fd_accdb_purge(child) reverts just the incremental changes.
1947 : On success, fd_accdb_advance_root(child) promotes them. The
1948 : stake delegations get a fork likewise. */
1949 0 : ctx->lead.accdb_incr_fork_id = fd_accdb_attach_child( ctx->accdb, ctx->lead.accdb_root_fork_id );
1950 0 : stake_fork = fd_stake_delegations_new_fork( ctx->stake_delegations, USHORT_MAX );
1951 0 : }
1952 :
1953 : /* Save the slot advertised by the snapshot peer and verify it
1954 : against the slot in the snapshot manifest. For redirect-based
1955 : HTTP downloads, these are initial estimates from gossip and
1956 : will be updated by the META message below once the redirect
1957 : resolves to a concrete snapshot filename. */
1958 0 : fd_ssctrl_init_t const * msg = fd_chunk_to_laddr_const( ctx->in[ in_idx ].wksp, chunk );
1959 0 : ctx->lead.advertised_slot = msg->slot;
1960 0 : fd_memcpy( ctx->lead.advertised_hash, msg->snapshot_hash, FD_HASH_FOOTPRINT );
1961 0 : ctx->lead.init_completed = 1;
1962 :
1963 : /* Reset shared state before publishing the fork. */
1964 0 : fd_memset( &ctx->shmem->values, 0, sizeof(ctx->shmem->values) );
1965 0 : FD_VOLATILE( ctx->shmem->next_appendvec_ticket ) = 0UL;
1966 0 : FD_COMPILER_MFENCE();
1967 :
1968 : /* Publish before acknowledging INIT. */
1969 0 : FD_VOLATILE( ctx->shmem->fork_id ) = ctx->full ? (ulong)USHORT_MAX : (ulong)ctx->lead.accdb_incr_fork_id.val;
1970 0 : FD_VOLATILE( ctx->shmem->stake_fork ) = stake_fork;
1971 0 : FD_COMPILER_MFENCE();
1972 0 : break;
1973 0 : }
1974 :
1975 0 : case FD_SNAPSHOT_MSG_META: {
1976 0 : forward_msg = 0; /* snapct already receives META directly from snapld */
1977 0 : if( FD_LIKELY( !is_lead( ctx ) ) ) break;
1978 :
1979 : /* For redirect-based HTTP downloads, the META message carries
1980 : the resolved slot and hash from the actual snapshot filename
1981 : the server redirected to. Update the advertised values so
1982 : that process_manifest can verify the manifest against them. */
1983 0 : FD_TEST( sz==sizeof(fd_ssctrl_meta_t) );
1984 0 : fd_ssctrl_meta_t const * meta = fd_chunk_to_laddr_const( ctx->in[ in_idx ].wksp, chunk );
1985 0 : if( meta->resolved_slot!=ULONG_MAX ) {
1986 0 : ctx->lead.advertised_slot = meta->resolved_slot;
1987 0 : fd_memcpy( ctx->lead.advertised_hash, meta->resolved_hash, FD_HASH_FOOTPRINT );
1988 0 : }
1989 0 : break;
1990 0 : }
1991 :
1992 0 : case FD_SNAPSHOT_MSG_CTRL_FINI: {
1993 : /* This is a special case: handle_data_frag must have already
1994 : processed FD_SSPARSE_ADVANCE_DONE and moved the state into
1995 : FD_SNAPSHOT_STATE_FINISHING. Otherwise, treat this as a
1996 : malformed snapshot so that the pipeline can retry. */
1997 0 : if( FD_UNLIKELY( ctx->state!=FD_SNAPSHOT_STATE_FINISHING ) ) {
1998 0 : FD_LOG_WARNING(( "received FINI while in state %s (%lu), expected FINISHING (possibly truncated tar stream)",
1999 0 : fd_ssctrl_state_str( (ulong)ctx->state ), (ulong)ctx->state ));
2000 0 : transition_malformed( ctx, stem );
2001 0 : forward_msg = 0;
2002 0 : break;
2003 0 : }
2004 :
2005 : /* Flush records before the FINI ack. */
2006 0 : if( FD_UNLIKELY( writer_flush( ctx ) ) ) {
2007 0 : transition_malformed( ctx, stem );
2008 0 : forward_msg = 0;
2009 0 : break;
2010 0 : }
2011 :
2012 0 : fd_accdb_flush_metrics( ctx->accdb );
2013 :
2014 : /* Publish prior total updates before the FINI ack. */
2015 0 : FD_COMPILER_MFENCE(); /* publish before ack */
2016 :
2017 : /* Keep per-tile gauges. Dashboards sum them. */
2018 0 : break;
2019 0 : }
2020 :
2021 0 : case FD_SNAPSHOT_MSG_CTRL_NEXT: {
2022 0 : FD_TEST( ctx->state==FD_SNAPSHOT_STATE_FINISHING );
2023 0 : ctx->state = FD_SNAPSHOT_STATE_IDLE;
2024 :
2025 : /* Backup metric counters */
2026 0 : ctx->metrics.full_accounts_loaded = ctx->metrics.accounts_loaded;
2027 0 : ctx->metrics.full_accounts_replaced = ctx->metrics.accounts_replaced;
2028 0 : ctx->metrics.full_accounts_ignored = ctx->metrics.accounts_ignored;
2029 :
2030 : /* Tile 0 only. */
2031 0 : if( FD_LIKELY( !is_lead( ctx ) ) ) break;
2032 :
2033 : /* FINI acks make shared data stable. */
2034 0 : if( FD_UNLIKELY( verify_sysvars( ctx ) ) ) {
2035 0 : FD_LOG_WARNING(( "sysvar verification failed for full snapshot" ));
2036 0 : transition_malformed( ctx, stem );
2037 0 : forward_msg = 0;
2038 0 : break;
2039 0 : }
2040 :
2041 0 : if( FD_UNLIKELY( validate_capitalization( ctx ) ) ) {
2042 0 : transition_malformed( ctx, stem );
2043 0 : forward_msg = 0;
2044 0 : break;
2045 0 : }
2046 :
2047 0 : fold_account_counts( ctx );
2048 0 : ctx->lead.recovery.capitalization = ctx->lead.manifest_capitalization;
2049 0 : fd_accdb_snapshot_save_whead( ctx->accdb, &ctx->lead.recovery.accdb_metadata );
2050 0 : ctx->lead.init_completed = 0;
2051 0 : break;
2052 0 : }
2053 :
2054 0 : case FD_SNAPSHOT_MSG_CTRL_DONE: {
2055 0 : FD_TEST( ctx->state==FD_SNAPSHOT_STATE_FINISHING );
2056 0 : ctx->state = FD_SNAPSHOT_STATE_IDLE;
2057 0 : if( FD_LIKELY( !is_lead( ctx ) ) ) break;
2058 :
2059 0 : if( FD_UNLIKELY( verify_sysvars( ctx ) ) ) {
2060 0 : if( ctx->full ) FD_LOG_WARNING(( "sysvar verification failed for full snapshot" ));
2061 0 : else FD_LOG_WARNING(( "sysvar verification failed for incremental snapshot" ));
2062 0 : transition_malformed( ctx, stem );
2063 0 : forward_msg = 0;
2064 0 : break;
2065 0 : }
2066 :
2067 0 : if( FD_UNLIKELY( validate_capitalization( ctx ) ) ) {
2068 0 : transition_malformed( ctx, stem );
2069 0 : forward_msg = 0;
2070 0 : break;
2071 0 : }
2072 :
2073 0 : fold_account_counts( ctx );
2074 0 : if( !ctx->full ) {
2075 0 : fd_accdb_snapshot_recover_delta( ctx->accdb, ctx->lead.accdb_incr_fork_id );
2076 : /* ensure that snapin tile sees all delta changes before rooting */
2077 0 : __atomic_thread_fence( __ATOMIC_SEQ_CST );
2078 0 : fd_accdb_advance_root( ctx->accdb, ctx->lead.accdb_incr_fork_id );
2079 0 : ctx->lead.accdb_root_fork_id = ctx->lead.accdb_incr_fork_id;
2080 0 : ctx->lead.accdb_incr_fork_id = (fd_accdb_fork_id_t){ .val = USHORT_MAX };
2081 0 : ushort stake_fork = FD_VOLATILE_CONST( ctx->shmem->stake_fork );
2082 0 : fd_stake_delegations_advance_root( 0UL, NULL, NULL, 0, 1, ctx->stake_delegations, stake_fork, NULL );
2083 0 : fd_stake_delegations_evict_fork( ctx->stake_delegations, stake_fork );
2084 0 : }
2085 :
2086 0 : fd_accdb_snapshot_load_end( ctx->accdb );
2087 :
2088 : /* TODO: Pass in tile_idx and tile_cnt when parallelizing snapin */
2089 0 : fd_features_restore_chunk( &ctx->lead.bank->f.features, ctx->accdb, ctx->lead.accdb_root_fork_id, ctx->lead.bank_slot, &ctx->lead.epoch_schedule, 0UL, 1UL );
2090 :
2091 : /* Notify replay when snapshot is fully loaded and verified. */
2092 0 : fd_stem_publish( stem, ctx->lead.manifest_out.idx, fd_ssmsg_sig( FD_SSMSG_DONE ), 0UL, 0UL, 0UL, 0UL, 0UL );
2093 0 : ctx->lead.init_completed = 0;
2094 0 : break;
2095 0 : }
2096 :
2097 0 : case FD_SNAPSHOT_MSG_CTRL_ERROR: {
2098 0 : FD_TEST( ctx->state!=FD_SNAPSHOT_STATE_SHUTDOWN );
2099 0 : ctx->state = FD_SNAPSHOT_STATE_ERROR;
2100 0 : break;
2101 0 : }
2102 :
2103 0 : case FD_SNAPSHOT_MSG_CTRL_FAIL: {
2104 0 : FD_TEST( ctx->state!=FD_SNAPSHOT_STATE_SHUTDOWN );
2105 0 : fd_accdb_flush_metrics( ctx->accdb );
2106 :
2107 0 : FD_COMPILER_MFENCE();
2108 :
2109 : /* Reset the worker state for this full/incr loading attempt */
2110 0 : reset_attempt_state( ctx );
2111 :
2112 : /* Defer rollback until the next INIT, which is triggered after
2113 : all workers have sent their FAIL acks. */
2114 0 : if( FD_UNLIKELY( is_lead( ctx ) ) ) {
2115 0 : FD_VOLATILE( ctx->shmem->fork_id ) = ULONG_MAX;
2116 0 : FD_COMPILER_MFENCE();
2117 :
2118 : /* Only a completed INIT has valid state to roll back. */
2119 0 : if( FD_LIKELY( ctx->lead.init_completed ) ) {
2120 0 : ctx->lead.rollback.pending = 1;
2121 0 : ctx->lead.rollback.full = ctx->full;
2122 0 : ctx->lead.rollback.fork = ctx->lead.accdb_incr_fork_id;
2123 0 : if( ctx->full ) ctx->lead.accdb_root_fork_id = (fd_accdb_fork_id_t){ .val = USHORT_MAX };
2124 0 : ctx->lead.accdb_incr_fork_id = (fd_accdb_fork_id_t){ .val = USHORT_MAX };
2125 0 : }
2126 0 : ctx->lead.init_completed = 0;
2127 0 : }
2128 :
2129 0 : ctx->state = FD_SNAPSHOT_STATE_IDLE;
2130 0 : break;
2131 0 : }
2132 :
2133 0 : case FD_SNAPSHOT_MSG_CTRL_SHUTDOWN: {
2134 0 : FD_TEST( ctx->state==FD_SNAPSHOT_STATE_IDLE );
2135 0 : ctx->state = FD_SNAPSHOT_STATE_SHUTDOWN;
2136 0 : break;
2137 0 : }
2138 :
2139 0 : default: {
2140 0 : FD_LOG_ERR(( "unexpected control frag %s (%lu) in state %s (%lu)",
2141 0 : fd_ssctrl_msg_ctrl_str( sig ), sig,
2142 0 : fd_ssctrl_state_str( (ulong)ctx->state ), (ulong)ctx->state ));
2143 0 : break;
2144 0 : }
2145 0 : }
2146 :
2147 : /* Forward the control message down the pipeline */
2148 0 : if( FD_LIKELY( forward_msg ) ) {
2149 0 : fd_stem_publish( stem, ctx->ct_out.idx, sig, 0UL, 0UL, 0UL, 0UL, 0UL );
2150 0 : }
2151 0 : }
2152 :
2153 : static inline int
2154 0 : all_controls_seen( fd_snapin_tile_t const * ctx ) {
2155 0 : int all_seen = 1;
2156 0 : for( ulong i=0UL; i<ctx->lane_cnt; i++ ) {
2157 0 : all_seen &= !!ctx->control_seen[ i ];
2158 0 : }
2159 0 : return all_seen;
2160 0 : }
2161 :
2162 : static inline int
2163 : before_frag( fd_snapin_tile_t * ctx,
2164 : ulong in_idx,
2165 : ulong seq FD_PARAM_UNUSED,
2166 0 : ulong sig ) {
2167 : /* If we're currently in ERROR state we should only process FAIL
2168 : control frags */
2169 0 : if( FD_UNLIKELY( ctx->state==FD_SNAPSHOT_STATE_ERROR ) ) {
2170 0 : return sig!=FD_SNAPSHOT_MSG_CTRL_FAIL;
2171 0 : }
2172 :
2173 0 : if( FD_UNLIKELY( sig==FD_SNAPSHOT_MSG_CTRL_ERROR ) ) {
2174 0 : return 0;
2175 0 : }
2176 :
2177 : /* Once this lane sends the pending control, hold its later frags
2178 : until all snapdc lanes send the same control. */
2179 0 : if( FD_UNLIKELY( ctx->pending_control!=ULONG_MAX && ctx->control_seen[ in_idx ] ) ) {
2180 0 : FD_TEST( sig!=ctx->pending_control );
2181 0 : return -1;
2182 0 : }
2183 :
2184 0 : if( FD_LIKELY( fd_snapdc_sig_type( sig )==FD_SNAPSHOT_MSG_DATA ) ) {
2185 : /* Only accept DATA frags for the expected frame */
2186 0 : ulong frame = fd_snapdc_sig_frame( sig );
2187 0 : FD_CHECK_ERR( frame>=ctx->expected_frame, "snapdc lane repeated a frame" );
2188 0 : if( FD_UNLIKELY( frame!=ctx->expected_frame ) ) return -1;
2189 0 : }
2190 :
2191 0 : return 0;
2192 0 : }
2193 :
2194 : static inline int
2195 : handle_lane_data_frag( fd_snapin_tile_t * ctx,
2196 : fd_stem_context_t * stem,
2197 : ulong in_idx,
2198 : ulong chunk,
2199 : ulong sz,
2200 0 : ulong ctl ) {
2201 0 : if( FD_UNLIKELY( ctx->incr_fork==ULONG_MAX ) ) {
2202 0 : start_processing_attempt( ctx );
2203 0 : }
2204 :
2205 : /* EOM marks the end of a frame */
2206 0 : int eom = !!fd_frag_meta_ctl_eom( ctl );
2207 :
2208 : /* The tar parser can reach EOF before snapdc reports the end of the
2209 : zstd frame. Only the empty EOM is valid (any payload after EOF is
2210 : malformed). */
2211 0 : int trailing_eom = ctx->state==FD_SNAPSHOT_STATE_FINISHING && eom && !sz;
2212 0 : if( FD_UNLIKELY( !trailing_eom && handle_data_frag( ctx, in_idx, chunk, sz, stem ) ) ) {
2213 0 : return 1;
2214 0 : }
2215 :
2216 0 : if( FD_UNLIKELY( eom ) ) {
2217 0 : ctx->expected_frame++;
2218 0 : }
2219 :
2220 0 : return 0;
2221 0 : }
2222 :
2223 : static inline void
2224 : handle_control_barrier( fd_snapin_tile_t * ctx,
2225 : fd_stem_context_t * stem,
2226 : ulong in_idx,
2227 : ulong sig,
2228 : ulong chunk,
2229 0 : ulong sz ) {
2230 : /* Error control frags must be immediately handled. */
2231 0 : if( FD_UNLIKELY( sig==FD_SNAPSHOT_MSG_CTRL_ERROR ) ) {
2232 0 : handle_control_frag( ctx, stem, in_idx, sig, chunk, sz );
2233 0 : return;
2234 0 : }
2235 :
2236 0 : if( FD_UNLIKELY( sig!=ctx->pending_control ) ) {
2237 0 : FD_TEST( ctx->pending_control==ULONG_MAX || sig==FD_SNAPSHOT_MSG_CTRL_FAIL );
2238 0 : clear_control_barrier( ctx );
2239 0 : ctx->pending_control = sig;
2240 0 : }
2241 :
2242 : /* Only process the control frag when all upstream tiles have sent
2243 : the same control message. */
2244 0 : FD_TEST( !ctx->control_seen[ in_idx ] );
2245 0 : ctx->control_seen[ in_idx ] = 1U;
2246 0 : if( FD_LIKELY( !all_controls_seen( ctx ) ) ) {
2247 0 : return;
2248 0 : }
2249 :
2250 : /* All controls received, process the control frag. */
2251 0 : clear_control_barrier( ctx );
2252 0 : handle_control_frag( ctx, stem, in_idx, sig, chunk, sz );
2253 0 : }
2254 :
2255 : static inline int
2256 : returnable_frag( fd_snapin_tile_t * ctx,
2257 : ulong in_idx,
2258 : ulong seq FD_PARAM_UNUSED,
2259 : ulong sig,
2260 : ulong chunk,
2261 : ulong sz,
2262 : ulong ctl,
2263 : ulong tsorig FD_PARAM_UNUSED,
2264 : ulong tspub FD_PARAM_UNUSED,
2265 0 : fd_stem_context_t * stem ) {
2266 0 : FD_TEST( ctx->state!=FD_SNAPSHOT_STATE_SHUTDOWN );
2267 :
2268 0 : if( FD_LIKELY( fd_snapdc_sig_type( sig )==FD_SNAPSHOT_MSG_DATA ) ) return handle_lane_data_frag( ctx, stem, in_idx, chunk, sz, ctl );
2269 0 : else handle_control_barrier( ctx, stem, in_idx, sig, chunk, sz );
2270 :
2271 0 : return 0;
2272 0 : }
2273 :
2274 : static ulong
2275 : populate_allowed_fds( fd_topo_t const * topo,
2276 : fd_topo_tile_t const * tile,
2277 : ulong out_fds_cnt,
2278 0 : int * out_fds ) {
2279 0 : if( FD_UNLIKELY( out_fds_cnt<5UL ) ) FD_LOG_ERR(( "invalid out_fds_cnt %lu", out_fds_cnt ));
2280 0 : fd_snapin_tile_t const * ctx = fd_topo_obj_laddr( topo, tile->tile_obj_id );
2281 :
2282 0 : ulong out_cnt = 0;
2283 0 : out_fds[ out_cnt++ ] = 2UL; /* stderr */
2284 0 : if( FD_LIKELY( -1!=fd_log_private_logfile_fd() ) ) {
2285 0 : out_fds[ out_cnt++ ] = fd_log_private_logfile_fd(); /* logfile */
2286 0 : }
2287 0 : out_fds[ out_cnt++ ] = FD_ACCDB_FD_RW; /* accounts db */
2288 0 : out_fds[ out_cnt++ ] = FD_STAKE_DELEGATIONS_FD; /* stake delegation disk spill */
2289 0 : out_fds[ out_cnt++ ] = ctx->writer.accdb_direct_fd; /* accounts db, O_DIRECT */
2290 :
2291 0 : return out_cnt;
2292 0 : }
2293 :
2294 : static ulong
2295 : populate_allowed_seccomp( fd_topo_t const * topo,
2296 : fd_topo_tile_t const * tile,
2297 : ulong out_cnt,
2298 0 : struct sock_filter * out ) {
2299 0 : fd_snapin_tile_t const * ctx = fd_topo_obj_laddr( topo, tile->tile_obj_id );
2300 0 : populate_sock_filter_policy_fd_snapin_tile( out_cnt, out, (uint)fd_log_private_logfile_fd(), FD_ACCDB_FD_RW, (uint)ctx->writer.accdb_direct_fd, FD_STAKE_DELEGATIONS_FD );
2301 0 : return sock_filter_policy_fd_snapin_tile_instr_cnt;
2302 0 : }
2303 :
2304 : static void
2305 : privileged_init( fd_topo_t const * topo,
2306 0 : fd_topo_tile_t const * tile ) {
2307 0 : fd_snapin_tile_t * ctx = fd_topo_obj_laddr( topo, tile->tile_obj_id );
2308 0 : memset( ctx, 0, sizeof(fd_snapin_tile_t) );
2309 0 : FD_TEST( fd_rng_secure( &ctx->lead.seed, 8UL ) );
2310 :
2311 0 : char path[ 64 ];
2312 0 : FD_TEST( fd_cstr_printf_check( path, sizeof(path), NULL, "/proc/self/fd/%d", FD_ACCDB_FD_RW ) );
2313 0 : ctx->writer.accdb_direct_fd = open( path, O_WRONLY|O_DIRECT|O_CLOEXEC );
2314 0 : FD_CHECK_ERR( ctx->writer.accdb_direct_fd>=0, "open(accounts.db, O_DIRECT) failed; the filesystem holding [paths.accounts] must support direct IO" );
2315 0 : }
2316 :
2317 : static inline fd_snapin_out_link_t
2318 : out1( fd_topo_t const * topo,
2319 : fd_topo_tile_t const * tile,
2320 : char const * name,
2321 0 : ulong kind_id ) {
2322 0 : ulong idx = fd_topo_find_tile_out_link( topo, tile, name, kind_id );
2323 :
2324 0 : if( FD_UNLIKELY( idx==ULONG_MAX ) ) return (fd_snapin_out_link_t){ .idx = ULONG_MAX, .mem = NULL, .chunk0 = 0, .wmark = 0, .chunk = 0, .mtu = 0 };
2325 :
2326 0 : ulong mtu = topo->links[ tile->out_link_id[ idx ] ].mtu;
2327 0 : if( FD_UNLIKELY( mtu==0UL ) ) return (fd_snapin_out_link_t){ .idx = idx, .mem = NULL, .chunk0 = ULONG_MAX, .wmark = ULONG_MAX, .chunk = ULONG_MAX, .mtu = mtu };
2328 :
2329 0 : void * mem = topo->workspaces[ topo->objs[ topo->links[ tile->out_link_id[ idx ] ].dcache_obj_id ].wksp_id ].wksp;
2330 0 : ulong chunk0 = fd_dcache_compact_chunk0( mem, topo->links[ tile->out_link_id[ idx ] ].dcache );
2331 0 : ulong wmark = fd_dcache_compact_wmark ( mem, topo->links[ tile->out_link_id[ idx ] ].dcache, mtu );
2332 0 : return (fd_snapin_out_link_t){ .idx = idx, .mem = mem, .chunk0 = chunk0, .wmark = wmark, .chunk = chunk0, .mtu = mtu };
2333 0 : }
2334 :
2335 : static void
2336 : unprivileged_init( fd_topo_t const * topo,
2337 0 : fd_topo_tile_t const * tile ) {
2338 0 : void * scratch = fd_topo_obj_laddr( topo, tile->tile_obj_id );
2339 :
2340 0 : FD_SCRATCH_ALLOC_INIT( l, scratch );
2341 0 : fd_snapin_tile_t * ctx = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_snapin_tile_t), sizeof(fd_snapin_tile_t) );
2342 0 : void * _accdb = FD_SCRATCH_ALLOC_APPEND( l, fd_accdb_align(), fd_accdb_footprint( tile->snapin.max_live_slots, 0 ) );
2343 :
2344 0 : ctx->tile_idx = tile->kind_id;
2345 0 : if( FD_UNLIKELY( ctx->tile_idx>=FD_TOPO_MAX_TILE_IN_LINKS ) ) FD_LOG_ERR(( "tile `" NAME "` has unsupported kind id %lu", tile->kind_id ));
2346 :
2347 0 : ctx->full = 1;
2348 0 : ctx->alpenglow = tile->snapin.alpenglow;
2349 0 : ctx->state = FD_SNAPSHOT_STATE_IDLE;
2350 0 : ctx->lane_cnt = tile->in_cnt;
2351 0 : clear_control_barrier( ctx );
2352 0 : fd_memset( &ctx->metrics, 0, sizeof(ctx->metrics) );
2353 :
2354 0 : void * _accdb_shmem = fd_topo_obj_laddr( topo, tile->snapin.accdb_obj_id );
2355 0 : fd_accdb_shmem_t * accdb_shmem = fd_accdb_shmem_join( _accdb_shmem );
2356 0 : FD_TEST( accdb_shmem );
2357 :
2358 0 : fd_sleep_t * accdb_sleep = topo->sleep_obj_id!=ULONG_MAX ? fd_sleep_join( fd_topo_obj_laddr( topo, topo->sleep_obj_id ) ) : NULL;
2359 0 : ctx->accdb = fd_accdb_join( fd_accdb_new( _accdb, accdb_shmem, FD_ACCDB_FD_RW, 0UL, NULL, accdb_sleep, fd_topo_find_tile( topo, "accdb", 0UL ), 0 ) );
2360 0 : FD_TEST( ctx->accdb );
2361 :
2362 0 : ctx->shmem = fd_topo_obj_laddr( topo, tile->snapin.shmem_obj_id );
2363 :
2364 : /* Every tile updates stakes. Only tile 0 owns the bank. */
2365 0 : fd_banks_t * banks = fd_banks_join( fd_topo_obj_laddr( topo, tile->snapin.banks_obj_id ) );
2366 0 : FD_TEST( banks );
2367 0 : ctx->stake_delegations = fd_banks_stake_delegations_root_query( banks );
2368 0 : FD_TEST( ctx->stake_delegations );
2369 :
2370 0 : ctx->ct_out = out1( topo, tile, "snapin_ct", ctx->tile_idx );
2371 0 : if( FD_UNLIKELY( ctx->ct_out.idx==ULONG_MAX ) ) FD_LOG_ERR(( "tile `" NAME ":%lu` missing required out link `snapin_ct`", ctx->tile_idx ));
2372 :
2373 0 : ctx->gui_out = out1( topo, tile, "snapin_gui", ctx->tile_idx );
2374 :
2375 0 : for( ulong i=0UL; i<ctx->lane_cnt; i++ ) {
2376 0 : fd_topo_link_t const * in_link = &topo->links[ tile->in_link_id[ i ] ];
2377 0 : FD_TEST( 0==strcmp( in_link->name, "snapdc_in" ) );
2378 0 : FD_TEST( in_link->kind_id==i );
2379 0 : fd_topo_wksp_t const * in_wksp = &topo->workspaces[ topo->objs[ in_link->dcache_obj_id ].wksp_id ];
2380 0 : ctx->in[ i ].wksp = in_wksp->wksp;
2381 0 : ctx->in[ i ].chunk0 = fd_dcache_compact_chunk0( ctx->in[ i ].wksp, in_link->dcache );
2382 0 : ctx->in[ i ].wmark = fd_dcache_compact_wmark( ctx->in[ i ].wksp, in_link->dcache, in_link->mtu );
2383 0 : ctx->in[ i ].mtu = in_link->mtu;
2384 0 : ctx->in[ i ].pos = 0UL;
2385 0 : }
2386 :
2387 0 : reset_attempt_state( ctx );
2388 0 : if( FD_LIKELY( !is_lead( ctx ) ) ) return;
2389 :
2390 : /* Tile 0 state. */
2391 0 : ctx->lead.init_completed = 0;
2392 0 : ctx->lead.txncache_max_groups_per_slot = tile->snapin.max_txn_per_slot;
2393 0 : ctx->lead.txncache_max_entries_per_slot = 2UL*tile->snapin.max_txn_per_slot;
2394 :
2395 0 : void * _txncache = FD_SCRATCH_ALLOC_APPEND( l, fd_txncache_align(), fd_txncache_footprint( tile->snapin.max_live_slots ) );
2396 0 : void * _manifest_parser = FD_SCRATCH_ALLOC_APPEND( l, fd_ssmanifest_parser_align(), fd_ssmanifest_parser_footprint() );
2397 0 : void * _sd_parser = FD_SCRATCH_ALLOC_APPEND( l, fd_slot_delta_parser_align(), fd_slot_delta_parser_footprint() );
2398 0 : ctx->lead.recent_groups = FD_SCRATCH_ALLOC_APPEND( l, alignof(recent_blockhash_group_t), sizeof(recent_blockhash_group_t)*FD_SNAPIN_MAX_RECENT_GROUPS );
2399 0 : ctx->lead.txncache_entries = FD_SCRATCH_ALLOC_APPEND( l, alignof(fd_sstxncache_hash_t), sizeof(fd_sstxncache_hash_t)*FD_TXNCACHE_MAX_SLOT_DELTAS*2UL*tile->snapin.max_txn_per_slot );
2400 :
2401 0 : void * _txncache_shmem = fd_topo_obj_laddr( topo, tile->snapin.txncache_obj_id );
2402 0 : fd_txncache_shmem_t * txncache_shmem = fd_txncache_shmem_join( _txncache_shmem );
2403 0 : FD_TEST( txncache_shmem );
2404 0 : ctx->lead.txncache = fd_txncache_join( fd_txncache_new( _txncache, txncache_shmem ) );
2405 0 : FD_TEST( ctx->lead.txncache );
2406 :
2407 0 : ctx->lead.blockhash_groups = NULL;
2408 0 : txncache_staging_reset( ctx );
2409 :
2410 0 : ctx->lead.bank = fd_banks_init_bank( banks );
2411 0 : FD_TEST( ctx->lead.bank );
2412 0 : FD_TEST( ctx->lead.bank->idx==0UL );
2413 :
2414 0 : ctx->lead.manifest_parser = fd_ssmanifest_parser_join( fd_ssmanifest_parser_new( _manifest_parser ) );
2415 0 : FD_TEST( ctx->lead.manifest_parser );
2416 :
2417 0 : ctx->lead.slot_delta_parser = fd_slot_delta_parser_join( fd_slot_delta_parser_new( _sd_parser ) );
2418 0 : FD_TEST( ctx->lead.slot_delta_parser );
2419 :
2420 0 : ctx->lead.manifest_out = out1( topo, tile, "snapin_manif", 0UL );
2421 0 : if( FD_UNLIKELY( ctx->lead.manifest_out.idx==ULONG_MAX ) ) FD_LOG_ERR(( "tile `" NAME "` missing required out link `snapin_manif`" ));
2422 :
2423 0 : fd_ssmanifest_parser_init( ctx->lead.manifest_parser, fd_chunk_to_laddr( ctx->lead.manifest_out.mem, ctx->lead.manifest_out.chunk ) );
2424 0 : fd_slot_delta_parser_init( ctx->lead.slot_delta_parser );
2425 :
2426 0 : ctx->lead.advertised_slot = 0UL;
2427 0 : ctx->lead.bank_slot = 0UL;
2428 0 : ctx->lead.epoch = 0UL;
2429 0 : ctx->lead.full_genesis_creation_time_seconds = 0UL;
2430 0 : ctx->lead.manifest_capitalization = 0UL;
2431 0 : ctx->lead.recovery.capitalization = 0UL;
2432 0 : fd_memset( &ctx->lead.account_counts, 0, sizeof(ctx->lead.account_counts) );
2433 0 : ctx->lead.accdb_root_fork_id = (fd_accdb_fork_id_t){ .val = USHORT_MAX };
2434 0 : ctx->lead.accdb_incr_fork_id = (fd_accdb_fork_id_t){ .val = USHORT_MAX };
2435 0 : fd_memset( &ctx->lead.recovery.accdb_metadata, 0, sizeof(ctx->lead.recovery.accdb_metadata) );
2436 0 : fd_memset( &ctx->lead.flags, 0, sizeof(ctx->lead.flags) );
2437 0 : ctx->lead.boot_timestamp = fd_log_wallclock();
2438 :
2439 0 : ctx->wfs_slot = tile->snapin.wait_for_supermajority_at_slot;
2440 0 : ctx->wfs_bank_hash = tile->snapin.wait_for_supermajority_with_bank_hash;
2441 0 : ctx->wfs_shred_version = tile->snapin.expected_shred_version;
2442 0 : ctx->wfs_hash_is_zero = !memcmp( ctx->wfs_bank_hash.uc, ((fd_hash_t){0}).uc, sizeof(fd_hash_t) );
2443 0 : }
2444 :
2445 : /* There are 3 output links that affect the calculation of STEM_BURST:
2446 : 1. snapin_ct - worst case: 1 message (ack or unsolicited ERROR)
2447 : 2. snapin_manif - worst case: 1 message (tile 0 only)
2448 : 3. snapin_gui - worst case: 1 message (config program account)
2449 : The STEM_BURST is the max value across these 3 links (not the sum).
2450 : Note that snapin_txn is excluded from this calculation, since it is
2451 : an unreliable link, working as a dcache place holder. */
2452 0 : #define STEM_BURST 1UL
2453 :
2454 0 : #define STEM_LAZY (128L*3000L)
2455 :
2456 0 : #define STEM_CALLBACK_CONTEXT_TYPE fd_snapin_tile_t
2457 0 : #define STEM_CALLBACK_CONTEXT_ALIGN alignof(fd_snapin_tile_t)
2458 :
2459 0 : #define STEM_CALLBACK_SHOULD_SHUTDOWN should_shutdown
2460 0 : #define STEM_CALLBACK_METRICS_WRITE metrics_write
2461 0 : #define STEM_CALLBACK_BEFORE_FRAG before_frag
2462 0 : #define STEM_CALLBACK_RETURNABLE_FRAG returnable_frag
2463 :
2464 : #include "../../disco/stem/fd_stem.c"
2465 :
2466 : static ulong
2467 0 : max_event_sz( fd_topo_tile_t const * tile FD_PARAM_UNUSED ) {
2468 0 : return sizeof(fd_event_accdb_partition_added_t);
2469 0 : }
2470 :
2471 : static ulong
2472 : snapin_shmem_footprint( fd_topo_t const * topo FD_PARAM_UNUSED,
2473 0 : fd_topo_obj_t const * obj FD_PARAM_UNUSED ) {
2474 0 : return sizeof(fd_snapin_shmem_t);
2475 0 : }
2476 :
2477 : static ulong
2478 : snapin_shmem_align( fd_topo_t const * topo FD_PARAM_UNUSED,
2479 0 : fd_topo_obj_t const * obj FD_PARAM_UNUSED ) {
2480 0 : return alignof(fd_snapin_shmem_t);
2481 0 : }
2482 :
2483 : static void
2484 : snapin_shmem_new( fd_topo_t const * topo,
2485 0 : fd_topo_obj_t const * obj ) {
2486 0 : fd_snapin_shmem_t * shmem = fd_topo_obj_laddr( topo, obj->id );
2487 0 : fd_memset( shmem, 0, sizeof(fd_snapin_shmem_t) );
2488 0 : shmem->fork_id = ULONG_MAX;
2489 0 : }
2490 :
2491 : fd_topo_obj_callbacks_t fd_obj_cb_snapin_shmem = {
2492 : .name = "snapin_shmem",
2493 : .footprint = snapin_shmem_footprint,
2494 : .align = snapin_shmem_align,
2495 : .new = snapin_shmem_new,
2496 : };
2497 :
2498 : fd_topo_run_tile_t fd_tile_snapin = {
2499 : .name = NAME,
2500 : .populate_allowed_fds = populate_allowed_fds,
2501 : .populate_allowed_seccomp = populate_allowed_seccomp,
2502 : .scratch_align = scratch_align,
2503 : .scratch_footprint = scratch_footprint,
2504 : .privileged_init = privileged_init,
2505 : .unprivileged_init = unprivileged_init,
2506 : .max_event_sz = max_event_sz,
2507 : .run = stem_run,
2508 : };
2509 :
2510 : #undef NAME
|