Line data Source code
1 : #include "fd_runtime.h"
2 : #include "../capture/fd_capture_ctx.h"
3 : #include "../types/fd_cast.h"
4 : #include "fd_alut.h"
5 : #include "fd_bank.h"
6 : #include "fd_executor_err.h"
7 : #include "fd_hashes.h"
8 : #include "fd_runtime_err.h"
9 : #include "fd_runtime_stack.h"
10 : #include "fd_acc_pool.h"
11 : #include "fd_genesis_parse.h"
12 : #include "fd_executor.h"
13 : #include "sysvar/fd_sysvar_cache.h"
14 : #include "sysvar/fd_sysvar_clock.h"
15 : #include "sysvar/fd_sysvar_epoch_schedule.h"
16 : #include "sysvar/fd_sysvar_recent_hashes.h"
17 : #include "sysvar/fd_sysvar_stake_history.h"
18 :
19 : #include "../stakes/fd_stakes.h"
20 : #include "../rewards/fd_rewards.h"
21 : #include "../accdb/fd_accdb_sync.h"
22 :
23 : #include "program/fd_builtin_programs.h"
24 : #include "program/fd_precompiles.h"
25 : #include "program/fd_program_util.h"
26 : #include "program/vote/fd_vote_state_versioned.h"
27 :
28 : #include "sysvar/fd_sysvar_clock.h"
29 : #include "sysvar/fd_sysvar_last_restart_slot.h"
30 : #include "sysvar/fd_sysvar_recent_hashes.h"
31 : #include "sysvar/fd_sysvar_rent.h"
32 : #include "sysvar/fd_sysvar_slot_hashes.h"
33 : #include "sysvar/fd_sysvar_slot_history.h"
34 :
35 : #include "tests/fd_dump_pb.h"
36 :
37 : #include "fd_system_ids.h"
38 :
39 : #include "../../disco/pack/fd_pack_tip_prog_blacklist.h"
40 :
41 : #include <unistd.h>
42 : #include <sys/stat.h>
43 : #include <sys/types.h>
44 : #include <fcntl.h>
45 :
46 : /******************************************************************************/
47 : /* Public Runtime Helpers */
48 : /******************************************************************************/
49 :
50 :
51 : /*
52 : https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/bank.rs#L1254-L1258
53 : https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/bank.rs#L1749
54 : */
55 : int
56 : fd_runtime_compute_max_tick_height( ulong ticks_per_slot,
57 : ulong slot,
58 0 : ulong * out_max_tick_height /* out */ ) {
59 0 : ulong max_tick_height = 0UL;
60 0 : if( FD_LIKELY( ticks_per_slot > 0UL ) ) {
61 0 : ulong next_slot = fd_ulong_sat_add( slot, 1UL );
62 0 : if( FD_UNLIKELY( next_slot == slot ) ) {
63 0 : FD_LOG_WARNING(( "max tick height addition overflowed slot %lu ticks_per_slot %lu", slot, ticks_per_slot ));
64 0 : return -1;
65 0 : }
66 0 : if( FD_UNLIKELY( ULONG_MAX / ticks_per_slot < next_slot ) ) {
67 0 : FD_LOG_WARNING(( "max tick height multiplication overflowed slot %lu ticks_per_slot %lu", slot, ticks_per_slot ));
68 0 : return -1;
69 0 : }
70 0 : max_tick_height = fd_ulong_sat_mul( next_slot, ticks_per_slot );
71 0 : }
72 0 : *out_max_tick_height = max_tick_height;
73 0 : return FD_RUNTIME_EXECUTE_SUCCESS;
74 0 : }
75 :
76 : static void
77 : update_next_leaders( fd_bank_t * bank,
78 : fd_runtime_stack_t * runtime_stack,
79 9 : fd_vote_stakes_t * vote_stakes ) {
80 :
81 9 : fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
82 :
83 9 : ulong epoch = fd_slot_to_epoch ( epoch_schedule, bank->f.slot, NULL ) + 1UL;
84 9 : ulong slot0 = fd_epoch_slot0 ( epoch_schedule, epoch );
85 9 : ulong slot_cnt = fd_epoch_slot_cnt( epoch_schedule, epoch );
86 :
87 9 : fd_top_votes_t const * top_votes_t_1 = fd_bank_top_votes_t_1_query( bank );
88 9 : fd_vote_stake_weight_t * epoch_weights = runtime_stack->stakes.stake_weights;
89 9 : ulong stake_weight_cnt = fd_stake_weights_by_node_next( top_votes_t_1, vote_stakes, bank->vote_stakes_fork_id, epoch_weights, FD_FEATURE_ACTIVE_BANK( bank, validator_admission_ticket ) );
90 :
91 9 : void * epoch_leaders_mem = fd_bank_epoch_leaders_modify( bank );
92 9 : fd_epoch_leaders_t * leaders = fd_epoch_leaders_join( fd_epoch_leaders_new(
93 9 : epoch_leaders_mem,
94 9 : epoch,
95 9 : slot0,
96 9 : slot_cnt,
97 9 : stake_weight_cnt,
98 9 : epoch_weights,
99 9 : 0UL ) );
100 9 : if( FD_UNLIKELY( !leaders ) ) {
101 0 : FD_LOG_ERR(( "Unable to init and join fd_epoch_leaders" ));
102 0 : }
103 :
104 : /* Populate a compressed set of stake weights for a valid leader
105 : schedule. */
106 9 : fd_vote_stake_weight_t * stake_weights = runtime_stack->epoch_weights.next_stake_weights;
107 9 : ulong idx = 0UL;
108 :
109 9 : int needs_compression = stake_weight_cnt>MAX_COMPRESSED_STAKE_WEIGHTS;
110 :
111 18 : for( ulong i=0UL; i<stake_weight_cnt; i++ ) {
112 9 : fd_pubkey_t const * vote_pubkey = &epoch_weights[i].vote_key;
113 9 : fd_pubkey_t const * node_pubkey = &epoch_weights[i].id_key;
114 9 : ulong stake = epoch_weights[i].stake;
115 :
116 9 : if( FD_LIKELY( !needs_compression || fd_epoch_leaders_is_leader_idx( leaders, i ) ) ) {
117 9 : stake_weights[ idx ].stake = stake;
118 9 : memcpy( stake_weights[ idx ].id_key.uc, node_pubkey, sizeof(fd_pubkey_t) );
119 9 : memcpy( stake_weights[ idx ].vote_key.uc, vote_pubkey, sizeof(fd_pubkey_t) );
120 9 : idx++;
121 9 : } else if( idx!=0UL && !fd_epoch_leaders_is_leader_idx( leaders, i-1UL ) ) {
122 0 : stake_weights[ idx-1UL ].stake += stake;
123 0 : } else {
124 0 : stake_weights[ idx ].id_key = (fd_pubkey_t){ .uc = FD_DUMMY_ACCOUNT };
125 0 : stake_weights[ idx ].vote_key = (fd_pubkey_t){ .uc = FD_DUMMY_ACCOUNT };
126 0 : stake_weights[ idx ].stake = stake;
127 0 : idx++;
128 0 : }
129 9 : }
130 9 : runtime_stack->epoch_weights.next_stake_weights_cnt = idx;
131 :
132 : /* Produce truncated set of id weights to send to Shred tile for
133 : Turbine tree computation. */
134 9 : ulong staked_cnt = compute_id_weights_from_vote_weights( runtime_stack->stakes.id_weights, epoch_weights, stake_weight_cnt );
135 9 : ulong excluded_stake = 0UL;
136 9 : if( FD_UNLIKELY( staked_cnt>MAX_SHRED_DESTS ) ) {
137 0 : for( ulong i=MAX_SHRED_DESTS; i<staked_cnt; i++ ) {
138 0 : excluded_stake += runtime_stack->stakes.id_weights[i].stake;
139 0 : }
140 0 : }
141 9 : staked_cnt = fd_ulong_min( staked_cnt, MAX_SHRED_DESTS );
142 9 : memcpy( runtime_stack->epoch_weights.next_id_weights, runtime_stack->stakes.id_weights, staked_cnt * sizeof(fd_stake_weight_t) );
143 9 : runtime_stack->epoch_weights.next_id_weights_cnt = staked_cnt;
144 9 : runtime_stack->epoch_weights.next_id_weights_excluded = excluded_stake;
145 9 : }
146 :
147 : void
148 : fd_runtime_update_leaders( fd_bank_t * bank,
149 9 : fd_runtime_stack_t * runtime_stack ) {
150 :
151 9 : fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
152 :
153 9 : ulong epoch = fd_slot_to_epoch ( epoch_schedule, bank->f.slot, NULL );
154 9 : ulong slot0 = fd_epoch_slot0 ( epoch_schedule, epoch );
155 9 : ulong slot_cnt = fd_epoch_slot_cnt( epoch_schedule, epoch );
156 :
157 9 : fd_vote_stakes_t * vote_stakes = fd_bank_vote_stakes( bank );
158 :
159 9 : update_next_leaders( bank, runtime_stack, vote_stakes );
160 :
161 9 : fd_top_votes_t const * top_votes_t_2 = fd_bank_top_votes_t_2_query( bank );
162 9 : fd_vote_stake_weight_t * epoch_weights = runtime_stack->stakes.stake_weights;
163 9 : ulong stake_weight_cnt = fd_stake_weights_by_node( top_votes_t_2, vote_stakes, bank->vote_stakes_fork_id, epoch_weights, FD_FEATURE_ACTIVE_BANK( bank, validator_admission_ticket ) );
164 :
165 : /* TODO: Can optimize by avoiding recomputing if another fork has
166 : already computed them for this epoch. */
167 9 : void * epoch_leaders_mem = fd_bank_epoch_leaders_modify( bank );
168 9 : fd_epoch_leaders_t * leaders = fd_epoch_leaders_join( fd_epoch_leaders_new(
169 9 : epoch_leaders_mem,
170 9 : epoch,
171 9 : slot0,
172 9 : slot_cnt,
173 9 : stake_weight_cnt,
174 9 : epoch_weights,
175 9 : 0UL ) );
176 9 : if( FD_UNLIKELY( !leaders ) ) {
177 0 : FD_LOG_ERR(( "Unable to init and join fd_epoch_leaders" ));
178 0 : }
179 :
180 : /* Populate a compressed set of stake weights for a valid leader
181 : schedule. */
182 9 : fd_vote_stake_weight_t * stake_weights = runtime_stack->epoch_weights.stake_weights;
183 9 : ulong idx = 0UL;
184 :
185 9 : int needs_compression = stake_weight_cnt>MAX_COMPRESSED_STAKE_WEIGHTS;
186 :
187 18 : for( ulong i=0UL; i<leaders->pub_cnt; i++ ) {
188 9 : fd_pubkey_t const * vote_pubkey = &epoch_weights[i].vote_key;
189 9 : fd_pubkey_t const * node_pubkey = &epoch_weights[i].id_key;
190 9 : ulong stake = epoch_weights[i].stake;
191 :
192 9 : if( FD_LIKELY( !needs_compression || fd_epoch_leaders_is_leader_idx( leaders, i ) ) ) {
193 9 : stake_weights[ idx ].stake = stake;
194 9 : memcpy( stake_weights[ idx ].id_key.uc, node_pubkey, sizeof(fd_pubkey_t) );
195 9 : memcpy( stake_weights[ idx ].vote_key.uc, vote_pubkey, sizeof(fd_pubkey_t) );
196 9 : idx++;
197 9 : } else if( idx!=0UL && !fd_epoch_leaders_is_leader_idx( leaders, i-1UL ) ) {
198 0 : stake_weights[ idx-1UL ].stake += stake;
199 0 : } else {
200 0 : stake_weights[ idx ].id_key = (fd_pubkey_t){ .uc = FD_DUMMY_ACCOUNT };
201 0 : stake_weights[ idx ].vote_key = (fd_pubkey_t){ .uc = FD_DUMMY_ACCOUNT };
202 0 : stake_weights[ idx ].stake = stake;
203 0 : idx++;
204 0 : }
205 9 : }
206 9 : runtime_stack->epoch_weights.stake_weights_cnt = idx;
207 :
208 : /* Produce truncated set of id weights to send to Shred tile for
209 : Turbine tree computation. */
210 9 : ulong staked_cnt = compute_id_weights_from_vote_weights( runtime_stack->stakes.id_weights, epoch_weights, stake_weight_cnt );
211 9 : ulong excluded_stake = 0UL;
212 9 : if( FD_UNLIKELY( staked_cnt>MAX_SHRED_DESTS ) ) {
213 0 : for( ulong i=MAX_SHRED_DESTS; i<staked_cnt; i++ ) {
214 0 : excluded_stake += runtime_stack->stakes.id_weights[i].stake;
215 0 : }
216 0 : }
217 9 : staked_cnt = fd_ulong_min( staked_cnt, MAX_SHRED_DESTS );
218 9 : memcpy( runtime_stack->epoch_weights.id_weights, runtime_stack->stakes.id_weights, staked_cnt * sizeof(fd_stake_weight_t) );
219 9 : runtime_stack->epoch_weights.id_weights_cnt = staked_cnt;
220 9 : runtime_stack->epoch_weights.id_weights_excluded = excluded_stake;
221 9 : }
222 :
223 : /******************************************************************************/
224 : /* Various Private Runtime Helpers */
225 : /******************************************************************************/
226 :
227 : static int
228 : fd_runtime_validate_fee_collector( fd_bank_t const * bank,
229 : fd_accdb_ro_t const * collector,
230 0 : ulong fee ) {
231 0 : if( FD_UNLIKELY( !fee ) ) FD_LOG_CRIT(( "invariant violation: fee>0" ));
232 :
233 0 : if( FD_UNLIKELY( !fd_pubkey_eq( fd_accdb_ref_owner( collector ), &fd_solana_system_program_id ) ) ) {
234 0 : return 0;
235 0 : }
236 :
237 : /* https://github.com/anza-xyz/agave/blob/v1.18.23/runtime/src/bank/fee_distribution.rs#L111
238 : https://github.com/anza-xyz/agave/blob/v1.18.23/runtime/src/accounts/account_rent_state.rs#L39
239 : In agave's fee deposit code, rent state transition check logic is as follows:
240 : The transition is NOT allowed iff
241 : === BEGIN
242 : the post deposit account is rent paying AND the pre deposit account is not rent paying
243 : OR
244 : the post deposit account is rent paying AND the pre deposit account is rent paying AND !(post_data_size == pre_data_size && post_lamports <= pre_lamports)
245 : === END
246 : post_data_size == pre_data_size is always true during fee deposit.
247 : However, post_lamports > pre_lamports because we are paying a >0 amount.
248 : So, the above reduces down to
249 : === BEGIN
250 : the post deposit account is rent paying AND the pre deposit account is not rent paying
251 : OR
252 : the post deposit account is rent paying AND the pre deposit account is rent paying AND TRUE
253 : === END
254 : This is equivalent to checking that the post deposit account is rent paying.
255 : An account is rent paying if the post deposit balance is >0 AND it's not rent exempt.
256 : We already know that the post deposit balance is >0 because we are paying a >0 amount.
257 : So TLDR we just check if the account is rent exempt.
258 : */
259 0 : fd_rent_t const * rent = &bank->f.rent;
260 0 : ulong minbal = fd_rent_exempt_minimum_balance( rent, fd_accdb_ref_data_sz( collector ) );
261 0 : ulong balance = fd_accdb_ref_lamports( collector );
262 0 : if( FD_UNLIKELY( __builtin_uaddl_overflow( balance, fee, &balance ) ) ) {
263 0 : FD_BASE58_ENCODE_32_BYTES( fd_accdb_ref_address( collector ), addr_b58 );
264 0 : FD_LOG_EMERG(( "integer overflow while crediting %lu fee reward lamports to %s (previous balance %lu)",
265 0 : fee, addr_b58, fd_accdb_ref_lamports( collector ) ));
266 0 : }
267 0 : if( FD_UNLIKELY( balance<minbal ) ) {
268 : /* fee collector not rent exempt after payout */
269 0 : return 0;
270 0 : }
271 :
272 0 : return 1;
273 0 : }
274 :
275 : static void
276 : fd_runtime_run_incinerator( fd_bank_t * bank,
277 : fd_accdb_user_t * accdb,
278 : fd_funk_txn_xid_t const * xid,
279 0 : fd_capture_ctx_t * capture_ctx ) {
280 0 : fd_pubkey_t const * address = &fd_sysvar_incinerator_id;
281 0 : fd_accdb_rw_t rw[1];
282 0 : if( !fd_accdb_open_rw( accdb, rw, xid, address, 0UL, 0 ) ) {
283 : /* Incinerator account does not exist, nothing to do */
284 0 : return;
285 0 : }
286 :
287 0 : fd_lthash_value_t prev_hash[1];
288 0 : fd_hashes_account_lthash( address, rw->meta, fd_accdb_ref_data_const( rw->ro ), prev_hash );
289 :
290 : /* Deleting account reduces capitalization */
291 0 : ulong new_capitalization = fd_ulong_sat_sub( bank->f.capitalization, fd_accdb_ref_lamports( rw->ro ) );
292 0 : bank->f.capitalization = new_capitalization;
293 :
294 : /* Delete incinerator account */
295 0 : fd_accdb_ref_lamports_set( rw, 0UL );
296 0 : fd_hashes_update_lthash( address, rw->meta, prev_hash, bank, capture_ctx );
297 0 : fd_accdb_close_rw( accdb, rw );
298 0 : }
299 :
300 : /* fd_runtime_settle_fees settles transaction fees accumulated during a
301 : slot. A portion is burnt, another portion is credited to the fee
302 : collector (typically leader). */
303 :
304 : static void
305 : fd_runtime_settle_fees( fd_bank_t * bank,
306 : fd_accdb_user_t * accdb,
307 : fd_funk_txn_xid_t const * xid,
308 0 : fd_capture_ctx_t * capture_ctx ) {
309 :
310 0 : ulong slot = bank->f.slot;
311 0 : ulong execution_fees = bank->f.execution_fees;
312 0 : ulong priority_fees = bank->f.priority_fees;
313 :
314 0 : ulong burn = execution_fees / 2;
315 0 : ulong fees = fd_ulong_sat_add( priority_fees, execution_fees - burn );
316 :
317 0 : if( FD_UNLIKELY( !fees ) ) return;
318 :
319 0 : fd_epoch_leaders_t const * leaders = fd_bank_epoch_leaders_query( bank );
320 0 : if( FD_UNLIKELY( !leaders ) ) FD_LOG_CRIT(( "fd_bank_epoch_leaders_query returned NULL" ));
321 :
322 0 : fd_pubkey_t const * leader = fd_epoch_leaders_get( leaders, bank->f.slot );
323 0 : if( FD_UNLIKELY( !leader ) ) FD_LOG_CRIT(( "fd_epoch_leaders_get(%lu) returned NULL", bank->f.slot ));
324 :
325 : /* Credit fee collector, creating it if necessary */
326 0 : fd_accdb_rw_t rw[1];
327 0 : fd_accdb_open_rw( accdb, rw, xid, leader, 0UL, FD_ACCDB_FLAG_CREATE );
328 0 : fd_lthash_value_t prev_hash[1];
329 0 : fd_hashes_account_lthash( leader, rw->meta, fd_accdb_ref_data_const( rw->ro ), prev_hash );
330 :
331 0 : if( FD_UNLIKELY( !fd_runtime_validate_fee_collector( bank, rw->ro, fees ) ) ) { /* validation failed */
332 0 : burn = fd_ulong_sat_add( burn, fees );
333 0 : FD_LOG_INFO(( "slot %lu has an invalid fee collector, burning fee reward (%lu lamports)", bank->f.slot, fees ));
334 0 : } else {
335 : /* Guaranteed to not overflow, checked above */
336 0 : fd_accdb_ref_lamports_set( rw, fd_accdb_ref_lamports( rw->ro ) + fees );
337 0 : fd_hashes_update_lthash( fd_accdb_ref_address( rw->ro ), rw->meta, prev_hash, bank, capture_ctx );
338 0 : }
339 :
340 0 : fd_accdb_close_rw( accdb, rw );
341 :
342 0 : ulong old = bank->f.capitalization;
343 0 : bank->f.capitalization = fd_ulong_sat_sub( old, burn );
344 0 : FD_LOG_INFO(( "slot %lu: burn %lu, capitalization %lu->%lu",
345 0 : slot, burn, old, bank->f.capitalization ));
346 0 : }
347 :
348 : static void
349 : fd_runtime_freeze( fd_bank_t * bank,
350 : fd_accdb_user_t * accdb,
351 0 : fd_capture_ctx_t * capture_ctx ) {
352 :
353 0 : fd_funk_txn_xid_t const xid = { .ul = { bank->f.slot, bank->idx } };
354 :
355 0 : if( FD_LIKELY( bank->f.slot != 0UL ) ) {
356 0 : fd_sysvar_recent_hashes_update( bank, accdb, &xid, capture_ctx );
357 0 : }
358 :
359 0 : fd_sysvar_slot_history_update( bank, accdb, &xid, capture_ctx );
360 :
361 0 : fd_runtime_settle_fees( bank, accdb, &xid, capture_ctx );
362 :
363 : /* jito collects a 3% fee at the end of the block + 3% fee at
364 : distribution time. */
365 0 : ulong tips_pre_comission = bank->f.tips;
366 0 : bank->f.tips = (tips_pre_comission - (tips_pre_comission * 6UL / 100UL));
367 :
368 0 : fd_runtime_run_incinerator( bank, accdb, &xid, capture_ctx );
369 :
370 0 : }
371 :
372 : /******************************************************************************/
373 : /* Block-Level Execution Preparation/Finalization */
374 : /******************************************************************************/
375 : void
376 : fd_runtime_new_fee_rate_governor_derived( fd_bank_t * bank,
377 108 : ulong latest_signatures_per_slot ) {
378 :
379 108 : fd_fee_rate_governor_t const * base_fee_rate_governor = &bank->f.fee_rate_governor;
380 :
381 108 : ulong old_lamports_per_signature = bank->f.rbh_lamports_per_sig;
382 :
383 108 : fd_fee_rate_governor_t me = {
384 108 : .target_signatures_per_slot = base_fee_rate_governor->target_signatures_per_slot,
385 108 : .target_lamports_per_signature = base_fee_rate_governor->target_lamports_per_signature,
386 108 : .max_lamports_per_signature = base_fee_rate_governor->max_lamports_per_signature,
387 108 : .min_lamports_per_signature = base_fee_rate_governor->min_lamports_per_signature,
388 108 : .burn_percent = base_fee_rate_governor->burn_percent
389 108 : };
390 :
391 108 : ulong new_lamports_per_signature = 0;
392 108 : if( me.target_signatures_per_slot > 0 ) {
393 0 : me.min_lamports_per_signature = fd_ulong_max( 1UL, (ulong)(me.target_lamports_per_signature / 2) );
394 0 : me.max_lamports_per_signature = me.target_lamports_per_signature * 10;
395 0 : ulong desired_lamports_per_signature = fd_ulong_min(
396 0 : me.max_lamports_per_signature,
397 0 : fd_ulong_max(
398 0 : me.min_lamports_per_signature,
399 0 : me.target_lamports_per_signature
400 0 : * fd_ulong_min(latest_signatures_per_slot, (ulong)UINT_MAX)
401 0 : / me.target_signatures_per_slot
402 0 : )
403 0 : );
404 0 : long gap = (long)desired_lamports_per_signature - (long)old_lamports_per_signature;
405 0 : if ( gap == 0 ) {
406 0 : new_lamports_per_signature = desired_lamports_per_signature;
407 0 : } else {
408 0 : long gap_adjust = (long)(fd_ulong_max( 1UL, (ulong)(me.target_lamports_per_signature / 20) ))
409 0 : * (gap != 0)
410 0 : * (gap > 0 ? 1 : -1);
411 0 : new_lamports_per_signature = fd_ulong_min(
412 0 : me.max_lamports_per_signature,
413 0 : fd_ulong_max(
414 0 : me.min_lamports_per_signature,
415 0 : (ulong)((long)old_lamports_per_signature + gap_adjust)
416 0 : )
417 0 : );
418 0 : }
419 108 : } else {
420 108 : new_lamports_per_signature = base_fee_rate_governor->target_lamports_per_signature;
421 108 : me.min_lamports_per_signature = me.target_lamports_per_signature;
422 108 : me.max_lamports_per_signature = me.target_lamports_per_signature;
423 108 : }
424 108 : bank->f.fee_rate_governor = me;
425 108 : bank->f.rbh_lamports_per_sig = new_lamports_per_signature;
426 108 : }
427 :
428 : /******************************************************************************/
429 : /* Epoch Boundary */
430 : /******************************************************************************/
431 :
432 : /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6704 */
433 : static void
434 : fd_apply_builtin_program_feature_transitions( fd_bank_t * bank,
435 : fd_accdb_user_t * accdb,
436 : fd_funk_txn_xid_t const * xid,
437 : fd_runtime_stack_t * runtime_stack,
438 9 : fd_capture_ctx_t * capture_ctx ) {
439 : /* TODO: Set the upgrade authority properly from the core bpf migration config. Right now it's set to None.
440 :
441 : Migrate any necessary stateless builtins to core BPF. So far,
442 : the only "stateless" builtin is the Feature program. Beginning
443 : checks in the migrate_builtin_to_core_bpf function will fail if the
444 : program has already been migrated to BPF. */
445 :
446 9 : fd_builtin_program_t const * builtins = fd_builtins();
447 90 : for( ulong i=0UL; i<fd_num_builtins(); i++ ) {
448 : /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6732-L6751 */
449 81 : if( builtins[i].core_bpf_migration_config && FD_FEATURE_ACTIVE_OFFSET( bank->f.slot, &bank->f.features, builtins[i].core_bpf_migration_config->enable_feature_offset ) ) {
450 0 : FD_BASE58_ENCODE_32_BYTES( builtins[i].pubkey->key, pubkey_b58 );
451 0 : FD_LOG_DEBUG(( "Migrating builtin program %s to core BPF", pubkey_b58 ));
452 0 : fd_migrate_builtin_to_core_bpf( bank, accdb, xid, runtime_stack, builtins[i].core_bpf_migration_config, capture_ctx );
453 0 : }
454 : /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6753-L6774 */
455 81 : if( builtins[i].enable_feature_offset!=NO_ENABLE_FEATURE_ID && FD_FEATURE_JUST_ACTIVATED_OFFSET( bank, builtins[i].enable_feature_offset ) ) {
456 0 : FD_BASE58_ENCODE_32_BYTES( builtins[i].pubkey->key, pubkey_b58 );
457 0 : FD_LOG_DEBUG(( "Enabling builtin program %s", pubkey_b58 ));
458 0 : fd_write_builtin_account( bank, accdb, xid, capture_ctx, *builtins[i].pubkey, builtins[i].data,strlen(builtins[i].data) );
459 0 : }
460 81 : }
461 :
462 : /* https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6776-L6793 */
463 9 : fd_stateless_builtin_program_t const * stateless_builtins = fd_stateless_builtins();
464 27 : for( ulong i=0UL; i<fd_num_stateless_builtins(); i++ ) {
465 18 : if( stateless_builtins[i].core_bpf_migration_config && FD_FEATURE_ACTIVE_OFFSET( bank->f.slot, &bank->f.features, stateless_builtins[i].core_bpf_migration_config->enable_feature_offset ) ) {
466 0 : FD_BASE58_ENCODE_32_BYTES( stateless_builtins[i].pubkey->key, pubkey_b58 );
467 0 : FD_LOG_DEBUG(( "Migrating stateless builtin program %s to core BPF", pubkey_b58 ));
468 0 : fd_migrate_builtin_to_core_bpf( bank, accdb, xid, runtime_stack, stateless_builtins[i].core_bpf_migration_config, capture_ctx );
469 0 : }
470 18 : }
471 :
472 : /* https://github.com/anza-xyz/agave/blob/c1080de464cfb578c301e975f498964b5d5313db/runtime/src/bank.rs#L6795-L6805 */
473 36 : for( fd_precompile_program_t const * precompiles = fd_precompiles(); precompiles->verify_fn; precompiles++ ) {
474 27 : if( precompiles->feature_offset != NO_ENABLE_FEATURE_ID &&
475 27 : FD_FEATURE_JUST_ACTIVATED_OFFSET( bank, precompiles->feature_offset ) ) {
476 0 : fd_write_builtin_account( bank, accdb, xid, capture_ctx, *precompiles->pubkey, "", 0 );
477 0 : }
478 27 : }
479 9 : }
480 :
481 : static void
482 : fd_feature_activate( fd_bank_t * bank,
483 : fd_accdb_user_t * accdb,
484 : fd_funk_txn_xid_t const * xid,
485 : fd_capture_ctx_t * capture_ctx,
486 : fd_feature_id_t const * id,
487 2412 : fd_pubkey_t const * addr ) {
488 2412 : fd_features_t * features = &bank->f.features;
489 :
490 2412 : if( id->reverted==1 ) return;
491 :
492 2313 : fd_accdb_ro_t ro[1];
493 2313 : if( FD_UNLIKELY( !fd_accdb_open_ro( accdb, ro, xid, addr ) ) ) {
494 2313 : return;
495 2313 : }
496 :
497 0 : if( FD_UNLIKELY( !fd_pubkey_eq( fd_accdb_ref_owner( ro ), &fd_solana_feature_program_id ) ) ) {
498 : /* Feature account not yet initialized */
499 0 : fd_accdb_close_ro( accdb, ro );
500 0 : return;
501 0 : }
502 :
503 0 : FD_BASE58_ENCODE_32_BYTES( addr->uc, addr_b58 );
504 :
505 0 : fd_feature_t feature;
506 0 : if( FD_UNLIKELY( !fd_feature_decode( &feature, fd_accdb_ref_data_const( ro ), fd_accdb_ref_data_sz( ro ) ) ) ) {
507 0 : FD_LOG_WARNING(( "cannot activate feature %s, corrupt account data", addr_b58 ));
508 0 : FD_LOG_HEXDUMP_NOTICE(( "corrupt feature account", fd_accdb_ref_data_const( ro ), fd_accdb_ref_data_sz( ro ) ));
509 0 : fd_accdb_close_ro( accdb, ro );
510 0 : return;
511 0 : }
512 0 : fd_accdb_close_ro( accdb, ro );
513 :
514 0 : if( feature.is_active ) {
515 0 : FD_LOG_DEBUG(( "feature %s already activated at slot %lu", addr_b58, feature.activation_slot ));
516 0 : fd_features_set( features, id, feature.activation_slot);
517 0 : } else {
518 0 : FD_LOG_DEBUG(( "feature %s not activated at slot %lu, activating", addr_b58, bank->f.slot ));
519 0 : fd_accdb_rw_t rw[1];
520 0 : if( FD_UNLIKELY( !fd_accdb_open_rw( accdb, rw, xid, addr, 0UL, 0 ) ) ) return;
521 0 : fd_lthash_value_t prev_hash[1];
522 0 : fd_hashes_account_lthash( addr, rw->meta, fd_accdb_ref_data_const( rw->ro ), prev_hash );
523 0 : feature.is_active = 1;
524 0 : feature.activation_slot = bank->f.slot;
525 0 : FD_CRIT( fd_accdb_ref_data_sz( rw->ro )>=sizeof(fd_feature_t), "unreachable" );
526 0 : FD_STORE( fd_feature_t, fd_accdb_ref_data( rw ), feature );
527 0 : fd_hashes_update_lthash( addr, rw->meta, prev_hash, bank, capture_ctx );
528 0 : fd_accdb_close_rw( accdb, rw );
529 0 : }
530 0 : }
531 :
532 : static void
533 : fd_features_activate( fd_bank_t * bank,
534 : fd_accdb_user_t * accdb,
535 : fd_funk_txn_xid_t const * xid,
536 9 : fd_capture_ctx_t * capture_ctx ) {
537 9 : for( fd_feature_id_t const * id = fd_feature_iter_init();
538 2421 : !fd_feature_iter_done( id );
539 2412 : id = fd_feature_iter_next( id ) ) {
540 2412 : fd_feature_activate( bank, accdb, xid, capture_ctx, id, &id->id );
541 2412 : }
542 9 : }
543 :
544 : /* SIMD-0194: deprecate_rent_exemption_threshold
545 : https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5322-L5329 */
546 : static void
547 : deprecate_rent_exemption_threshold( fd_bank_t * bank,
548 : fd_accdb_user_t * accdb,
549 : fd_funk_txn_xid_t const * xid,
550 3 : fd_capture_ctx_t * capture_ctx ) {
551 : /* We use the bank fields here to mirror Agave - in mainnet, devnet
552 : and testnet Agave's bank rent.burn_percent field is different to
553 : the value in the sysvar. When this feature is activated in Agave,
554 : the sysvar inherits the value from the bank. */
555 3 : fd_rent_t rent = bank->f.rent;
556 3 : rent.lamports_per_uint8_year = fd_rust_cast_double_to_ulong(
557 3 : (double)rent.lamports_per_uint8_year * rent.exemption_threshold );
558 3 : rent.exemption_threshold = FD_SIMD_0194_NEW_RENT_EXEMPTION_THRESHOLD;
559 :
560 : /* We don't refresh the sysvar cache here. The cache is refreshed in
561 : fd_sysvar_cache_restore, which is called at the start of every
562 : block in fd_runtime_block_execute_prepare, after this function. */
563 3 : fd_sysvar_rent_write( bank, accdb, xid, capture_ctx, &rent );
564 3 : bank->f.rent = rent;
565 3 : }
566 :
567 : // https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5296-L5391
568 : static void
569 : fd_compute_and_apply_new_feature_activations( fd_bank_t * bank,
570 : fd_accdb_user_t * accdb,
571 : fd_funk_txn_xid_t const * xid,
572 : fd_runtime_stack_t * runtime_stack,
573 9 : fd_capture_ctx_t * capture_ctx ) {
574 : /* Activate new features
575 : https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5296-L5391 */
576 9 : fd_features_activate( bank, accdb, xid, capture_ctx );
577 9 : fd_features_restore( bank, accdb, xid );
578 :
579 : /* SIMD-0194: deprecate_rent_exemption_threshold
580 : https://github.com/anza-xyz/agave/blob/v3.1.4/runtime/src/bank.rs#L5322-L5329 */
581 9 : if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, deprecate_rent_exemption_threshold ) ) ) {
582 3 : deprecate_rent_exemption_threshold( bank, accdb, xid, capture_ctx );
583 3 : }
584 :
585 : /* Apply builtin program feature transitions
586 : https://github.com/anza-xyz/agave/blob/v2.1.0/runtime/src/bank.rs#L6621-L6624 */
587 9 : fd_apply_builtin_program_feature_transitions( bank, accdb, xid, runtime_stack, capture_ctx );
588 :
589 9 : if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, vote_state_v4 ) ) ) {
590 0 : fd_upgrade_core_bpf_program( bank, accdb, xid, runtime_stack, &fd_solana_stake_program_id, &fd_solana_stake_program_vote_state_v4_buffer_address, capture_ctx );
591 0 : }
592 :
593 : /* https://github.com/anza-xyz/agave/blob/v4.0.0-beta.2/runtime/src/bank.rs#L5703-L5716 */
594 9 : if( FD_UNLIKELY( FD_FEATURE_JUST_ACTIVATED_BANK( bank, replace_spl_token_with_p_token ) ) ) {
595 0 : fd_upgrade_loader_v2_program_with_loader_v3_program(
596 0 : bank,
597 0 : accdb,
598 0 : xid,
599 0 : runtime_stack,
600 0 : &fd_solana_spl_token_id,
601 0 : &fd_solana_ptoken_program_buffer_address,
602 0 : FD_FEATURE_ACTIVE_BANK( bank, relax_programdata_account_check_migration ),
603 0 : capture_ctx );
604 0 : }
605 9 : }
606 :
607 : /* Starting a new epoch.
608 : New epoch: T
609 : Just ended epoch: T-1
610 : Epoch before: T-2
611 :
612 : In this function:
613 : - stakes in T-2 (vote_states_prev_prev) should be replaced by T-1 (vote_states_prev)
614 : - stakes at T-1 (vote_states_prev) should be replaced by updated stakes at T (vote_states)
615 : - leader schedule should be calculated using new T-2 stakes (vote_states_prev_prev)
616 :
617 : Invariant during an epoch T:
618 : vote_states_prev holds the stakes at T-1
619 : vote_states_prev_prev holds the stakes at T-2
620 : */
621 : /* process for the start of a new epoch */
622 : static void
623 : fd_runtime_process_new_epoch( fd_banks_t * banks,
624 : fd_bank_t * bank,
625 : fd_accdb_user_t * accdb,
626 : fd_funk_txn_xid_t const * xid,
627 : fd_capture_ctx_t * capture_ctx,
628 : ulong parent_epoch,
629 9 : fd_runtime_stack_t * runtime_stack ) {
630 9 : long start = fd_log_wallclock();
631 :
632 9 : fd_compute_and_apply_new_feature_activations( bank, accdb, xid, runtime_stack, capture_ctx );
633 :
634 : /* Update the cached warmup/cooldown rate epoch now that features may
635 : have changed (reduce_stake_warmup_cooldown may have just activated). */
636 9 : bank->f.warmup_cooldown_rate_epoch = fd_slot_to_epoch( &bank->f.epoch_schedule,
637 9 : bank->f.features.reduce_stake_warmup_cooldown,
638 9 : NULL );
639 :
640 : /* Updates stake history sysvar accumulated values and recomputes
641 : stake delegations for vote accounts. */
642 :
643 9 : fd_stake_delegations_t const * stake_delegations = fd_bank_stake_delegations_frontier_query( banks, bank );
644 9 : if( FD_UNLIKELY( !stake_delegations ) ) {
645 0 : FD_LOG_CRIT(( "stake_delegations is NULL" ));
646 0 : }
647 :
648 9 : fd_stakes_activate_epoch( bank, runtime_stack, accdb, xid, capture_ctx, stake_delegations,
649 9 : &bank->f.warmup_cooldown_rate_epoch );
650 :
651 : /* Distribute rewards. This involves calculating the rewards for
652 : every vote and stake account. */
653 :
654 9 : fd_hash_t const * parent_blockhash = fd_blockhashes_peek_last_hash( &bank->f.block_hash_queue );
655 9 : fd_begin_partitioned_rewards( bank,
656 9 : accdb,
657 9 : xid,
658 9 : runtime_stack,
659 9 : capture_ctx,
660 9 : stake_delegations,
661 9 : parent_blockhash,
662 9 : parent_epoch );
663 :
664 9 : fd_bank_stake_delegations_end_frontier_query( banks, bank );
665 :
666 : /* The Agave client handles updating their stakes cache with a call to
667 : update_epoch_stakes() which keys stakes by the leader schedule
668 : epochs and retains up to 6 epochs of stakes. However, to correctly
669 : calculate the leader schedule, we just need to maintain the vote
670 : states for the current epoch, the previous epoch, and the one
671 : before that.
672 : https://github.com/anza-xyz/agave/blob/v3.0.4/runtime/src/bank.rs#L2175
673 : */
674 :
675 : /* Now that our stakes caches have been updated, we can calculate the
676 : leader schedule for the upcoming epoch epoch using our new
677 : vote_states_prev_prev (stakes for T-2). */
678 :
679 9 : fd_runtime_update_leaders( bank, runtime_stack );
680 :
681 9 : long end = fd_log_wallclock();
682 9 : FD_LOG_NOTICE(( "starting epoch %lu at slot %lu took %.6f seconds", bank->f.epoch, bank->f.slot, (double)(end - start) / 1e9 ));
683 9 : }
684 :
685 : static void
686 : fd_runtime_block_pre_execute_process_new_epoch( fd_banks_t * banks,
687 : fd_bank_t * bank,
688 : fd_accdb_user_t * accdb,
689 : fd_funk_txn_xid_t const * xid,
690 : fd_capture_ctx_t * capture_ctx,
691 : fd_runtime_stack_t * runtime_stack,
692 108 : int * is_epoch_boundary ) {
693 :
694 108 : ulong const slot = bank->f.slot;
695 108 : if( FD_LIKELY( slot != 0UL ) ) {
696 108 : fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
697 :
698 108 : ulong prev_epoch = fd_slot_to_epoch( epoch_schedule, bank->f.parent_slot, NULL );
699 108 : ulong slot_idx;
700 108 : ulong new_epoch = fd_slot_to_epoch( epoch_schedule, slot, &slot_idx );
701 108 : if( FD_UNLIKELY( slot_idx==1UL && new_epoch==0UL ) ) {
702 : /* The block after genesis has a height of 1. */
703 0 : bank->f.block_height = 1UL;
704 0 : }
705 :
706 108 : if( FD_UNLIKELY( prev_epoch<new_epoch || !slot_idx ) ) {
707 9 : FD_LOG_DEBUG(( "Epoch boundary starting" ));
708 9 : fd_runtime_process_new_epoch( banks, bank, accdb, xid, capture_ctx, prev_epoch, runtime_stack );
709 9 : *is_epoch_boundary = 1;
710 99 : } else {
711 99 : *is_epoch_boundary = 0;
712 99 : }
713 :
714 108 : fd_distribute_partitioned_epoch_rewards( bank, accdb, xid, capture_ctx );
715 108 : } else {
716 0 : *is_epoch_boundary = 0;
717 0 : }
718 108 : }
719 :
720 :
721 : static void
722 : fd_runtime_block_sysvar_update_pre_execute( fd_bank_t * bank,
723 : fd_accdb_user_t * accdb,
724 : fd_funk_txn_xid_t const * xid,
725 : fd_runtime_stack_t * runtime_stack,
726 108 : fd_capture_ctx_t * capture_ctx ) {
727 : // let (fee_rate_governor, fee_components_time_us) = measure_us!(
728 : // FeeRateGovernor::new_derived(&parent.fee_rate_governor, parent.signature_count())
729 : // );
730 : /* https://github.com/firedancer-io/solana/blob/dab3da8e7b667d7527565bddbdbecf7ec1fb868e/runtime/src/bank.rs#L1312-L1314 */
731 :
732 108 : fd_runtime_new_fee_rate_governor_derived( bank, bank->f.parent_signature_cnt );
733 :
734 108 : fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
735 108 : ulong parent_epoch = fd_slot_to_epoch( epoch_schedule, bank->f.parent_slot, NULL );
736 108 : fd_sysvar_clock_update( bank, accdb, xid, capture_ctx, runtime_stack, &parent_epoch );
737 :
738 : // It has to go into the current txn previous info but is not in slot 0
739 108 : if( bank->f.slot != 0 ) {
740 108 : fd_sysvar_slot_hashes_update( bank, accdb, xid, capture_ctx );
741 108 : }
742 108 : fd_sysvar_last_restart_slot_update( bank, accdb, xid, capture_ctx, bank->f.last_restart_slot.slot );
743 108 : }
744 :
745 : int
746 : fd_runtime_load_txn_address_lookup_tables( fd_txn_in_t const * txn_in,
747 : fd_txn_t const * txn,
748 : uchar const * payload,
749 : fd_accdb_user_t * accdb,
750 : fd_funk_txn_xid_t const * xid,
751 : ulong slot,
752 : fd_slot_hash_t const * hashes, /* deque */
753 81 : fd_acct_addr_t * out_accts_alt ) {
754 :
755 81 : if( FD_LIKELY( txn->transaction_version!=FD_TXN_V0 ) ) return FD_RUNTIME_EXECUTE_SUCCESS;
756 :
757 81 : fd_alut_interp_t interp[1];
758 81 : fd_alut_interp_new(
759 81 : interp,
760 81 : out_accts_alt,
761 81 : txn,
762 81 : payload,
763 81 : hashes,
764 81 : slot );
765 :
766 81 : fd_txn_acct_addr_lut_t const * addr_luts = fd_txn_get_address_tables_const( txn );
767 84 : for( ulong i=0UL; i<txn->addr_table_lookup_cnt; i++ ) {
768 3 : fd_txn_acct_addr_lut_t const * addr_lut = &addr_luts[i];
769 3 : fd_pubkey_t addr_lut_acc = FD_LOAD( fd_pubkey_t, payload+addr_lut->addr_off );
770 :
771 : /* https://github.com/anza-xyz/agave/blob/368ea563c423b0a85cc317891187e15c9a321521/accounts-db/src/accounts.rs#L90-L94 */
772 3 : fd_accdb_ro_t alut_ro[1];
773 :
774 3 : int is_found = 0;
775 3 : if( FD_UNLIKELY( txn_in && txn_in->bundle.is_bundle ) ) {
776 6 : for( ulong j=txn_in->bundle.prev_txn_cnt; j>0UL && !is_found; j-- ) {
777 3 : fd_txn_out_t * prev_txn_out = txn_in->bundle.prev_txn_outs[ j-1 ];
778 6 : for( ushort k=0; k<prev_txn_out->accounts.cnt; k++ ) {
779 6 : if( fd_pubkey_eq( &prev_txn_out->accounts.keys[ k ], &addr_lut_acc ) && prev_txn_out->accounts.is_writable[ k ] ) {
780 3 : fd_accdb_ro_init_nodb( alut_ro, &addr_lut_acc, prev_txn_out->accounts.account[ k ].meta );
781 3 : if( FD_UNLIKELY( !alut_ro->meta->lamports ) ) {
782 0 : fd_alut_interp_delete( interp );
783 0 : return FD_RUNTIME_TXN_ERR_ADDRESS_LOOKUP_TABLE_NOT_FOUND;
784 0 : }
785 3 : is_found = 1;
786 3 : break;
787 3 : }
788 6 : }
789 3 : }
790 3 : }
791 :
792 3 : if( FD_UNLIKELY( !is_found && !fd_accdb_open_ro( accdb, alut_ro, xid, &addr_lut_acc ) ) ) {
793 0 : fd_alut_interp_delete( interp );
794 0 : return FD_RUNTIME_TXN_ERR_ADDRESS_LOOKUP_TABLE_NOT_FOUND;
795 0 : }
796 :
797 3 : int err = fd_alut_interp_next(
798 3 : interp,
799 3 : &addr_lut_acc,
800 3 : fd_accdb_ref_owner ( alut_ro ),
801 3 : fd_accdb_ref_data_const( alut_ro ),
802 3 : fd_accdb_ref_data_sz ( alut_ro ) );
803 3 : fd_accdb_close_ro( accdb, alut_ro );
804 3 : if( FD_UNLIKELY( err ) ) {
805 0 : fd_alut_interp_delete( interp );
806 0 : return err;
807 0 : }
808 3 : }
809 :
810 81 : fd_alut_interp_delete( interp );
811 :
812 81 : return FD_RUNTIME_EXECUTE_SUCCESS;
813 81 : }
814 :
815 : /* Pre-populate the bank's in-memory feature set with upcoming feature
816 : activations. If the current slot is the last slot before an epoch
817 : boundary, scan all known feature accounts. Otherwise, returns early.
818 :
819 : For any feature that is pending (not yet activated on-chain) but has
820 : an account owned by the feature program, set the in-memory activation
821 : slot within the bank's featureset to the first slot of the next
822 : epoch. This is needed so that deployment verification (which uses
823 : slot+1) can detect features that will activate at the next epoch
824 : boundary.
825 :
826 : In Agave, program deployments use the feature set from the next
827 : slot via DELAY_VISIBILITY_SLOT_OFFSET. The runtime environments
828 : for deployment are selected based on epoch_of(slot+1):
829 : https://github.com/anza-xyz/agave/blob/v3.1.8/runtime/src/bank.rs#L3280-L3295
830 : https://github.com/anza-xyz/agave/blob/v3.1.8/svm/src/transaction_processor.rs#L339-L345
831 :
832 : This function does NOT write to feature accounts or update the
833 : lthash. It only modifies the bank's in-memory feature set. */
834 : static void
835 : fd_features_prepopulate_upcoming( fd_bank_t * bank,
836 : fd_accdb_user_t * accdb,
837 108 : fd_funk_txn_xid_t const * xid ) {
838 108 : ulong slot = bank->f.slot;
839 108 : fd_epoch_schedule_t const * epoch_schedule = &bank->f.epoch_schedule;
840 108 : ulong curr_epoch = fd_slot_to_epoch( epoch_schedule, slot, NULL );
841 108 : ulong next_epoch = fd_slot_to_epoch( epoch_schedule, slot+1UL, NULL );
842 108 : if( FD_LIKELY( curr_epoch==next_epoch ) ) return;
843 :
844 9 : fd_features_restore( bank, accdb, xid );
845 9 : }
846 :
847 : void
848 : fd_runtime_block_execute_prepare( fd_banks_t * banks,
849 : fd_bank_t * bank,
850 : fd_accdb_user_t * accdb,
851 : fd_runtime_stack_t * runtime_stack,
852 : fd_capture_ctx_t * capture_ctx,
853 108 : int * is_epoch_boundary ) {
854 :
855 108 : fd_funk_txn_xid_t const xid = { .ul = { bank->f.slot, bank->idx } };
856 :
857 108 : fd_runtime_block_pre_execute_process_new_epoch( banks, bank, accdb, &xid, capture_ctx, runtime_stack, is_epoch_boundary );
858 :
859 108 : if( FD_LIKELY( bank->f.slot ) ) {
860 108 : fd_cost_tracker_t * cost_tracker = fd_bank_cost_tracker_modify( bank );
861 108 : FD_TEST( cost_tracker );
862 108 : fd_cost_tracker_init( cost_tracker, &bank->f.features, bank->f.slot );
863 108 : }
864 :
865 108 : fd_features_prepopulate_upcoming( bank, accdb, &xid );
866 :
867 108 : fd_runtime_block_sysvar_update_pre_execute( bank, accdb, &xid, runtime_stack, capture_ctx );
868 :
869 108 : if( FD_UNLIKELY( !fd_sysvar_cache_restore( bank, accdb, &xid ) ) ) {
870 0 : FD_LOG_ERR(( "Failed to restore sysvar cache" ));
871 0 : }
872 108 : }
873 :
874 : static void
875 : fd_runtime_update_bank_hash( fd_bank_t * bank,
876 0 : fd_capture_ctx_t * capture_ctx ) {
877 : /* Compute the new bank hash */
878 0 : fd_lthash_value_t const * lthash = fd_bank_lthash_locking_query( bank );
879 0 : fd_hash_t new_bank_hash[1] = { 0 };
880 0 : fd_hashes_hash_bank(
881 0 : lthash,
882 0 : &bank->f.prev_bank_hash,
883 0 : (fd_hash_t *)bank->f.poh.hash,
884 0 : bank->f.signature_count,
885 0 : new_bank_hash );
886 :
887 : /* Update the bank hash */
888 0 : bank->f.bank_hash = *new_bank_hash;
889 :
890 0 : if( capture_ctx && capture_ctx->capture_solcap &&
891 0 : bank->f.slot>=capture_ctx->solcap_start_slot ) {
892 :
893 0 : uchar lthash_hash[FD_HASH_FOOTPRINT];
894 0 : fd_blake3_hash(lthash->bytes, FD_LTHASH_LEN_BYTES, lthash_hash );
895 0 : fd_capture_link_write_bank_preimage(
896 0 : capture_ctx,
897 0 : bank->f.slot,
898 0 : (fd_hash_t *)new_bank_hash->hash,
899 0 : (fd_hash_t *)&bank->f.prev_bank_hash,
900 0 : (fd_hash_t *)lthash_hash,
901 0 : (fd_hash_t *)bank->f.poh.hash,
902 0 : bank->f.signature_count );
903 0 : }
904 :
905 0 : fd_bank_lthash_end_locking_query( bank );
906 0 : }
907 :
908 : /******************************************************************************/
909 : /* Transaction Level Execution Management */
910 : /******************************************************************************/
911 :
912 : /* fd_runtime_pre_execute_check is responsible for conducting many of
913 : the transaction sanitization checks. This is a combination of some
914 : of the work done in Agave's load_and_execute_transactions(), and some
915 : of the work done in Agave's transaction ingestion stage, before the
916 : transaction even hits the scheduler. We do some of the checks also
917 : in our transaction ingestion stage. For example, the duplicate
918 : account check is performed in both the leader and the replay
919 : scheduler. As a result, the duplicate account check below is
920 : essentially redundant, except that our fuzzing harness expects a
921 : single entry point to cover all of these checks. So we keep all of
922 : the checks below for fuzzing purposes. We could in theory hoist some
923 : of the pre-scheduler checks into a public function that is only
924 : invoked by the fuzzer to avoid duplication in the leader and the
925 : replay pipeline. But all the duplicate checks are pretty cheap, and
926 : the order and placement of the checks are also in motion on Agave's
927 : side, and performing all the checks faithfully would require access
928 : to the bank in the scheduler which is kind of gross. So that's all
929 : probably more hassle than worth. */
930 :
931 : static inline int
932 : fd_runtime_pre_execute_check( fd_runtime_t * runtime,
933 : fd_bank_t * bank,
934 : fd_txn_in_t const * txn_in,
935 156 : fd_txn_out_t * txn_out ) {
936 :
937 : /* https://github.com/anza-xyz/agave/blob/16de8b75ebcd57022409b422de557dd37b1de8db/sdk/src/transaction/sanitized.rs#L263-L275
938 : TODO: Agave's precompile verification is done at the slot level, before batching and executing transactions. This logic should probably
939 : be moved in the future. The Agave call heirarchy looks something like this:
940 : process_single_slot
941 : v
942 : confirm_full_slot
943 : v
944 : confirm_slot_entries --------------------------------------------------->
945 : v v v
946 : verify_transaction ComputeBudget::process_instruction process_entries
947 : v v
948 : verify_precompiles process_batches
949 : v
950 : ...
951 : v
952 : load_and_execute_transactions
953 : v
954 : ...
955 : v
956 : load_accounts --> load_transaction_accounts
957 : v
958 : general transaction execution
959 :
960 : */
961 :
962 : /* Verify the transaction. For now, this step only involves processing
963 : the compute budget instructions. */
964 156 : int err = fd_executor_verify_transaction( bank, txn_in, txn_out );
965 156 : if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
966 3 : txn_out->err.is_committable = 0;
967 3 : return err;
968 3 : }
969 :
970 : /* Resolve and verify ALUT-referenced account keys, if applicable */
971 153 : err = fd_executor_setup_txn_alut_account_keys( runtime, bank, txn_in, txn_out );
972 153 : if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
973 0 : txn_out->err.is_committable = 0;
974 0 : return err;
975 0 : }
976 :
977 : /* Set up the transaction accounts and other txn ctx metadata */
978 153 : fd_executor_setup_accounts_for_txn( runtime, bank, txn_in, txn_out );
979 :
980 : /* Post-sanitization checks. Called from prepare_sanitized_batch()
981 : which, for now, only is used to lock the accounts and perform a
982 : couple basic validations.
983 : https://github.com/anza-xyz/agave/blob/838c1952595809a31520ff1603a13f2c9123aa51/accounts-db/src/account_locks.rs#L118 */
984 153 : err = fd_executor_validate_account_locks( bank, txn_out );
985 153 : if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
986 0 : txn_out->err.is_committable = 0;
987 0 : return err;
988 0 : }
989 :
990 : /* load_and_execute_transactions() -> check_transactions()
991 : https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/runtime/src/bank.rs#L3667-L3672 */
992 153 : err = fd_executor_check_transactions( runtime, bank, txn_in, txn_out );
993 153 : if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
994 0 : txn_out->err.is_committable = 0;
995 0 : return err;
996 0 : }
997 :
998 : /* load_and_execute_sanitized_transactions() -> validate_fees() ->
999 : validate_transaction_fee_payer()
1000 : https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/svm/src/transaction_processor.rs#L236-L249 */
1001 153 : err = fd_executor_validate_transaction_fee_payer( runtime, bank, txn_in, txn_out );
1002 153 : if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
1003 12 : txn_out->err.is_committable = 0;
1004 12 : return err;
1005 12 : }
1006 :
1007 141 : txn_out->details.exec_start_timestamp = fd_tickcount();
1008 :
1009 : /* https://github.com/anza-xyz/agave/blob/ced98f1ebe73f7e9691308afa757323003ff744f/svm/src/transaction_processor.rs#L284-L296 */
1010 141 : err = fd_executor_load_transaction_accounts( runtime, bank, txn_in, txn_out );
1011 141 : if( FD_UNLIKELY( err!=FD_RUNTIME_EXECUTE_SUCCESS ) ) {
1012 : /* Regardless of whether transaction accounts were loaded successfully, the transaction is
1013 : included in the block and transaction fees are collected.
1014 : https://github.com/anza-xyz/agave/blob/v2.1.6/svm/src/transaction_processor.rs#L341-L357 */
1015 0 : txn_out->err.is_fees_only = 1;
1016 :
1017 : /* If the transaction fails to load, the "rollback" accounts will include one of the following:
1018 : 1. Nonce account only
1019 : 2. Fee payer only
1020 : 3. Nonce account + fee payer
1021 :
1022 : Because the cost tracker uses the loaded account data size in block cost calculations, we need to
1023 : make sure our calculated loaded accounts data size is conformant with Agave's.
1024 : https://github.com/anza-xyz/agave/blob/v2.1.14/runtime/src/bank.rs#L4116
1025 :
1026 : In any case, we should always add the dlen of the fee payer. */
1027 0 : txn_out->details.loaded_accounts_data_size = fd_accdb_ref_data_sz( txn_out->accounts.account[ FD_FEE_PAYER_TXN_IDX ].ro );
1028 :
1029 : /* Special case handling for if a nonce account is present in the transaction. */
1030 0 : if( txn_out->accounts.nonce_idx_in_txn!=ULONG_MAX ) {
1031 : /* If the nonce account is not the fee payer, then we separately add the dlen of the nonce account. Otherwise, we would
1032 : be double counting the dlen of the fee payer. */
1033 0 : if( txn_out->accounts.nonce_idx_in_txn!=FD_FEE_PAYER_TXN_IDX ) {
1034 0 : txn_out->details.loaded_accounts_data_size += txn_out->accounts.rollback_nonce->dlen;
1035 0 : }
1036 0 : }
1037 0 : }
1038 :
1039 : /*
1040 : The fee payer and the nonce account will be stored and hashed so
1041 : long as the transaction landed on chain, or, in Agave terminology,
1042 : the transaction was processed.
1043 : https://github.com/anza-xyz/agave/blob/v2.1.1/runtime/src/account_saver.rs#L72
1044 :
1045 : A transaction lands on chain in one of two ways:
1046 : (1) Passed fee validation and loaded accounts.
1047 : (2) Passed fee validation and failed to load accounts and the enable_transaction_loading_failure_fees feature is enabled as per
1048 : SIMD-0082 https://github.com/anza-xyz/feature-gate-tracker/issues/52
1049 :
1050 : So, at this point, the transaction is committable.
1051 : */
1052 :
1053 141 : return err;
1054 153 : }
1055 :
1056 : /* fd_runtime_finalize_account is a helper used to commit the data from
1057 : a writable transaction account back into the accountsdb. */
1058 :
1059 : static void
1060 : fd_runtime_finalize_account( fd_accdb_user_t * accdb,
1061 : fd_funk_txn_xid_t const * xid,
1062 : fd_pubkey_t const * pubkey,
1063 48 : fd_account_meta_t * meta ) {
1064 : /* FIXME if account doesn't change according to LtHash, don't update
1065 : database record */
1066 :
1067 48 : fd_accdb_rw_t rw[1];
1068 48 : int rw_ok = !!fd_accdb_open_rw(
1069 48 : accdb,
1070 48 : rw,
1071 48 : xid,
1072 48 : pubkey,
1073 48 : meta->dlen,
1074 48 : FD_ACCDB_FLAG_CREATE|FD_ACCDB_FLAG_TRUNCATE );
1075 48 : if( FD_UNLIKELY( !rw_ok ) ) FD_LOG_CRIT(( "fd_accdb_open_rw failed" ));
1076 :
1077 48 : void const * data = fd_account_data( meta );
1078 48 : fd_accdb_ref_lamports_set( rw, meta->lamports );
1079 48 : fd_accdb_ref_owner_set ( rw, meta->owner );
1080 48 : fd_accdb_ref_exec_bit_set( rw, meta->executable );
1081 48 : fd_accdb_ref_data_set ( accdb, rw, data, meta->dlen );
1082 48 : fd_accdb_ref_slot_set ( rw, xid->ul[0] );
1083 :
1084 48 : fd_accdb_close_rw( accdb, rw );
1085 48 : }
1086 :
1087 : /* fd_runtime_save_account persists a transaction account to the account
1088 : database and updates the bank lthash.
1089 :
1090 : This function:
1091 : - Loads the previous account revision
1092 : - Computes the LtHash of the previous revision
1093 : - Computes the LtHash of the new revision
1094 : - Removes/adds the previous/new revision's LtHash
1095 : - Saves the new version of the account to funk
1096 : - Sends updates to metrics and capture infra
1097 :
1098 : Returns FD_RUNTIME_SAVE_* */
1099 :
1100 : static int
1101 : fd_runtime_save_account( fd_accdb_user_t * accdb,
1102 : fd_funk_txn_xid_t const * xid,
1103 : fd_pubkey_t const * pubkey,
1104 : fd_account_meta_t * meta,
1105 : fd_bank_t * bank,
1106 54 : fd_capture_ctx_t * capture_ctx ) {
1107 54 : fd_lthash_value_t lthash_post[1];
1108 54 : fd_lthash_value_t lthash_prev[1];
1109 :
1110 : /* Update LtHash
1111 : - Query old version of account and hash it
1112 : - Hash new version of account */
1113 54 : fd_accdb_ro_t ro[1];
1114 54 : int old_exist = 0;
1115 54 : if( fd_accdb_open_ro( accdb, ro, xid, pubkey ) ) {
1116 48 : old_exist = fd_accdb_ref_lamports( ro )!=0UL;
1117 48 : fd_hashes_account_lthash(
1118 48 : pubkey,
1119 48 : ro->meta,
1120 48 : fd_accdb_ref_data_const( ro ),
1121 48 : lthash_prev );
1122 48 : fd_accdb_close_ro( accdb, ro );
1123 48 : } else {
1124 6 : old_exist = 0;
1125 6 : fd_lthash_zero( lthash_prev );
1126 6 : }
1127 54 : int new_exist = meta->lamports!=0UL;
1128 :
1129 54 : if( FD_LIKELY( old_exist || new_exist ) ) {
1130 48 : fd_hashes_update_lthash1( lthash_post, lthash_prev, pubkey, meta, bank, capture_ctx );
1131 48 : }
1132 :
1133 : /* The first 32 bytes of an LtHash with a single input element are
1134 : equal to the BLAKE3_256 hash of an account. Therefore, comparing
1135 : the first 32 bytes is a cryptographically secure equality check
1136 : for an account. */
1137 54 : int changed = 0!=memcmp( lthash_post->bytes, lthash_prev->bytes, 32UL );
1138 :
1139 54 : if( changed ) {
1140 48 : fd_runtime_finalize_account( accdb, xid, pubkey, meta );
1141 48 : }
1142 :
1143 54 : int save_type = (old_exist<<1) | (new_exist);
1144 54 : if( save_type==FD_RUNTIME_SAVE_MODIFY && !changed ) {
1145 6 : save_type = FD_RUNTIME_SAVE_UNCHANGED;
1146 6 : }
1147 54 : return save_type;
1148 54 : }
1149 :
1150 : /* fd_runtime_commit_txn is a helper used by the non-tpool transaction
1151 : executor to finalize borrowed account changes back into funk. It also
1152 : handles txncache insertion and updates to the vote/stake cache.
1153 : TODO: This function should probably be moved to fd_executor.c. */
1154 :
1155 : void
1156 : fd_runtime_commit_txn( fd_runtime_t * runtime,
1157 : fd_bank_t * bank,
1158 30 : fd_txn_out_t * txn_out ) {
1159 :
1160 30 : if( FD_UNLIKELY( !txn_out->err.is_committable ) ) {
1161 0 : FD_LOG_CRIT(( "fd_runtime_commit_txn: transaction is not committable" ));
1162 0 : }
1163 :
1164 30 : txn_out->details.commit_start_timestamp = fd_tickcount();
1165 :
1166 : /* Release executable accounts */
1167 :
1168 30 : for( ulong i=0UL; i<runtime->accounts.executable_cnt; i++ ) {
1169 0 : fd_accdb_close_ro( runtime->accdb, &runtime->accounts.executable[i] );
1170 0 : }
1171 30 : runtime->accounts.executable_cnt = 0UL;
1172 :
1173 : /* Release read-only accounts */
1174 :
1175 90 : for( ulong i=0UL; i<txn_out->accounts.cnt; i++ ) {
1176 60 : if( !txn_out->accounts.is_writable[i] ) {
1177 6 : fd_accdb_close_ro( runtime->accdb, txn_out->accounts.account[i].ro );
1178 6 : }
1179 60 : }
1180 :
1181 30 : fd_funk_txn_xid_t xid = { .ul = { bank->f.slot, bank->idx } };
1182 :
1183 30 : if( FD_UNLIKELY( txn_out->err.txn_err ) ) {
1184 :
1185 : /* Save the fee_payer. Everything but the fee balance should be reset.
1186 : TODO: an optimization here could be to use a dirty flag in the
1187 : borrowed account. If the borrowed account data has been changed in
1188 : any way, then the full account can be rolled back as it is done now.
1189 : However, most of the time the account data is not changed, and only
1190 : the lamport balance has to change. */
1191 :
1192 : /* With nonce account rollbacks, there are three cases:
1193 : 1. No nonce account in the transaction
1194 : 2. Nonce account is the fee payer
1195 : 3. Nonce account is not the fee payer
1196 :
1197 : We should always rollback the nonce account first. Note that the nonce account may be the fee payer (case 2). */
1198 0 : if( txn_out->accounts.nonce_idx_in_txn!=ULONG_MAX ) {
1199 0 : int save_type =
1200 0 : fd_runtime_save_account(
1201 0 : runtime->accdb,
1202 0 : &xid,
1203 0 : &txn_out->accounts.keys[txn_out->accounts.nonce_idx_in_txn],
1204 0 : txn_out->accounts.rollback_nonce,
1205 0 : bank,
1206 0 : runtime->log.capture_ctx );
1207 0 : runtime->metrics.txn_account_save[ save_type ]++;
1208 0 : }
1209 : /* Now, we must only save the fee payer if the nonce account was not the fee payer (because that was already saved above) */
1210 0 : if( FD_LIKELY( txn_out->accounts.nonce_idx_in_txn!=FD_FEE_PAYER_TXN_IDX ) ) {
1211 0 : int save_type =
1212 0 : fd_runtime_save_account(
1213 0 : runtime->accdb,
1214 0 : &xid,
1215 0 : &txn_out->accounts.keys[FD_FEE_PAYER_TXN_IDX],
1216 0 : txn_out->accounts.rollback_fee_payer,
1217 0 : bank,
1218 0 : runtime->log.capture_ctx );
1219 0 : runtime->metrics.txn_account_save[ save_type ]++;
1220 0 : }
1221 30 : } else {
1222 :
1223 :
1224 30 : fd_top_votes_t * top_votes = fd_bank_top_votes_t_2_modify( bank );
1225 90 : for( ushort i=0; i<txn_out->accounts.cnt; i++ ) {
1226 : /* We are only interested in saving writable accounts and the fee
1227 : payer account. */
1228 60 : if( !txn_out->accounts.is_writable[i] ) {
1229 6 : continue;
1230 6 : }
1231 :
1232 54 : fd_pubkey_t const * pubkey = &txn_out->accounts.keys[i];
1233 54 : fd_accdb_rw_t * account = &txn_out->accounts.account[i];
1234 :
1235 : /* Tips for bundles are collected in the bank: a user submitting a
1236 : bundle must include a instruction that transfers lamports to
1237 : a specific tip account. Tips accumulated through the slot. */
1238 54 : if( fd_pack_tip_is_tip_account( fd_type_pun_const( pubkey->uc ) ) ) {
1239 0 : txn_out->details.tips += fd_ulong_sat_sub( fd_accdb_ref_lamports( account->ro ), runtime->accounts.starting_lamports[i] );
1240 0 : }
1241 :
1242 54 : if( txn_out->accounts.stake_update[i] ) {
1243 0 : fd_stakes_update_stake_delegation( pubkey, account->meta, bank );
1244 0 : }
1245 :
1246 54 : if( txn_out->accounts.vote_update[i] ) {
1247 0 : if( FD_UNLIKELY( fd_accdb_ref_lamports( account->ro )==0UL || !fd_vsv_is_correct_size_and_initialized( account->meta ) ) ) {
1248 0 : fd_top_votes_invalidate( top_votes, pubkey );
1249 0 : } else {
1250 0 : fd_vote_block_timestamp_t last_vote = fd_vsv_get_vote_block_timestamp( fd_account_data( account->meta ), account->meta->dlen );
1251 0 : fd_top_votes_update( top_votes, pubkey, last_vote.slot, last_vote.timestamp );
1252 0 : }
1253 0 : }
1254 :
1255 54 : int save_type = fd_runtime_save_account( runtime->accdb, &xid, pubkey, account->meta, bank, runtime->log.capture_ctx );
1256 54 : runtime->metrics.txn_account_save[ save_type ]++;
1257 54 : }
1258 :
1259 : /* Atomically add all accumulated tips to the bank once after processing all accounts */
1260 30 : if( txn_out->details.tips>0UL )
1261 0 : FD_ATOMIC_FETCH_AND_ADD( &bank->f.tips, txn_out->details.tips );
1262 30 : }
1263 :
1264 : /* Accumulate block-level information to the bank. */
1265 :
1266 30 : FD_ATOMIC_FETCH_AND_ADD( &bank->f.txn_count, 1UL );
1267 30 : FD_ATOMIC_FETCH_AND_ADD( &bank->f.execution_fees, txn_out->details.execution_fee );
1268 30 : FD_ATOMIC_FETCH_AND_ADD( &bank->f.priority_fees, txn_out->details.priority_fee );
1269 30 : FD_ATOMIC_FETCH_AND_ADD( &bank->f.signature_count, txn_out->details.signature_count );
1270 :
1271 30 : if( !txn_out->details.is_simple_vote ) {
1272 30 : FD_ATOMIC_FETCH_AND_ADD( &bank->f.nonvote_txn_count, 1 );
1273 30 : if( FD_UNLIKELY( txn_out->err.exec_err ) ) {
1274 0 : FD_ATOMIC_FETCH_AND_ADD( &bank->f.nonvote_failed_txn_count, 1 );
1275 0 : }
1276 30 : }
1277 :
1278 30 : if( FD_UNLIKELY( txn_out->err.exec_err ) ) {
1279 0 : FD_ATOMIC_FETCH_AND_ADD( &bank->f.failed_txn_count, 1 );
1280 0 : }
1281 :
1282 30 : FD_ATOMIC_FETCH_AND_ADD( &bank->f.total_compute_units_used, txn_out->details.compute_budget.compute_unit_limit - txn_out->details.compute_budget.compute_meter );
1283 :
1284 : /* Update the cost tracker. */
1285 :
1286 30 : fd_cost_tracker_t * cost_tracker = fd_bank_cost_tracker_modify( bank );
1287 30 : int res = fd_cost_tracker_try_add_cost( cost_tracker, txn_out );
1288 30 : if( FD_UNLIKELY( res!=FD_COST_TRACKER_SUCCESS ) ) {
1289 0 : FD_LOG_DEBUG(( "fd_runtime_commit_txn: transaction failed to fit into block %d", res ));
1290 0 : txn_out->err.is_committable = 0;
1291 0 : txn_out->err.txn_err = fd_cost_tracker_err_to_runtime_err( res );
1292 0 : }
1293 :
1294 : /* Finally, update the status cache. */
1295 :
1296 30 : if( FD_LIKELY( runtime->status_cache && txn_out->accounts.nonce_idx_in_txn==ULONG_MAX ) ) {
1297 : /* In Agave, durable nonce transactions are inserted to the status
1298 : cache the same as any others, but this is only to serve RPC
1299 : requests, they do not need to be in there for correctness as the
1300 : nonce mechanism itself prevents double spend. We skip this logic
1301 : entirely to simplify and improve performance of the txn cache. */
1302 :
1303 0 : fd_txncache_insert( runtime->status_cache, bank->txncache_fork_id, txn_out->details.blockhash.uc, txn_out->details.blake_txn_msg_hash.uc );
1304 0 : }
1305 :
1306 90 : for( ushort i=0; i<txn_out->accounts.cnt; i++ ) {
1307 60 : if( txn_out->accounts.is_writable[i] ) {
1308 54 : fd_acc_pool_release( runtime->acc_pool, fd_type_pun( txn_out->accounts.account[i].meta ) );
1309 54 : }
1310 60 : }
1311 :
1312 30 : fd_acc_pool_release( runtime->acc_pool, txn_out->accounts.rollback_nonce_mem );
1313 30 : fd_acc_pool_release( runtime->acc_pool, txn_out->accounts.rollback_fee_payer_mem );
1314 30 : }
1315 :
1316 : void
1317 : fd_runtime_cancel_txn( fd_runtime_t * runtime,
1318 114 : fd_txn_out_t * txn_out ) {
1319 :
1320 114 : if( FD_UNLIKELY( txn_out->err.is_committable ) ) {
1321 0 : FD_LOG_CRIT(( "fd_runtime_cancel_txn: transaction is committable" ));
1322 0 : }
1323 :
1324 114 : if( !txn_out->accounts.is_setup ) {
1325 0 : return;
1326 0 : }
1327 :
1328 117 : for( ulong i=0UL; i<runtime->accounts.executable_cnt; i++ ) {
1329 3 : fd_accdb_close_ro( runtime->accdb, &runtime->accounts.executable[i] );
1330 3 : }
1331 114 : runtime->accounts.executable_cnt = 0UL;
1332 :
1333 486 : for( ushort i=0; i<txn_out->accounts.cnt; i++ ) {
1334 372 : if( txn_out->accounts.is_writable[i] ) {
1335 234 : fd_acc_pool_release( runtime->acc_pool, fd_type_pun( txn_out->accounts.account[i].meta ) );
1336 234 : } else {
1337 138 : fd_accdb_close_ro( runtime->accdb, txn_out->accounts.account[i].ro );
1338 138 : }
1339 372 : }
1340 :
1341 114 : fd_acc_pool_release( runtime->acc_pool, txn_out->accounts.rollback_nonce_mem );
1342 114 : fd_acc_pool_release( runtime->acc_pool, txn_out->accounts.rollback_fee_payer_mem );
1343 114 : }
1344 :
1345 : static inline void
1346 156 : fd_runtime_reset_runtime( fd_runtime_t * runtime ) {
1347 156 : runtime->instr.stack_sz = 0;
1348 156 : runtime->instr.trace_length = 0UL;
1349 : /* The only condition where the executable count of the current
1350 : runtime is not 0 is when a bundle of transaction is being executed.
1351 : In this case, close any outstanding executable accounts. */
1352 159 : for( ulong i=0UL; i<runtime->accounts.executable_cnt; i++ ) {
1353 3 : fd_accdb_close_ro( runtime->accdb, &runtime->accounts.executable[i] );
1354 3 : }
1355 156 : runtime->accounts.executable_cnt = 0UL;
1356 :
1357 156 : }
1358 :
1359 : static inline void
1360 : fd_runtime_new_txn_out( fd_txn_in_t const * txn_in,
1361 156 : fd_txn_out_t * txn_out ) {
1362 156 : txn_out->details.prep_start_timestamp = fd_tickcount();
1363 156 : txn_out->details.load_start_timestamp = LONG_MAX;
1364 156 : txn_out->details.exec_start_timestamp = LONG_MAX;
1365 156 : txn_out->details.commit_start_timestamp = LONG_MAX;
1366 :
1367 156 : fd_compute_budget_details_new( &txn_out->details.compute_budget );
1368 :
1369 156 : txn_out->details.loaded_accounts_data_size = 0UL;
1370 156 : txn_out->details.accounts_resize_delta = 0L;
1371 :
1372 156 : txn_out->details.return_data.len = 0UL;
1373 156 : memset( txn_out->details.return_data.program_id.key, 0, sizeof(fd_pubkey_t) );
1374 :
1375 156 : txn_out->details.tips = 0UL;
1376 156 : txn_out->details.execution_fee = 0UL;
1377 156 : txn_out->details.priority_fee = 0UL;
1378 156 : txn_out->details.signature_count = 0UL;
1379 :
1380 156 : txn_out->details.signature_count = TXN( txn_in->txn )->signature_cnt;
1381 156 : txn_out->details.is_simple_vote = fd_txn_is_simple_vote_transaction( TXN( txn_in->txn ), txn_in->txn->payload );
1382 :
1383 156 : fd_hash_t * blockhash = (fd_hash_t *)((uchar *)txn_in->txn->payload + TXN( txn_in->txn )->recent_blockhash_off);
1384 156 : memcpy( txn_out->details.blockhash.uc, blockhash->hash, sizeof(fd_hash_t) );
1385 :
1386 156 : txn_out->accounts.is_setup = 0;
1387 156 : txn_out->accounts.cnt = 0UL;
1388 156 : txn_out->accounts.rollback_nonce = NULL;
1389 156 : txn_out->accounts.rollback_fee_payer = NULL;
1390 156 : memset( txn_out->accounts.stake_update, 0, sizeof(txn_out->accounts.stake_update) );
1391 156 : memset( txn_out->accounts.vote_update, 0, sizeof(txn_out->accounts.vote_update) );
1392 :
1393 156 : txn_out->err.is_committable = 1;
1394 156 : txn_out->err.is_fees_only = 0;
1395 156 : txn_out->err.txn_err = FD_RUNTIME_EXECUTE_SUCCESS;
1396 156 : txn_out->err.exec_err = FD_EXECUTOR_INSTR_SUCCESS;
1397 156 : txn_out->err.exec_err_kind = FD_EXECUTOR_ERR_KIND_NONE;
1398 156 : txn_out->err.exec_err_idx = INT_MAX;
1399 156 : txn_out->err.custom_err = 0;
1400 156 : }
1401 :
1402 : void
1403 : fd_runtime_prepare_and_execute_txn( fd_runtime_t * runtime,
1404 : fd_bank_t * bank,
1405 : fd_txn_in_t const * txn_in,
1406 156 : fd_txn_out_t * txn_out ) {
1407 :
1408 156 : fd_runtime_reset_runtime( runtime );
1409 :
1410 156 : fd_runtime_new_txn_out( txn_in, txn_out );
1411 :
1412 : /* Set up the core account keys before any pre-execution checks.
1413 : This is needed both for execution and for protobuf context
1414 : dumping. */
1415 156 : fd_executor_setup_txn_account_keys( txn_in, txn_out );
1416 :
1417 156 : # if FD_HAS_FLATCC
1418 156 : uchar dump_txn = !!( runtime->log.dump_proto_ctx &&
1419 156 : bank->f.slot >= runtime->log.dump_proto_ctx->dump_proto_start_slot &&
1420 156 : runtime->log.dump_proto_ctx->dump_txn_to_pb );
1421 :
1422 : /* Phase 1: Capture TxnContext before execution. */
1423 156 : if( FD_UNLIKELY( dump_txn ) ) {
1424 0 : if( runtime->log.txn_dump_ctx ) {
1425 0 : fd_dump_txn_context_to_protobuf( runtime->log.txn_dump_ctx, runtime, bank, txn_in, txn_out );
1426 0 : } else {
1427 0 : fd_dump_txn_to_protobuf( runtime, bank, txn_in, txn_out );
1428 0 : }
1429 0 : }
1430 156 : # endif
1431 :
1432 : /* Transaction sanitization. If a transaction can't be commited or is
1433 : fees-only, we return early. */
1434 156 : txn_out->err.txn_err = fd_runtime_pre_execute_check( runtime, bank, txn_in, txn_out );
1435 156 : ulong cu_before = txn_out->details.compute_budget.compute_meter;
1436 :
1437 : /* Execute the transaction if eligible to do so. */
1438 156 : if( FD_LIKELY( txn_out->err.is_committable ) ) {
1439 141 : if( FD_LIKELY( !txn_out->err.is_fees_only ) ) {
1440 141 : txn_out->err.txn_err = fd_execute_txn( runtime, bank, txn_in, txn_out );
1441 141 : }
1442 141 : fd_cost_tracker_calculate_cost( bank, txn_in, txn_out );
1443 141 : }
1444 156 : ulong cu_after = txn_out->details.compute_budget.compute_meter;
1445 156 : runtime->metrics.cu_cum += fd_ulong_sat_sub( cu_before, cu_after );
1446 :
1447 156 : # if FD_HAS_FLATCC
1448 : /* Phase 2: Capture TxnResult after execution and write to disk. */
1449 156 : if( FD_UNLIKELY( dump_txn && runtime->log.txn_dump_ctx ) ) {
1450 0 : fd_dump_txn_result_to_protobuf( runtime->log.txn_dump_ctx, txn_in, txn_out, txn_out->err.txn_err );
1451 0 : fd_dump_txn_fixture_to_file( runtime->log.txn_dump_ctx, runtime->log.dump_proto_ctx, txn_in );
1452 0 : }
1453 156 : # endif
1454 156 : }
1455 :
1456 : /* fd_executor_txn_verify and fd_runtime_pre_execute_check are responisble
1457 : for the bulk of the pre-transaction execution checks in the runtime.
1458 : They aim to preserve the ordering present in the Agave client to match
1459 : parity in terms of error codes. Sigverify is kept separate from the rest
1460 : of the transaction checks for fuzzing convenience.
1461 :
1462 : For reference this is the general code path which contains all relevant
1463 : pre-transactions checks in the v2.0.x Agave client from upstream
1464 : to downstream is as follows:
1465 :
1466 : confirm_slot_entries() which calls verify_ticks() and
1467 : verify_transaction(). verify_transaction() calls verify_and_hash_message()
1468 : and verify_precompiles() which parallels fd_executor_txn_verify() and
1469 : fd_executor_verify_transaction().
1470 :
1471 : process_entries() contains a duplicate account check which is part of
1472 : agave account lock acquiring. This is checked inline in
1473 : fd_runtime_pre_execute_check().
1474 :
1475 : load_and_execute_transactions() contains the function check_transactions().
1476 : This contains check_age() and check_status_cache() which is paralleled by
1477 : fd_executor_check_transaction_age_and_compute_budget_limits() and
1478 : fd_executor_check_status_cache() respectively.
1479 :
1480 : load_and_execute_sanitized_transactions() contains validate_fees()
1481 : which is responsible for executing the compute budget instructions,
1482 : validating the fee payer and collecting the fee. This is mirrored in
1483 : firedancer with fd_executor_compute_budget_program_execute_instructions()
1484 : and fd_executor_collect_fees(). load_and_execute_sanitized_transactions()
1485 : also checks the total data size of the accounts in load_accounts() and
1486 : validates the program accounts in load_transaction_accounts(). This
1487 : is paralled by fd_executor_load_transaction_accounts(). */
1488 :
1489 :
1490 : /******************************************************************************/
1491 : /* Genesis */
1492 : /*******************************************************************************/
1493 :
1494 : static void
1495 : fd_runtime_genesis_init_program( fd_bank_t * bank,
1496 : fd_accdb_user_t * accdb,
1497 : fd_funk_txn_xid_t const * xid,
1498 0 : fd_capture_ctx_t * capture_ctx ) {
1499 :
1500 0 : fd_sysvar_clock_init( bank, accdb, xid, capture_ctx );
1501 0 : fd_sysvar_rent_init( bank, accdb, xid, capture_ctx );
1502 :
1503 0 : fd_sysvar_slot_history_init( bank, accdb, xid, capture_ctx );
1504 0 : fd_sysvar_epoch_schedule_init( bank, accdb, xid, capture_ctx );
1505 0 : fd_sysvar_recent_hashes_init( bank, accdb, xid, capture_ctx );
1506 0 : fd_sysvar_stake_history_init( bank, accdb, xid, capture_ctx );
1507 0 : fd_sysvar_last_restart_slot_init( bank, accdb, xid, capture_ctx );
1508 :
1509 0 : fd_builtin_programs_init( bank, accdb, xid, capture_ctx );
1510 0 : fd_stakes_config_init( accdb, xid );
1511 0 : }
1512 :
1513 : static void
1514 : fd_runtime_init_bank_from_genesis( fd_banks_t * banks,
1515 : fd_bank_t * bank,
1516 : fd_runtime_stack_t * runtime_stack,
1517 : fd_accdb_user_t * accdb,
1518 : fd_funk_txn_xid_t const * xid,
1519 : fd_genesis_t const * genesis,
1520 : uchar const * genesis_blob,
1521 0 : fd_hash_t const * genesis_hash ) {
1522 :
1523 0 : bank->f.parent_slot = ULONG_MAX;
1524 0 : bank->f.poh = *genesis_hash;
1525 :
1526 0 : fd_hash_t * bank_hash = &bank->f.bank_hash;
1527 0 : memset( bank_hash->hash, 0, FD_SHA256_HASH_SZ );
1528 :
1529 0 : uint128 target_tick_duration = (uint128)genesis->poh.tick_duration_secs * 1000000000UL + (uint128)genesis->poh.tick_duration_ns;
1530 :
1531 0 : fd_epoch_schedule_t * epoch_schedule = &bank->f.epoch_schedule;
1532 0 : epoch_schedule->leader_schedule_slot_offset = genesis->epoch_schedule.leader_schedule_slot_offset;
1533 0 : epoch_schedule->warmup = genesis->epoch_schedule.warmup;
1534 0 : epoch_schedule->first_normal_epoch = genesis->epoch_schedule.first_normal_epoch;
1535 0 : epoch_schedule->first_normal_slot = genesis->epoch_schedule.first_normal_slot;
1536 0 : epoch_schedule->slots_per_epoch = genesis->epoch_schedule.slots_per_epoch;
1537 :
1538 0 : fd_rent_t * rent = &bank->f.rent;
1539 0 : rent->lamports_per_uint8_year = genesis->rent.lamports_per_uint8_year;
1540 0 : rent->exemption_threshold = genesis->rent.exemption_threshold;
1541 0 : rent->burn_percent = genesis->rent.burn_percent;
1542 :
1543 0 : fd_inflation_t * inflation = &bank->f.inflation;
1544 0 : inflation->initial = genesis->inflation.initial;
1545 0 : inflation->terminal = genesis->inflation.terminal;
1546 0 : inflation->taper = genesis->inflation.taper;
1547 0 : inflation->foundation = genesis->inflation.foundation;
1548 0 : inflation->foundation_term = genesis->inflation.foundation_term;
1549 0 : inflation->unused = 0.0;
1550 :
1551 0 : bank->f.block_height = 0UL;
1552 :
1553 0 : {
1554 : /* FIXME Why is there a previous blockhash at genesis? Why is the
1555 : last_hash field an option type in Agave, if even the first
1556 : real block has a previous blockhash? */
1557 0 : fd_blockhashes_t * bhq = fd_blockhashes_init( &bank->f.block_hash_queue, 0UL );
1558 0 : fd_blockhash_info_t * info = fd_blockhashes_push_new( bhq, genesis_hash );
1559 0 : info->fee_calculator.lamports_per_signature = 0UL;
1560 0 : }
1561 :
1562 0 : fd_fee_rate_governor_t * fee_rate_governor = &bank->f.fee_rate_governor;
1563 0 : fee_rate_governor->target_lamports_per_signature = genesis->fee_rate_governor.target_lamports_per_signature;
1564 0 : fee_rate_governor->target_signatures_per_slot = genesis->fee_rate_governor.target_signatures_per_slot;
1565 0 : fee_rate_governor->min_lamports_per_signature = genesis->fee_rate_governor.min_lamports_per_signature;
1566 0 : fee_rate_governor->max_lamports_per_signature = genesis->fee_rate_governor.max_lamports_per_signature;
1567 0 : fee_rate_governor->burn_percent = genesis->fee_rate_governor.burn_percent;
1568 :
1569 0 : bank->f.max_tick_height = genesis->poh.ticks_per_slot * (bank->f.slot + 1);
1570 :
1571 0 : bank->f.hashes_per_tick = genesis->poh.hashes_per_tick;
1572 :
1573 0 : bank->f.ns_per_slot = (fd_w_u128_t) { .ud=target_tick_duration * genesis->poh.ticks_per_slot };
1574 :
1575 0 : bank->f.ticks_per_slot = genesis->poh.ticks_per_slot;
1576 :
1577 0 : bank->f.genesis_creation_time = genesis->creation_time;
1578 :
1579 0 : bank->f.slots_per_year = SECONDS_PER_YEAR * (1000000000.0 / (double)target_tick_duration) / (double)genesis->poh.ticks_per_slot;
1580 :
1581 0 : bank->f.signature_count = 0UL;
1582 :
1583 : /* Derive epoch stakes */
1584 :
1585 0 : fd_stake_delegations_t * stake_delegations = fd_banks_stake_delegations_root_query( banks );
1586 0 : if( FD_UNLIKELY( !stake_delegations ) ) {
1587 0 : FD_LOG_CRIT(( "Failed to join and new a stake delegations" ));
1588 0 : }
1589 :
1590 0 : ulong capitalization = 0UL;
1591 :
1592 0 : for( ulong i=0UL; i<genesis->account_cnt; i++ ) {
1593 0 : fd_genesis_account_t account[1];
1594 0 : fd_genesis_account( genesis, genesis_blob, account, i );
1595 :
1596 0 : capitalization = fd_ulong_sat_add( capitalization, account->meta.lamports );
1597 :
1598 0 : uchar const * acc_data = account->data;
1599 :
1600 0 : if( !memcmp( account->meta.owner, fd_solana_stake_program_id.key, sizeof(fd_pubkey_t) ) ) {
1601 : /* If an account is a stake account, then it must be added to the
1602 : stake delegations cache. We should only add stake accounts that
1603 : have a valid non-zero stake. */
1604 0 : fd_stake_state_t const * stake_state = fd_stake_state_view( acc_data, account->meta.dlen );
1605 0 : if( FD_UNLIKELY( !stake_state ) ) { FD_BASE58_ENCODE_32_BYTES( account->pubkey.uc, stake_b58 ); FD_LOG_ERR(( "invalid stake account %s", stake_b58 )); }
1606 0 : if( stake_state->stake_type!=FD_STAKE_STATE_STAKE ) continue;
1607 0 : if( !stake_state->stake.stake.delegation.stake ) continue;
1608 :
1609 0 : if( FD_UNLIKELY( stake_state->stake.stake.delegation.warmup_cooldown_rate!=0.25 &&
1610 0 : stake_state->stake.stake.delegation.warmup_cooldown_rate!=0.09 ) ) {
1611 0 : FD_BASE58_ENCODE_32_BYTES( account->pubkey.uc, stake_b58 );
1612 0 : FD_LOG_ERR(( "Invalid warmup cooldown rate %f for stake account %s", stake_state->stake.stake.delegation.warmup_cooldown_rate, stake_b58 ));
1613 0 : }
1614 :
1615 0 : fd_stake_delegations_root_update(
1616 0 : stake_delegations,
1617 0 : &account->pubkey,
1618 0 : &stake_state->stake.stake.delegation.voter_pubkey,
1619 0 : stake_state->stake.stake.delegation.stake,
1620 0 : stake_state->stake.stake.delegation.activation_epoch,
1621 0 : stake_state->stake.stake.delegation.deactivation_epoch,
1622 0 : stake_state->stake.stake.credits_observed,
1623 0 : stake_state->stake.stake.delegation.warmup_cooldown_rate );
1624 :
1625 0 : } else if( !memcmp( account->meta.owner, fd_solana_feature_program_id.key, sizeof(fd_pubkey_t) ) ) {
1626 : /* Feature Account */
1627 :
1628 : /* Scan list of feature IDs to resolve address=>feature offset */
1629 0 : fd_feature_id_t const *found = NULL;
1630 0 : for( fd_feature_id_t const * id = fd_feature_iter_init();
1631 0 : !fd_feature_iter_done( id );
1632 0 : id = fd_feature_iter_next( id ) ) {
1633 0 : if( fd_pubkey_eq( &account->pubkey, &id->id ) ) {
1634 0 : found = id;
1635 0 : break;
1636 0 : }
1637 0 : }
1638 :
1639 0 : if( found ) {
1640 : /* Load feature activation */
1641 0 : fd_feature_t feature[1];
1642 0 : if( FD_UNLIKELY( !fd_feature_decode( feature, acc_data, account->meta.dlen ) ) ) {
1643 0 : FD_BASE58_ENCODE_32_BYTES( account->pubkey.uc, addr_b58 );
1644 0 : FD_LOG_WARNING(( "genesis contains corrupt feature account %s", addr_b58 ));
1645 0 : FD_LOG_HEXDUMP_ERR(( "data", acc_data, account->meta.dlen ));
1646 0 : }
1647 0 : fd_features_t * features = &bank->f.features;
1648 0 : if( feature->is_active ) {
1649 0 : FD_BASE58_ENCODE_32_BYTES( account->pubkey.uc, pubkey_b58 );
1650 0 : FD_LOG_DEBUG(( "feature %s activated at slot %lu (genesis)", pubkey_b58, feature->activation_slot ));
1651 0 : fd_features_set( features, found, feature->activation_slot );
1652 0 : } else {
1653 0 : FD_BASE58_ENCODE_32_BYTES( account->pubkey.uc, pubkey_b58 );
1654 0 : FD_LOG_DEBUG(( "feature %s not activated (genesis)", pubkey_b58 ));
1655 0 : fd_features_set( features, found, ULONG_MAX );
1656 0 : }
1657 0 : }
1658 0 : }
1659 0 : }
1660 :
1661 : /* fd_refresh_vote_accounts is responsible for updating the vote
1662 : states with the total amount of active delegated stake. It does
1663 : this by iterating over all active stake delegations and summing up
1664 : the amount of stake that is delegated to each vote account. */
1665 :
1666 0 : ulong new_rate_activation_epoch = 0UL;
1667 :
1668 0 : fd_stake_history_t stake_history[1];
1669 0 : fd_sysvar_stake_history_read( accdb, xid, stake_history );
1670 :
1671 0 : fd_refresh_vote_accounts(
1672 0 : bank,
1673 0 : accdb,
1674 0 : xid,
1675 0 : runtime_stack,
1676 0 : stake_delegations,
1677 0 : stake_history,
1678 0 : &new_rate_activation_epoch );
1679 :
1680 0 : fd_vote_stakes_t * vote_stakes = fd_bank_vote_stakes( bank );
1681 0 : fd_vote_stakes_genesis_fini( vote_stakes );
1682 :
1683 0 : bank->f.epoch = 0UL;
1684 :
1685 0 : bank->f.capitalization = capitalization;
1686 0 : }
1687 :
1688 : static int
1689 : fd_runtime_process_genesis_block( fd_bank_t * bank,
1690 : fd_accdb_user_t * accdb,
1691 : fd_funk_txn_xid_t const * xid,
1692 : fd_capture_ctx_t * capture_ctx,
1693 0 : fd_runtime_stack_t * runtime_stack ) {
1694 :
1695 0 : fd_hash_t * poh = &bank->f.poh;
1696 0 : ulong hashcnt_per_slot = bank->f.hashes_per_tick * bank->f.ticks_per_slot;
1697 0 : while( hashcnt_per_slot-- ) {
1698 0 : fd_sha256_hash( poh->hash, sizeof(fd_hash_t), poh->hash );
1699 0 : }
1700 :
1701 0 : bank->f.execution_fees = 0UL;
1702 :
1703 0 : bank->f.priority_fees = 0UL;
1704 :
1705 0 : bank->f.signature_count = 0UL;
1706 :
1707 0 : bank->f.txn_count = 0UL;
1708 :
1709 0 : bank->f.failed_txn_count = 0UL;
1710 :
1711 0 : bank->f.nonvote_failed_txn_count = 0UL;
1712 :
1713 0 : bank->f.total_compute_units_used = 0UL;
1714 :
1715 0 : fd_runtime_genesis_init_program( bank, accdb, xid, capture_ctx );
1716 :
1717 0 : fd_sysvar_slot_history_update( bank, accdb, xid, capture_ctx );
1718 :
1719 0 : fd_runtime_update_leaders( bank, runtime_stack );
1720 :
1721 0 : fd_runtime_freeze( bank, accdb, capture_ctx );
1722 :
1723 0 : fd_lthash_value_t const * lthash = fd_bank_lthash_locking_query( bank );
1724 :
1725 0 : fd_hash_t const * prev_bank_hash = &bank->f.bank_hash;
1726 :
1727 0 : fd_hash_t * bank_hash = &bank->f.bank_hash;
1728 0 : fd_hashes_hash_bank(
1729 0 : lthash,
1730 0 : prev_bank_hash,
1731 0 : (fd_hash_t *)bank->f.poh.hash,
1732 0 : 0UL,
1733 0 : bank_hash );
1734 :
1735 0 : fd_bank_lthash_end_locking_query( bank );
1736 :
1737 0 : return FD_RUNTIME_EXECUTE_SUCCESS;
1738 0 : }
1739 :
1740 : void
1741 : fd_runtime_read_genesis( fd_banks_t * banks,
1742 : fd_bank_t * bank,
1743 : fd_accdb_user_t * accdb,
1744 : fd_funk_txn_xid_t const * xid,
1745 : fd_capture_ctx_t * capture_ctx,
1746 : fd_hash_t const * genesis_hash,
1747 : fd_lthash_value_t const * genesis_lthash,
1748 : fd_genesis_t const * genesis,
1749 : uchar const * genesis_blob,
1750 0 : fd_runtime_stack_t * runtime_stack ) {
1751 :
1752 0 : fd_lthash_value_t * lthash = fd_bank_lthash_locking_modify( bank );
1753 0 : *lthash = *genesis_lthash;
1754 0 : fd_bank_lthash_end_locking_modify( bank );
1755 :
1756 : /* Once the accounts have been loaded from the genesis config into
1757 : the accounts db, we can initialize the bank state. This involves
1758 : setting some fields, and notably setting up the vote and stake
1759 : caches which are used for leader scheduling/rewards. */
1760 :
1761 0 : fd_runtime_init_bank_from_genesis( banks, bank, runtime_stack, accdb, xid, genesis, genesis_blob, genesis_hash );
1762 :
1763 : /* Write the native programs to the accounts db. */
1764 :
1765 0 : for( ulong i=0UL; i<genesis->builtin_cnt; i++ ) {
1766 0 : fd_genesis_builtin_t builtin[1];
1767 0 : fd_genesis_builtin( genesis, genesis_blob, builtin, i );
1768 0 : fd_write_builtin_account( bank, accdb, xid, capture_ctx, builtin->pubkey, builtin->data, builtin->dlen );
1769 0 : }
1770 :
1771 0 : fd_features_restore( bank, accdb, xid );
1772 :
1773 : /* At this point, state related to the bank and the accounts db
1774 : have been initialized and we are free to finish executing the
1775 : block. In practice, this updates some bank fields (notably the
1776 : poh and bank hash). */
1777 :
1778 0 : int err = fd_runtime_process_genesis_block( bank, accdb, xid, capture_ctx, runtime_stack );
1779 0 : if( FD_UNLIKELY( err ) ) FD_LOG_CRIT(( "genesis slot 0 execute failed with error %d", err ));
1780 0 : }
1781 :
1782 : void
1783 : fd_runtime_block_execute_finalize( fd_bank_t * bank,
1784 : fd_accdb_user_t * accdb,
1785 0 : fd_capture_ctx_t * capture_ctx ) {
1786 :
1787 : /* This slot is now "frozen" and can't be changed anymore. */
1788 0 : fd_runtime_freeze( bank, accdb, capture_ctx );
1789 :
1790 0 : fd_runtime_update_bank_hash( bank, capture_ctx );
1791 0 : }
1792 :
1793 :
1794 : /* Mirrors Agave function solana_sdk::transaction_context::find_index_of_account
1795 :
1796 : Backward scan over transaction accounts.
1797 : Returns -1 if not found.
1798 :
1799 : https://github.com/anza-xyz/agave/blob/v2.1.14/sdk/src/transaction_context.rs#L233-L238 */
1800 :
1801 : int
1802 : fd_runtime_find_index_of_account( fd_txn_out_t const * txn_out,
1803 252 : fd_pubkey_t const * pubkey ) {
1804 885 : for( ulong i=txn_out->accounts.cnt; i>0UL; i-- ) {
1805 759 : if( 0==memcmp( pubkey, &txn_out->accounts.keys[ i-1UL ], sizeof(fd_pubkey_t) ) ) {
1806 126 : return (int)(i-1UL);
1807 126 : }
1808 759 : }
1809 126 : return -1;
1810 252 : }
1811 :
1812 : fd_accdb_ref_t *
1813 : fd_runtime_get_account_at_index( fd_txn_in_t const * txn_in,
1814 : fd_txn_out_t * txn_out,
1815 : ushort idx,
1816 1575 : fd_txn_account_condition_fn_t * condition ) {
1817 1575 : if( FD_UNLIKELY( idx>=txn_out->accounts.cnt ) ) {
1818 0 : return NULL;
1819 0 : }
1820 :
1821 1575 : if( FD_LIKELY( condition != NULL ) ) {
1822 666 : if( FD_UNLIKELY( !condition( txn_in, txn_out, idx ) ) ) {
1823 18 : return NULL;
1824 18 : }
1825 666 : }
1826 :
1827 1557 : return txn_out->accounts.account[ idx ].ref;
1828 1575 : }
1829 :
1830 : fd_accdb_ref_t *
1831 : fd_runtime_get_account_with_key( fd_txn_in_t const * txn_in,
1832 : fd_txn_out_t * txn_out,
1833 : fd_pubkey_t const * pubkey,
1834 : int * index_out,
1835 0 : fd_txn_account_condition_fn_t * condition ) {
1836 0 : int index = fd_runtime_find_index_of_account( txn_out, pubkey );
1837 0 : if( FD_UNLIKELY( index<0 ) ) return NULL;
1838 :
1839 0 : *index_out = index;
1840 :
1841 0 : return fd_runtime_get_account_at_index( txn_in, txn_out, (uchar)index, condition );
1842 0 : }
1843 :
1844 : fd_accdb_ro_t *
1845 : fd_runtime_get_executable_account( fd_runtime_t * runtime,
1846 : fd_txn_in_t const * txn_in,
1847 : fd_txn_out_t * txn_out,
1848 0 : fd_pubkey_t const * pubkey ) {
1849 : /* First try to fetch the executable account from the existing
1850 : borrowed accounts. If the pubkey is in the account keys, then we
1851 : want to re-use that borrowed account since it reflects changes from
1852 : prior instructions. Referencing the read-only executable accounts
1853 : list is incorrect behavior when the program data account is written
1854 : to in a prior instruction (e.g. program upgrade + invoke within the
1855 : same txn) */
1856 :
1857 0 : fd_txn_account_condition_fn_t * condition = fd_runtime_account_check_exists;
1858 :
1859 0 : int index;
1860 0 : fd_accdb_ref_t * ref = fd_runtime_get_account_with_key(
1861 0 : txn_in, txn_out, pubkey, &index, condition );
1862 0 : if( FD_UNLIKELY( ref ) ) return fd_accdb_ref_ro( ref );
1863 :
1864 0 : for( ushort i=0; i<runtime->accounts.executable_cnt; i++ ) {
1865 0 : if( fd_pubkey_eq( pubkey, fd_accdb_ref_address( &runtime->accounts.executable[i] ) ) ) {
1866 0 : fd_accdb_ro_t * ro = &runtime->accounts.executable[i];
1867 0 : if( FD_UNLIKELY( !fd_account_meta_exists( ro->meta ) ) ) {
1868 0 : return NULL;
1869 0 : }
1870 0 : return ro;
1871 0 : }
1872 0 : }
1873 :
1874 0 : return NULL;
1875 0 : }
1876 :
1877 : int
1878 : fd_runtime_get_key_of_account_at_index( fd_txn_out_t * txn_out,
1879 : ushort idx,
1880 921 : fd_pubkey_t const * * key ) {
1881 : /* Return a MissingAccount error if idx is out of bounds.
1882 : https://github.com/anza-xyz/agave/blob/v3.1.4/transaction-context/src/lib.rs#L187 */
1883 921 : if( FD_UNLIKELY( idx>=txn_out->accounts.cnt ) ) {
1884 0 : return FD_EXECUTOR_INSTR_ERR_MISSING_ACC;
1885 0 : }
1886 :
1887 921 : *key = &txn_out->accounts.keys[ idx ];
1888 921 : return FD_EXECUTOR_INSTR_SUCCESS;
1889 921 : }
1890 :
1891 : /* https://github.com/anza-xyz/agave/blob/v2.1.1/sdk/program/src/message/versions/v0/loaded.rs#L162 */
1892 : int
1893 : fd_txn_account_is_demotion( const int idx,
1894 : const fd_txn_t * txn_descriptor,
1895 5967 : const uint bpf_upgradeable_in_txn ) {
1896 5967 : uint is_program = 0U;
1897 11967 : for( ulong j=0UL; j<txn_descriptor->instr_cnt; j++ ) {
1898 6000 : if( txn_descriptor->instr[j].program_id == idx ) {
1899 0 : is_program = 1U;
1900 0 : break;
1901 0 : }
1902 6000 : }
1903 :
1904 5967 : return (is_program && !bpf_upgradeable_in_txn);
1905 5967 : }
1906 :
1907 : uint
1908 : fd_txn_account_has_bpf_loader_upgradeable( const fd_pubkey_t * account_keys,
1909 6156 : const ulong accounts_cnt ) {
1910 19761 : for( ulong j=0; j<accounts_cnt; j++ ) {
1911 13605 : const fd_pubkey_t * acc = &account_keys[j];
1912 13605 : if ( memcmp( acc->uc, fd_solana_bpf_loader_upgradeable_program_id.key, sizeof(fd_pubkey_t) ) == 0 ) {
1913 0 : return 1U;
1914 0 : }
1915 13605 : }
1916 6156 : return 0U;
1917 6156 : }
1918 :
1919 : static inline int
1920 : fd_runtime_account_is_writable_idx_flat( const ushort idx,
1921 : const fd_pubkey_t * addr_at_idx,
1922 : const fd_txn_t * txn_descriptor,
1923 6156 : const uint bpf_upgradeable_in_txn ) {
1924 : /* https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L43 */
1925 6156 : if( !fd_txn_is_writable( txn_descriptor, idx ) ) {
1926 180 : return 0;
1927 180 : }
1928 :
1929 : /* See comments in fd_system_ids.h.
1930 : https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L44 */
1931 5976 : if( fd_pubkey_is_active_reserved_key( addr_at_idx ) ||
1932 5976 : fd_pubkey_is_pending_reserved_key( addr_at_idx ) ) {
1933 :
1934 9 : return 0;
1935 9 : }
1936 :
1937 5967 : if( fd_txn_account_is_demotion( idx, txn_descriptor, bpf_upgradeable_in_txn ) ) {
1938 0 : return 0;
1939 0 : }
1940 :
1941 5967 : return 1;
1942 5967 : }
1943 :
1944 :
1945 : /* This function aims to mimic the writable accounts check to populate the writable accounts cache, used
1946 : to determine if accounts are writable or not.
1947 :
1948 : https://github.com/anza-xyz/agave/blob/v2.1.11/sdk/program/src/message/sanitized.rs#L38-L47 */
1949 : int
1950 : fd_runtime_account_is_writable_idx( fd_txn_in_t const * txn_in,
1951 : fd_txn_out_t const * txn_out,
1952 6156 : ushort idx ) {
1953 6156 : uint bpf_upgradeable = fd_txn_account_has_bpf_loader_upgradeable( txn_out->accounts.keys, txn_out->accounts.cnt );
1954 6156 : return fd_runtime_account_is_writable_idx_flat( idx,
1955 6156 : &txn_out->accounts.keys[idx],
1956 6156 : TXN( txn_in->txn ),
1957 6156 : bpf_upgradeable );
1958 6156 : }
1959 :
1960 : /* Account pre-condition filtering functions */
1961 :
1962 : int
1963 : fd_runtime_account_check_exists( fd_txn_in_t const * txn_in,
1964 : fd_txn_out_t * txn_out,
1965 513 : ushort idx ) {
1966 513 : (void) txn_in;
1967 513 : return fd_account_meta_exists( txn_out->accounts.account[idx].meta );
1968 513 : }
1969 :
1970 : int
1971 : fd_runtime_account_check_fee_payer_writable( fd_txn_in_t const * txn_in,
1972 : fd_txn_out_t * txn_out,
1973 153 : ushort idx ) {
1974 153 : (void) txn_out;
1975 153 : return fd_txn_is_writable( TXN( txn_in->txn ), idx );
1976 153 : }
1977 :
1978 :
1979 : int
1980 282 : fd_account_meta_checked_sub_lamports( fd_account_meta_t * meta, ulong lamports ) {
1981 282 : ulong balance_post = 0UL;
1982 282 : int err = fd_ulong_checked_sub( meta->lamports,
1983 282 : lamports,
1984 282 : &balance_post );
1985 282 : if( FD_UNLIKELY( err ) ) {
1986 0 : return FD_EXECUTOR_INSTR_ERR_ARITHMETIC_OVERFLOW;
1987 0 : }
1988 :
1989 282 : meta->lamports = balance_post;
1990 282 : return FD_EXECUTOR_INSTR_SUCCESS;
1991 282 : }
|