-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
blockstore_processor.rs
4551 lines (4101 loc) · 160 KB
/
blockstore_processor.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use {
crate::{
block_error::BlockError,
blockstore::Blockstore,
blockstore_db::BlockstoreError,
blockstore_meta::SlotMeta,
entry_notifier_service::{EntryNotification, EntryNotifierSender},
leader_schedule_cache::LeaderScheduleCache,
token_balances::collect_token_balances,
use_snapshot_archives_at_startup::UseSnapshotArchivesAtStartup,
},
chrono_humanize::{Accuracy, HumanTime, Tense},
crossbeam_channel::Sender,
itertools::Itertools,
log::*,
rand::{seq::SliceRandom, thread_rng},
rayon::{prelude::*, ThreadPool},
scopeguard::defer,
solana_accounts_db::{
accounts_db::{AccountShrinkThreshold, AccountsDbConfig},
accounts_index::AccountSecondaryIndexes,
accounts_update_notifier_interface::AccountsUpdateNotifier,
epoch_accounts_hash::EpochAccountsHash,
rent_debits::RentDebits,
transaction_results::{
TransactionExecutionDetails, TransactionExecutionResult, TransactionResults,
},
},
solana_cost_model::cost_model::CostModel,
solana_entry::entry::{
self, create_ticks, Entry, EntrySlice, EntryType, EntryVerificationStatus, VerifyRecyclers,
},
solana_measure::{measure, measure::Measure},
solana_metrics::datapoint_error,
solana_program_runtime::timings::{ExecuteTimingType, ExecuteTimings, ThreadExecuteTimings},
solana_rayon_threadlimit::{get_max_thread_count, get_thread_count},
solana_runtime::{
accounts_background_service::{AbsRequestSender, SnapshotRequestKind},
bank::{Bank, TransactionBalancesSet},
bank_forks::BankForks,
bank_utils,
commitment::VOTE_THRESHOLD_SIZE,
prioritization_fee_cache::PrioritizationFeeCache,
runtime_config::RuntimeConfig,
transaction_batch::TransactionBatch,
vote_account::VoteAccountsHashMap,
vote_sender_types::ReplayVoteSender,
},
solana_sdk::{
clock::{Slot, MAX_PROCESSING_AGE},
feature_set,
genesis_config::GenesisConfig,
hash::Hash,
pubkey::Pubkey,
saturating_add_assign,
signature::{Keypair, Signature},
timing,
transaction::{
Result, SanitizedTransaction, TransactionError, TransactionVerificationMode,
VersionedTransaction,
},
},
solana_transaction_status::token_balances::TransactionTokenBalancesSet,
std::{
borrow::Cow,
collections::{HashMap, HashSet},
path::PathBuf,
result,
sync::{
atomic::{AtomicBool, Ordering::Relaxed},
Arc, Mutex, RwLock,
},
time::{Duration, Instant},
},
thiserror::Error,
};
struct TransactionBatchWithIndexes<'a, 'b> {
pub batch: TransactionBatch<'a, 'b>,
pub transaction_indexes: Vec<usize>,
}
struct ReplayEntry {
entry: EntryType,
starting_index: usize,
}
// get_max_thread_count to match number of threads in the old code.
// see: https://github.com/solana-labs/solana/pull/24853
lazy_static! {
static ref PAR_THREAD_POOL: ThreadPool = rayon::ThreadPoolBuilder::new()
.num_threads(get_max_thread_count())
.thread_name(|i| format!("solBstoreProc{i:02}"))
.build()
.unwrap();
}
fn first_err(results: &[Result<()>]) -> Result<()> {
for r in results {
if r.is_err() {
return r.clone();
}
}
Ok(())
}
// Includes transaction signature for unit-testing
fn get_first_error(
batch: &TransactionBatch,
fee_collection_results: Vec<Result<()>>,
) -> Option<(Result<()>, Signature)> {
let mut first_err = None;
for (result, transaction) in fee_collection_results
.iter()
.zip(batch.sanitized_transactions())
{
if let Err(ref err) = result {
if first_err.is_none() {
first_err = Some((result.clone(), *transaction.signature()));
}
warn!(
"Unexpected validator error: {:?}, transaction: {:?}",
err, transaction
);
datapoint_error!(
"validator_process_entry_error",
(
"error",
format!("error: {err:?}, transaction: {transaction:?}"),
String
)
);
}
}
first_err
}
fn execute_batch(
batch: &TransactionBatchWithIndexes,
bank: &Arc<Bank>,
transaction_status_sender: Option<&TransactionStatusSender>,
replay_vote_sender: Option<&ReplayVoteSender>,
timings: &mut ExecuteTimings,
log_messages_bytes_limit: Option<usize>,
prioritization_fee_cache: &PrioritizationFeeCache,
) -> Result<()> {
let TransactionBatchWithIndexes {
batch,
transaction_indexes,
} = batch;
let record_token_balances = transaction_status_sender.is_some();
let mut mint_decimals: HashMap<Pubkey, u8> = HashMap::new();
let pre_token_balances = if record_token_balances {
collect_token_balances(bank, batch, &mut mint_decimals)
} else {
vec![]
};
let (tx_results, balances) = batch.bank().load_execute_and_commit_transactions(
batch,
MAX_PROCESSING_AGE,
transaction_status_sender.is_some(),
transaction_status_sender.is_some(),
transaction_status_sender.is_some(),
transaction_status_sender.is_some(),
timings,
log_messages_bytes_limit,
);
bank_utils::find_and_send_votes(
batch.sanitized_transactions(),
&tx_results,
replay_vote_sender,
);
let TransactionResults {
fee_collection_results,
execution_results,
rent_debits,
..
} = tx_results;
let executed_transactions = execution_results
.iter()
.zip(batch.sanitized_transactions())
.filter_map(|(execution_result, tx)| execution_result.was_executed().then_some(tx))
.collect_vec();
if let Some(transaction_status_sender) = transaction_status_sender {
let transactions = batch.sanitized_transactions().to_vec();
let post_token_balances = if record_token_balances {
collect_token_balances(bank, batch, &mut mint_decimals)
} else {
vec![]
};
let token_balances =
TransactionTokenBalancesSet::new(pre_token_balances, post_token_balances);
transaction_status_sender.send_transaction_status_batch(
bank.clone(),
transactions,
execution_results,
balances,
token_balances,
rent_debits,
transaction_indexes.to_vec(),
);
}
prioritization_fee_cache.update(bank, executed_transactions.into_iter());
let first_err = get_first_error(batch, fee_collection_results);
first_err.map(|(result, _)| result).unwrap_or(Ok(()))
}
#[derive(Default)]
struct ExecuteBatchesInternalMetrics {
execution_timings_per_thread: HashMap<usize, ThreadExecuteTimings>,
total_batches_len: u64,
execute_batches_us: u64,
}
fn execute_batches_internal(
bank: &Arc<Bank>,
batches: &[TransactionBatchWithIndexes],
transaction_status_sender: Option<&TransactionStatusSender>,
replay_vote_sender: Option<&ReplayVoteSender>,
log_messages_bytes_limit: Option<usize>,
prioritization_fee_cache: &PrioritizationFeeCache,
) -> Result<ExecuteBatchesInternalMetrics> {
assert!(!batches.is_empty());
let execution_timings_per_thread: Mutex<HashMap<usize, ThreadExecuteTimings>> =
Mutex::new(HashMap::new());
let mut execute_batches_elapsed = Measure::start("execute_batches_elapsed");
let results: Vec<Result<()>> = PAR_THREAD_POOL.install(|| {
batches
.into_par_iter()
.map(|transaction_batch| {
let transaction_count =
transaction_batch.batch.sanitized_transactions().len() as u64;
let mut timings = ExecuteTimings::default();
let (result, execute_batches_time): (Result<()>, Measure) = measure!(
{
execute_batch(
transaction_batch,
bank,
transaction_status_sender,
replay_vote_sender,
&mut timings,
log_messages_bytes_limit,
prioritization_fee_cache,
)
},
"execute_batch",
);
let thread_index = PAR_THREAD_POOL.current_thread_index().unwrap();
execution_timings_per_thread
.lock()
.unwrap()
.entry(thread_index)
.and_modify(|thread_execution_time| {
let ThreadExecuteTimings {
total_thread_us,
total_transactions_executed,
execute_timings: total_thread_execute_timings,
} = thread_execution_time;
*total_thread_us += execute_batches_time.as_us();
*total_transactions_executed += transaction_count;
total_thread_execute_timings
.saturating_add_in_place(ExecuteTimingType::TotalBatchesLen, 1);
total_thread_execute_timings.accumulate(&timings);
})
.or_insert(ThreadExecuteTimings {
total_thread_us: execute_batches_time.as_us(),
total_transactions_executed: transaction_count,
execute_timings: timings,
});
result
})
.collect()
});
execute_batches_elapsed.stop();
first_err(&results)?;
Ok(ExecuteBatchesInternalMetrics {
execution_timings_per_thread: execution_timings_per_thread.into_inner().unwrap(),
total_batches_len: batches.len() as u64,
execute_batches_us: execute_batches_elapsed.as_us(),
})
}
fn rebatch_transactions<'a>(
lock_results: &'a [Result<()>],
bank: &'a Arc<Bank>,
sanitized_txs: &'a [SanitizedTransaction],
start: usize,
end: usize,
transaction_indexes: &'a [usize],
) -> TransactionBatchWithIndexes<'a, 'a> {
let txs = &sanitized_txs[start..=end];
let results = &lock_results[start..=end];
let mut tx_batch = TransactionBatch::new(results.to_vec(), bank, Cow::from(txs));
tx_batch.set_needs_unlock(false);
let transaction_indexes = transaction_indexes[start..=end].to_vec();
TransactionBatchWithIndexes {
batch: tx_batch,
transaction_indexes,
}
}
fn execute_batches(
bank: &Arc<Bank>,
batches: &[TransactionBatchWithIndexes],
transaction_status_sender: Option<&TransactionStatusSender>,
replay_vote_sender: Option<&ReplayVoteSender>,
timing: &mut BatchExecutionTiming,
log_messages_bytes_limit: Option<usize>,
prioritization_fee_cache: &PrioritizationFeeCache,
) -> Result<()> {
if batches.is_empty() {
return Ok(());
}
let ((lock_results, sanitized_txs), transaction_indexes): ((Vec<_>, Vec<_>), Vec<_>) = batches
.iter()
.flat_map(|batch| {
batch
.batch
.lock_results()
.iter()
.cloned()
.zip(batch.batch.sanitized_transactions().to_vec())
.zip(batch.transaction_indexes.to_vec())
})
.unzip();
let mut minimal_tx_cost = u64::MAX;
let mut total_cost: u64 = 0;
let tx_costs = sanitized_txs
.iter()
.map(|tx| {
let tx_cost = CostModel::calculate_cost(tx, &bank.feature_set);
let cost = tx_cost.sum();
minimal_tx_cost = std::cmp::min(minimal_tx_cost, cost);
total_cost = total_cost.saturating_add(cost);
tx_cost
})
.collect::<Vec<_>>();
if bank
.feature_set
.is_active(&feature_set::apply_cost_tracker_during_replay::id())
{
let mut cost_tracker = bank.write_cost_tracker().unwrap();
for tx_cost in &tx_costs {
cost_tracker
.try_add(tx_cost)
.map_err(TransactionError::from)?;
}
}
let target_batch_count = get_thread_count() as u64;
let mut tx_batches: Vec<TransactionBatchWithIndexes> = vec![];
let rebatched_txs = if total_cost > target_batch_count.saturating_mul(minimal_tx_cost) {
let target_batch_cost = total_cost / target_batch_count;
let mut batch_cost: u64 = 0;
let mut slice_start = 0;
tx_costs
.into_iter()
.enumerate()
.for_each(|(index, tx_cost)| {
let next_index = index + 1;
batch_cost = batch_cost.saturating_add(tx_cost.sum());
if batch_cost >= target_batch_cost || next_index == sanitized_txs.len() {
let tx_batch = rebatch_transactions(
&lock_results,
bank,
&sanitized_txs,
slice_start,
index,
&transaction_indexes,
);
slice_start = next_index;
tx_batches.push(tx_batch);
batch_cost = 0;
}
});
&tx_batches[..]
} else {
batches
};
let execute_batches_internal_metrics = execute_batches_internal(
bank,
rebatched_txs,
transaction_status_sender,
replay_vote_sender,
log_messages_bytes_limit,
prioritization_fee_cache,
)?;
timing.accumulate(execute_batches_internal_metrics);
Ok(())
}
/// Process an ordered list of entries in parallel
/// 1. In order lock accounts for each entry while the lock succeeds, up to a Tick entry
/// 2. Process the locked group in parallel
/// 3. Register the `Tick` if it's available
/// 4. Update the leader scheduler, goto 1
///
/// This method is for use testing against a single Bank, and assumes `Bank::transaction_count()`
/// represents the number of transactions executed in this Bank
pub fn process_entries_for_tests(
bank: &Arc<Bank>,
entries: Vec<Entry>,
randomize: bool,
transaction_status_sender: Option<&TransactionStatusSender>,
replay_vote_sender: Option<&ReplayVoteSender>,
) -> Result<()> {
let verify_transaction = {
let bank = bank.clone();
move |versioned_tx: VersionedTransaction| -> Result<SanitizedTransaction> {
bank.verify_transaction(versioned_tx, TransactionVerificationMode::FullVerification)
}
};
let mut entry_starting_index: usize = bank.transaction_count().try_into().unwrap();
let mut batch_timing = BatchExecutionTiming::default();
let mut replay_entries: Vec<_> =
entry::verify_transactions(entries, Arc::new(verify_transaction))?
.into_iter()
.map(|entry| {
let starting_index = entry_starting_index;
if let EntryType::Transactions(ref transactions) = entry {
entry_starting_index = entry_starting_index.saturating_add(transactions.len());
}
ReplayEntry {
entry,
starting_index,
}
})
.collect();
let ignored_prioritization_fee_cache = PrioritizationFeeCache::new(0u64);
let result = process_entries(
bank,
&mut replay_entries,
randomize,
transaction_status_sender,
replay_vote_sender,
&mut batch_timing,
None,
&ignored_prioritization_fee_cache,
);
debug!("process_entries: {:?}", batch_timing);
result
}
// Note: If randomize is true this will shuffle entries' transactions in-place.
fn process_entries(
bank: &Arc<Bank>,
entries: &mut [ReplayEntry],
randomize: bool,
transaction_status_sender: Option<&TransactionStatusSender>,
replay_vote_sender: Option<&ReplayVoteSender>,
batch_timing: &mut BatchExecutionTiming,
log_messages_bytes_limit: Option<usize>,
prioritization_fee_cache: &PrioritizationFeeCache,
) -> Result<()> {
// accumulator for entries that can be processed in parallel
let mut batches = vec![];
let mut tick_hashes = vec![];
let mut rng = thread_rng();
for ReplayEntry {
entry,
starting_index,
} in entries
{
match entry {
EntryType::Tick(hash) => {
// If it's a tick, save it for later
tick_hashes.push(hash);
if bank.is_block_boundary(bank.tick_height() + tick_hashes.len() as u64) {
// If it's a tick that will cause a new blockhash to be created,
// execute the group and register the tick
execute_batches(
bank,
&batches,
transaction_status_sender,
replay_vote_sender,
batch_timing,
log_messages_bytes_limit,
prioritization_fee_cache,
)?;
batches.clear();
for hash in &tick_hashes {
bank.register_tick(hash);
}
tick_hashes.clear();
}
}
EntryType::Transactions(transactions) => {
let starting_index = *starting_index;
let transaction_indexes = if randomize {
let mut transactions_and_indexes: Vec<(SanitizedTransaction, usize)> =
transactions.drain(..).zip(starting_index..).collect();
transactions_and_indexes.shuffle(&mut rng);
let (txs, indexes): (Vec<_>, Vec<_>) =
transactions_and_indexes.into_iter().unzip();
*transactions = txs;
indexes
} else {
(starting_index..starting_index.saturating_add(transactions.len())).collect()
};
loop {
// try to lock the accounts
let batch = bank.prepare_sanitized_batch(transactions);
let first_lock_err = first_err(batch.lock_results());
// if locking worked
if first_lock_err.is_ok() {
batches.push(TransactionBatchWithIndexes {
batch,
transaction_indexes,
});
// done with this entry
break;
}
// else we failed to lock, 2 possible reasons
if batches.is_empty() {
// An entry has account lock conflicts with *itself*, which should not happen
// if generated by a properly functioning leader
datapoint_error!(
"validator_process_entry_error",
(
"error",
format!(
"Lock accounts error, entry conflicts with itself, txs: {transactions:?}"
),
String
)
);
// bail
first_lock_err?;
} else {
// else we have an entry that conflicts with a prior entry
// execute the current queue and try to process this entry again
execute_batches(
bank,
&batches,
transaction_status_sender,
replay_vote_sender,
batch_timing,
log_messages_bytes_limit,
prioritization_fee_cache,
)?;
batches.clear();
}
}
}
}
}
execute_batches(
bank,
&batches,
transaction_status_sender,
replay_vote_sender,
batch_timing,
log_messages_bytes_limit,
prioritization_fee_cache,
)?;
for hash in tick_hashes {
bank.register_tick(hash);
}
Ok(())
}
#[derive(Error, Debug)]
pub enum BlockstoreProcessorError {
#[error("failed to load entries, error: {0}")]
FailedToLoadEntries(#[from] BlockstoreError),
#[error("failed to load meta")]
FailedToLoadMeta,
#[error("invalid block error: {0}")]
InvalidBlock(#[from] BlockError),
#[error("invalid transaction error: {0}")]
InvalidTransaction(#[from] TransactionError),
#[error("no valid forks found")]
NoValidForksFound,
#[error("invalid hard fork slot {0}")]
InvalidHardFork(Slot),
#[error("root bank with mismatched capitalization at {0}")]
RootBankWithMismatchedCapitalization(Slot),
}
/// Callback for accessing bank state while processing the blockstore
pub type ProcessCallback = Arc<dyn Fn(&Bank) + Sync + Send>;
#[derive(Default, Clone)]
pub struct ProcessOptions {
/// Run PoH, transaction signature and other transaction verifications on the entries.
pub run_verification: bool,
pub full_leader_cache: bool,
pub halt_at_slot: Option<Slot>,
pub new_hard_forks: Option<Vec<Slot>>,
pub debug_keys: Option<Arc<HashSet<Pubkey>>>,
pub account_indexes: AccountSecondaryIndexes,
pub limit_load_slot_count_from_snapshot: Option<usize>,
pub allow_dead_slots: bool,
pub accounts_db_test_hash_calculation: bool,
pub accounts_db_skip_shrink: bool,
pub accounts_db_config: Option<AccountsDbConfig>,
pub verify_index: bool,
pub shrink_ratio: AccountShrinkThreshold,
pub runtime_config: RuntimeConfig,
pub on_halt_store_hash_raw_data_for_debug: bool,
/// true if after processing the contents of the blockstore at startup, we should run an accounts hash calc
/// This is useful for debugging.
pub run_final_accounts_hash_calc: bool,
pub use_snapshot_archives_at_startup: UseSnapshotArchivesAtStartup,
}
pub fn test_process_blockstore(
genesis_config: &GenesisConfig,
blockstore: &Blockstore,
opts: &ProcessOptions,
exit: Arc<AtomicBool>,
) -> (Arc<RwLock<BankForks>>, LeaderScheduleCache) {
// Spin up a thread to be a fake Accounts Background Service. Need to intercept and handle all
// EpochAccountsHash requests so future rooted banks do not hang in Bank::freeze() waiting for
// an in-flight EAH calculation to complete.
let (snapshot_request_sender, snapshot_request_receiver) = crossbeam_channel::unbounded();
let abs_request_sender = AbsRequestSender::new(snapshot_request_sender);
let bg_exit = Arc::new(AtomicBool::new(false));
let bg_thread = {
let exit = Arc::clone(&bg_exit);
std::thread::spawn(move || {
while !exit.load(Relaxed) {
snapshot_request_receiver
.try_iter()
.filter(|snapshot_request| {
snapshot_request.request_kind == SnapshotRequestKind::EpochAccountsHash
})
.for_each(|snapshot_request| {
snapshot_request
.snapshot_root_bank
.rc
.accounts
.accounts_db
.epoch_accounts_hash_manager
.set_valid(
EpochAccountsHash::new(Hash::new_unique()),
snapshot_request.snapshot_root_bank.slot(),
)
});
std::thread::sleep(Duration::from_millis(100));
}
})
};
let (bank_forks, leader_schedule_cache, ..) = crate::bank_forks_utils::load_bank_forks(
genesis_config,
blockstore,
Vec::new(),
None,
None,
opts,
None,
None,
None,
exit,
);
process_blockstore_from_root(
blockstore,
&bank_forks,
&leader_schedule_cache,
opts,
None,
None,
None,
&abs_request_sender,
)
.unwrap();
bg_exit.store(true, Relaxed);
bg_thread.join().unwrap();
(bank_forks, leader_schedule_cache)
}
pub(crate) fn process_blockstore_for_bank_0(
genesis_config: &GenesisConfig,
blockstore: &Blockstore,
account_paths: Vec<PathBuf>,
opts: &ProcessOptions,
cache_block_meta_sender: Option<&CacheBlockMetaSender>,
entry_notification_sender: Option<&EntryNotifierSender>,
accounts_update_notifier: Option<AccountsUpdateNotifier>,
exit: Arc<AtomicBool>,
) -> Arc<RwLock<BankForks>> {
// Setup bank for slot 0
let bank0 = Bank::new_with_paths(
genesis_config,
Arc::new(opts.runtime_config.clone()),
account_paths,
opts.debug_keys.clone(),
None,
opts.account_indexes.clone(),
opts.shrink_ratio,
false,
opts.accounts_db_config.clone(),
accounts_update_notifier,
exit,
);
let bank_forks = Arc::new(RwLock::new(BankForks::new(bank0)));
info!("Processing ledger for slot 0...");
process_bank_0(
&bank_forks.read().unwrap().root_bank(),
blockstore,
opts,
&VerifyRecyclers::default(),
cache_block_meta_sender,
entry_notification_sender,
);
bank_forks
}
/// Process blockstore from a known root bank
#[allow(clippy::too_many_arguments)]
pub fn process_blockstore_from_root(
blockstore: &Blockstore,
bank_forks: &RwLock<BankForks>,
leader_schedule_cache: &LeaderScheduleCache,
opts: &ProcessOptions,
transaction_status_sender: Option<&TransactionStatusSender>,
cache_block_meta_sender: Option<&CacheBlockMetaSender>,
entry_notification_sender: Option<&EntryNotifierSender>,
accounts_background_request_sender: &AbsRequestSender,
) -> result::Result<(), BlockstoreProcessorError> {
let (start_slot, start_slot_hash) = {
// Starting slot must be a root, and thus has no parents
assert_eq!(bank_forks.read().unwrap().banks().len(), 1);
let bank = bank_forks.read().unwrap().root_bank();
assert!(bank.parent().is_none());
(bank.slot(), bank.hash())
};
info!("Processing ledger from slot {}...", start_slot);
let now = Instant::now();
// Ensure start_slot is rooted for correct replay; also ensure start_slot and
// qualifying children are marked as connected
if blockstore.is_primary_access() {
blockstore
.mark_slots_as_if_rooted_normally_at_startup(
vec![(start_slot, Some(start_slot_hash))],
true,
)
.expect("Couldn't mark start_slot as root in startup");
blockstore
.set_and_chain_connected_on_root_and_next_slots(start_slot)
.expect("Couldn't mark start_slot as connected during startup")
} else {
info!(
"Start slot {} isn't a root, and won't be updated due to secondary blockstore access",
start_slot
);
}
if let Ok(Some(highest_slot)) = blockstore.highest_slot() {
info!("ledger holds data through slot {}", highest_slot);
}
let mut timing = ExecuteTimings::default();
let (num_slots_processed, num_new_roots_found) = if let Some(start_slot_meta) = blockstore
.meta(start_slot)
.unwrap_or_else(|_| panic!("Failed to get meta for slot {start_slot}"))
{
load_frozen_forks(
bank_forks,
&start_slot_meta,
blockstore,
leader_schedule_cache,
opts,
transaction_status_sender,
cache_block_meta_sender,
entry_notification_sender,
&mut timing,
accounts_background_request_sender,
)?
} else {
// If there's no meta in the blockstore for the input `start_slot`,
// then we started from a snapshot and are unable to process anything.
//
// If the ledger has any data at all, the snapshot was likely taken at
// a slot that is not within the range of ledger min/max slot(s).
warn!(
"Starting slot {} is not in Blockstore, unable to process",
start_slot
);
(0, 0)
};
let processing_time = now.elapsed();
datapoint_info!(
"process_blockstore_from_root",
("total_time_us", processing_time.as_micros(), i64),
(
"frozen_banks",
bank_forks.read().unwrap().frozen_banks().len(),
i64
),
("slot", bank_forks.read().unwrap().root(), i64),
("num_slots_processed", num_slots_processed, i64),
("num_new_roots_found", num_new_roots_found, i64),
("forks", bank_forks.read().unwrap().banks().len(), i64),
);
info!("ledger processing timing: {:?}", timing);
{
let bank_forks = bank_forks.read().unwrap();
let mut bank_slots = bank_forks.banks().keys().copied().collect::<Vec<_>>();
bank_slots.sort_unstable();
info!(
"ledger processed in {}. root slot is {}, {} bank{}: {}",
HumanTime::from(chrono::Duration::from_std(processing_time).unwrap())
.to_text_en(Accuracy::Precise, Tense::Present),
bank_forks.root(),
bank_slots.len(),
if bank_slots.len() > 1 { "s" } else { "" },
bank_slots.iter().map(|slot| slot.to_string()).join(", "),
);
assert!(bank_forks.active_bank_slots().is_empty());
}
Ok(())
}
/// Verify that a segment of entries has the correct number of ticks and hashes
fn verify_ticks(
bank: &Bank,
entries: &[Entry],
slot_full: bool,
tick_hash_count: &mut u64,
) -> std::result::Result<(), BlockError> {
let next_bank_tick_height = bank.tick_height() + entries.tick_count();
let max_bank_tick_height = bank.max_tick_height();
if next_bank_tick_height > max_bank_tick_height {
warn!("Too many entry ticks found in slot: {}", bank.slot());
return Err(BlockError::TooManyTicks);
}
if next_bank_tick_height < max_bank_tick_height && slot_full {
info!("Too few entry ticks found in slot: {}", bank.slot());
return Err(BlockError::TooFewTicks);
}
if next_bank_tick_height == max_bank_tick_height {
let has_trailing_entry = entries.last().map(|e| !e.is_tick()).unwrap_or_default();
if has_trailing_entry {
warn!("Slot: {} did not end with a tick entry", bank.slot());
return Err(BlockError::TrailingEntry);
}
if !slot_full {
warn!("Slot: {} was not marked full", bank.slot());
return Err(BlockError::InvalidLastTick);
}
}
let hashes_per_tick = bank.hashes_per_tick().unwrap_or(0);
if !entries.verify_tick_hash_count(tick_hash_count, hashes_per_tick) {
warn!(
"Tick with invalid number of hashes found in slot: {}",
bank.slot()
);
return Err(BlockError::InvalidTickHashCount);
}
Ok(())
}
fn confirm_full_slot(
blockstore: &Blockstore,
bank: &Arc<Bank>,
opts: &ProcessOptions,
recyclers: &VerifyRecyclers,
progress: &mut ConfirmationProgress,
transaction_status_sender: Option<&TransactionStatusSender>,
entry_notification_sender: Option<&EntryNotifierSender>,
replay_vote_sender: Option<&ReplayVoteSender>,
timing: &mut ExecuteTimings,
) -> result::Result<(), BlockstoreProcessorError> {
let mut confirmation_timing = ConfirmationTiming::default();
let skip_verification = !opts.run_verification;
let ignored_prioritization_fee_cache = PrioritizationFeeCache::new(0u64);
confirm_slot(
blockstore,
bank,
&mut confirmation_timing,
progress,
skip_verification,
transaction_status_sender,
entry_notification_sender,
replay_vote_sender,
recyclers,
opts.allow_dead_slots,
opts.runtime_config.log_messages_bytes_limit,
&ignored_prioritization_fee_cache,
)?;
timing.accumulate(&confirmation_timing.batch_execute.totals);
if !bank.is_complete() {
Err(BlockstoreProcessorError::InvalidBlock(
BlockError::Incomplete,
))
} else {
Ok(())
}
}
/// Measures different parts of the slot confirmation processing pipeline.
#[derive(Debug)]
pub struct ConfirmationTiming {
/// Moment when the `ConfirmationTiming` instance was created. Used to track the total wall
/// clock time from the moment the first shard for the slot is received and to the moment the
/// slot is complete.
pub started: Instant,
/// Wall clock time used by the slot confirmation code, including PoH/signature verification,
/// and replay. As replay can run in parallel with the verification, this value can not be
/// recovered from the `replay_elapsed` and or `{poh,transaction}_verify_elapsed`. This
/// includes failed cases, when `confirm_slot_entries` exist with an error. In microseconds.
pub confirmation_elapsed: u64,
/// Wall clock time used by the entry replay code. Does not include the PoH or the transaction
/// signature/precompiles verification, but can overlap with the PoH and signature verification.
/// In microseconds.
pub replay_elapsed: u64,
/// Wall clock times, used for the PoH verification of entries. In microseconds.
pub poh_verify_elapsed: u64,
/// Wall clock time, used for the signature verification as well as precompiles verification.
/// In microseconds.
pub transaction_verify_elapsed: u64,
/// Wall clock time spent loading data sets (and entries) from the blockstore. This does not
/// include the case when the blockstore load failed. In microseconds.
pub fetch_elapsed: u64,
/// Same as `fetch_elapsed` above, but for the case when the blockstore load fails. In
/// microseconds.
pub fetch_fail_elapsed: u64,
/// `batch_execute()` measurements.
pub batch_execute: BatchExecutionTiming,
}
impl Default for ConfirmationTiming {
fn default() -> Self {
Self {
started: Instant::now(),
confirmation_elapsed: 0,
replay_elapsed: 0,
poh_verify_elapsed: 0,
transaction_verify_elapsed: 0,
fetch_elapsed: 0,
fetch_fail_elapsed: 0,
batch_execute: BatchExecutionTiming::default(),
}
}
}
/// Measures times related to transaction execution in a slot.