forked from solana-labs/solana
-
Notifications
You must be signed in to change notification settings - Fork 344
/
Copy pathblockstore_processor.rs
5432 lines (4930 loc) · 196 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::*,
rayon::{prelude::*, ThreadPool},
scopeguard::defer,
solana_accounts_db::{
accounts_db::AccountsDbConfig, accounts_update_notifier_interface::AccountsUpdateNotifier,
epoch_accounts_hash::EpochAccountsHash,
},
solana_cost_model::cost_model::CostModel,
solana_entry::entry::{
self, create_ticks, Entry, EntrySlice, EntryType, EntryVerificationStatus, VerifyRecyclers,
},
solana_measure::{measure::Measure, measure_us},
solana_metrics::datapoint_error,
solana_rayon_threadlimit::{get_max_thread_count, get_thread_count},
solana_runtime::{
accounts_background_service::{AbsRequestSender, SnapshotRequestKind},
bank::{Bank, PreCommitResult, TransactionBalancesSet},
bank_forks::{BankForks, SetRootError},
bank_utils,
commitment::VOTE_THRESHOLD_SIZE,
installed_scheduler_pool::BankWithScheduler,
prioritization_fee_cache::PrioritizationFeeCache,
runtime_config::RuntimeConfig,
transaction_batch::{OwnedOrBorrowed, TransactionBatch},
vote_sender_types::ReplayVoteSender,
},
solana_runtime_transaction::{
runtime_transaction::RuntimeTransaction, transaction_with_meta::TransactionWithMeta,
},
solana_sdk::{
clock::{Slot, MAX_PROCESSING_AGE},
genesis_config::GenesisConfig,
hash::Hash,
pubkey::Pubkey,
signature::{Keypair, Signature},
transaction::{
Result, SanitizedTransaction, TransactionError, TransactionVerificationMode,
VersionedTransaction,
},
},
solana_svm::{
transaction_commit_result::{TransactionCommitResult, TransactionCommitResultExtensions},
transaction_processing_result::{ProcessedTransaction, TransactionProcessingResult},
transaction_processor::ExecutionRecordingConfig,
},
solana_svm_transaction::{svm_message::SVMMessage, svm_transaction::SVMTransaction},
solana_timings::{report_execute_timings, ExecuteTimingType, ExecuteTimings},
solana_transaction_status::token_balances::TransactionTokenBalancesSet,
solana_vote::vote_account::VoteAccountsHashMap,
std::{
borrow::Cow,
collections::{HashMap, HashSet},
num::Saturating,
ops::{Index, Range},
path::PathBuf,
result,
sync::{
atomic::{AtomicBool, Ordering::Relaxed},
Arc, Mutex, RwLock,
},
time::{Duration, Instant},
vec::Drain,
},
thiserror::Error,
ExecuteTimingType::{NumExecuteBatches, TotalBatchesLen},
};
#[cfg(feature = "dev-context-only-utils")]
use {qualifier_attr::qualifiers, solana_runtime::bank::HashOverrides};
pub struct TransactionBatchWithIndexes<'a, 'b, Tx: SVMMessage> {
pub batch: TransactionBatch<'a, 'b, Tx>,
pub transaction_indexes: Vec<usize>,
}
// `TransactionBatchWithIndexes` but without the `Drop` that prevents
// us from nicely unwinding these with manual unlocking.
pub struct LockedTransactionsWithIndexes<Tx: SVMMessage> {
lock_results: Vec<Result<()>>,
transactions: Vec<RuntimeTransaction<Tx>>,
starting_index: usize,
}
struct ReplayEntry {
entry: EntryType<RuntimeTransaction<SanitizedTransaction>>,
starting_index: usize,
}
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 do_get_first_error<T, Tx: SVMTransaction>(
batch: &TransactionBatch<Tx>,
results: &[Result<T>],
) -> Option<(Result<()>, Signature)> {
let mut first_err = None;
for (result, transaction) in results.iter().zip(batch.sanitized_transactions()) {
if let Err(err) = result {
if first_err.is_none() {
first_err = Some((Err(err.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 get_first_error<T, Tx: SVMTransaction>(
batch: &TransactionBatch<Tx>,
commit_results: &[Result<T>],
) -> Result<()> {
do_get_first_error(batch, commit_results)
.map(|(error, _signature)| error)
.unwrap_or(Ok(()))
}
fn create_thread_pool(num_threads: usize) -> ThreadPool {
rayon::ThreadPoolBuilder::new()
.num_threads(num_threads)
.thread_name(|i| format!("solReplayTx{i:02}"))
.build()
.expect("new rayon threadpool")
}
pub fn execute_batch<'a>(
batch: &'a TransactionBatchWithIndexes<impl TransactionWithMeta>,
bank: &'a Arc<Bank>,
transaction_status_sender: Option<&'a TransactionStatusSender>,
replay_vote_sender: Option<&'a ReplayVoteSender>,
timings: &'a mut ExecuteTimings,
log_messages_bytes_limit: Option<usize>,
prioritization_fee_cache: &'a PrioritizationFeeCache,
// None is meaningfully used to detect this is called from the block producing unified
// scheduler. If so, suppress too verbose logging for the code path.
extra_pre_commit_callback: Option<
impl FnOnce(&Result<ProcessedTransaction>) -> Result<Option<usize>>,
>,
) -> Result<()> {
let TransactionBatchWithIndexes {
batch,
transaction_indexes,
} = batch;
let record_token_balances = transaction_status_sender.is_some();
let mut transaction_indexes = Cow::from(transaction_indexes);
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 pre_commit_callback = |timings: &mut _, processing_results: &_| -> PreCommitResult {
match extra_pre_commit_callback {
None => {
get_first_error(batch, processing_results)?;
check_block_cost_limits_if_enabled(batch, bank, timings, processing_results)?;
Ok(None)
}
Some(extra_pre_commit_callback) => {
// We're entering into the block-producing unified scheduler special case...
// `processing_results` should always contain exactly only 1 result in that case.
assert_eq!(processing_results.len(), 1);
assert!(transaction_indexes.is_empty());
// From now on, we need to freeze-lock the tpu bank, in order to prevent it from
// freezing in the middle of this code-path. Otherwise, the assertion at the start
// of commit_transactions() would trigger panic because it's fatal runtime
// invariant violation.
let freeze_lock = bank.freeze_lock();
if let Some(index) = extra_pre_commit_callback(&processing_results[0])? {
let transaction_indexes = transaction_indexes.to_mut();
// Adjust the empty new vec with the exact needed capacity. Otherwise, excess
// cap would be reserved on `.push()` in it.
transaction_indexes.reserve_exact(1);
transaction_indexes.push(index);
}
// At this point, poh should have been succeeded so it's guaranteed that the bank
// hasn't been frozen yet and we're still holding the lock. So, it's okay to pass
// down freeze_lock without any introspection here to be unconditionally dropped
// after commit_transactions(). This reasoning is same as
// solana_core::banking_stage::Consumer::execute_and_commit_transactions_locked()
Ok(Some(freeze_lock))
}
}
};
let (commit_results, balances) = batch
.bank()
.load_execute_and_commit_transactions_with_pre_commit_callback(
batch,
MAX_PROCESSING_AGE,
transaction_status_sender.is_some(),
ExecutionRecordingConfig::new_single_setting(transaction_status_sender.is_some()),
timings,
log_messages_bytes_limit,
pre_commit_callback,
)?;
bank_utils::find_and_send_votes(
batch.sanitized_transactions(),
&commit_results,
replay_vote_sender,
);
let committed_transactions = commit_results
.iter()
.zip(batch.sanitized_transactions())
.filter_map(|(commit_result, tx)| commit_result.was_committed().then_some(tx))
.collect_vec();
if let Some(transaction_status_sender) = transaction_status_sender {
let transactions: Vec<SanitizedTransaction> = batch
.sanitized_transactions()
.iter()
.map(|tx| tx.as_sanitized_transaction().into_owned())
.collect();
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.slot(),
transactions,
commit_results,
balances,
token_balances,
transaction_indexes.into_owned(),
);
}
prioritization_fee_cache.update(bank, committed_transactions.into_iter());
Ok(())
}
// collect transactions actual execution costs, subject to block limits;
// block will be marked as dead if exceeds cost limits, details will be
// reported to metric `replay-stage-mark_dead_slot`
fn check_block_cost_limits(
bank: &Bank,
processing_results: &[TransactionProcessingResult],
sanitized_transactions: &[impl TransactionWithMeta],
) -> Result<()> {
assert_eq!(sanitized_transactions.len(), processing_results.len());
let tx_costs_with_actual_execution_units: Vec<_> = processing_results
.iter()
.zip(sanitized_transactions)
.filter_map(|(processing_result, tx)| {
if let Ok(processed_tx) = processing_result {
Some(CostModel::calculate_cost_for_executed_transaction(
tx,
processed_tx.executed_units(),
processed_tx.loaded_accounts_data_size(),
&bank.feature_set,
))
} else {
None
}
})
.collect();
{
let mut cost_tracker = bank.write_cost_tracker().unwrap();
for tx_cost in &tx_costs_with_actual_execution_units {
cost_tracker
.try_add(tx_cost)
.map_err(TransactionError::from)?;
}
}
Ok(())
}
fn check_block_cost_limits_if_enabled(
batch: &TransactionBatch<impl TransactionWithMeta>,
bank: &Bank,
timings: &mut ExecuteTimings,
processing_results: &[TransactionProcessingResult],
) -> Result<()> {
let (check_block_cost_limits_result, check_block_cost_limits_us) = measure_us!(if bank
.feature_set
.is_active(&solana_feature_set::apply_cost_tracker_during_replay::id())
{
check_block_cost_limits(bank, processing_results, batch.sanitized_transactions())
} else {
Ok(())
});
timings.saturating_add_in_place(
ExecuteTimingType::CheckBlockLimitsUs,
check_block_cost_limits_us,
);
check_block_cost_limits_result
}
#[derive(Default)]
pub struct ExecuteBatchesInternalMetrics {
execution_timings_per_thread: HashMap<usize, ThreadExecuteTimings>,
total_batches_len: u64,
execute_batches_us: u64,
}
impl ExecuteBatchesInternalMetrics {
pub fn new_with_timings_from_all_threads(execute_timings: ExecuteTimings) -> Self {
const DUMMY_THREAD_INDEX: usize = 999;
let mut new = Self::default();
new.execution_timings_per_thread.insert(
DUMMY_THREAD_INDEX,
ThreadExecuteTimings {
execute_timings,
..ThreadExecuteTimings::default()
},
);
new
}
}
fn execute_batches_internal(
bank: &Arc<Bank>,
replay_tx_thread_pool: &ThreadPool,
batches: &[TransactionBatchWithIndexes<RuntimeTransaction<SanitizedTransaction>>],
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<()>> = replay_tx_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_us) = measure_us!(execute_batch(
transaction_batch,
bank,
transaction_status_sender,
replay_vote_sender,
&mut timings,
log_messages_bytes_limit,
prioritization_fee_cache,
None::<fn(&_) -> _>,
));
let thread_index = replay_tx_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_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: Saturating(execute_batches_us),
total_transactions_executed: Saturating(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(),
})
}
// This fn diverts the code-path into two variants. Both must provide exactly the same set of
// validations. For this reason, this fn is deliberately inserted into the code path to be called
// inside process_entries(), so that Bank::prepare_sanitized_batch() has been called on all of
// batches already, while minimizing code duplication (thus divergent behavior risk) at the cost of
// acceptable overhead of meaningless buffering of batches for the scheduler variant.
//
// Also note that the scheduler variant can't implement the batch-level sanitization naively, due
// to the nature of individual tx processing. That's another reason of this particular placement of
// divergent point in the code-path (i.e. not one layer up with its own prepare_sanitized_batch()
// invocation).
fn process_batches(
bank: &BankWithScheduler,
replay_tx_thread_pool: &ThreadPool,
locked_entries: impl ExactSizeIterator<Item = LockedTransactionsWithIndexes<SanitizedTransaction>>,
transaction_status_sender: Option<&TransactionStatusSender>,
replay_vote_sender: Option<&ReplayVoteSender>,
batch_execution_timing: &mut BatchExecutionTiming,
log_messages_bytes_limit: Option<usize>,
prioritization_fee_cache: &PrioritizationFeeCache,
) -> Result<()> {
if bank.has_installed_scheduler() {
debug!(
"process_batches()/schedule_batches_for_execution({} batches)",
locked_entries.len()
);
// Scheduling usually succeeds (immediately returns `Ok(())`) here without being blocked on
// the actual transaction executions.
//
// As an exception, this code path could propagate the transaction execution _errors of
// previously-scheduled transactions_ to notify the replay stage. Then, the replay stage
// will bail out the further processing of the malformed (possibly malicious) block
// immediately, not to waste any system resources. Note that this propagation is of early
// hints. Even if errors won't be propagated in this way, they are guaranteed to be
// propagated eventually via the blocking fn called
// BankWithScheduler::wait_for_completed_scheduler().
//
// To recite, the returned error is completely unrelated to the argument's `locked_entries`
// at the hand. While being awkward, the _async_ unified scheduler is abusing this existing
// error propagation code path to the replay stage for compatibility and ease of
// integration, exploiting the fact that the replay stage doesn't care _which transaction
// the returned error is originating from_.
//
// In the future, more proper error propagation mechanism will be introduced once after we
// fully transition to the unified scheduler for the block verification. That one would be
// a push based one from the unified scheduler to the replay stage to eliminate the current
// overhead: 1 read lock per batch in
// `BankWithScheduler::schedule_transaction_executions()`.
schedule_batches_for_execution(bank, locked_entries)
} else {
debug!(
"process_batches()/rebatch_and_execute_batches({} batches)",
locked_entries.len()
);
rebatch_and_execute_batches(
bank,
replay_tx_thread_pool,
locked_entries,
transaction_status_sender,
replay_vote_sender,
batch_execution_timing,
log_messages_bytes_limit,
prioritization_fee_cache,
)
}
}
fn schedule_batches_for_execution(
bank: &BankWithScheduler,
locked_entries: impl Iterator<Item = LockedTransactionsWithIndexes<SanitizedTransaction>>,
) -> Result<()> {
// Track the first error encountered in the loop below, if any.
// This error will be propagated to the replay stage, or Ok(()).
let mut first_err = Ok(());
for LockedTransactionsWithIndexes {
lock_results,
transactions,
starting_index,
} in locked_entries
{
// unlock before sending to scheduler.
bank.unlock_accounts(transactions.iter().zip(lock_results.iter()));
// give ownership to scheduler. capture the first error, but continue the loop
// to unlock.
// scheduling is skipped if we have already detected an error in this loop
let indexes = starting_index..starting_index + transactions.len();
first_err = first_err.and_then(|()| {
bank.schedule_transaction_executions(transactions.into_iter().zip_eq(indexes))
});
}
first_err
}
fn rebatch_transactions<'a, Tx: TransactionWithMeta>(
lock_results: &'a [Result<()>],
bank: &'a Arc<Bank>,
sanitized_txs: &'a [Tx],
range: Range<usize>,
transaction_indexes: &'a [usize],
) -> TransactionBatchWithIndexes<'a, 'a, Tx> {
let txs = &sanitized_txs[range.clone()];
let results = &lock_results[range.clone()];
let mut tx_batch =
TransactionBatch::new(results.to_vec(), bank, OwnedOrBorrowed::Borrowed(txs));
tx_batch.set_needs_unlock(true); // unlock on drop for easier clean up
let transaction_indexes = transaction_indexes[range].to_vec();
TransactionBatchWithIndexes {
batch: tx_batch,
transaction_indexes,
}
}
fn rebatch_and_execute_batches(
bank: &Arc<Bank>,
replay_tx_thread_pool: &ThreadPool,
locked_entries: impl ExactSizeIterator<Item = LockedTransactionsWithIndexes<SanitizedTransaction>>,
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 locked_entries.len() == 0 {
return Ok(());
}
// Flatten the locked entries. Store the original entry lengths to avoid rebatching logic
// for small entries.
let mut original_entry_lengths = Vec::with_capacity(locked_entries.len());
let ((lock_results, sanitized_txs), transaction_indexes): ((Vec<_>, Vec<_>), Vec<_>) =
locked_entries
.flat_map(
|LockedTransactionsWithIndexes {
lock_results,
transactions,
starting_index,
}| {
let num_transactions = transactions.len();
original_entry_lengths.push(num_transactions);
lock_results
.into_iter()
.zip_eq(transactions)
.zip_eq(starting_index..starting_index + num_transactions)
},
)
.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);
cost
})
.collect::<Vec<_>>();
let target_batch_count = get_thread_count() as u64;
let mut tx_batches = 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, cost)| {
let next_index = index + 1;
batch_cost = batch_cost.saturating_add(cost);
if batch_cost >= target_batch_cost || next_index == sanitized_txs.len() {
let tx_batch = rebatch_transactions(
&lock_results,
bank,
&sanitized_txs,
slice_start..next_index,
&transaction_indexes,
);
slice_start = next_index;
tx_batches.push(tx_batch);
batch_cost = 0;
}
});
&tx_batches[..]
} else {
let mut slice_start = 0;
for num_transactions in original_entry_lengths {
let next_index = slice_start + num_transactions;
// this is more of a "re-construction" of the original batches than
// a rebatching. But the logic is the same, with the transfer of
// unlocking responsibility to the batch.
let tx_batch = rebatch_transactions(
&lock_results,
bank,
&sanitized_txs,
slice_start..next_index,
&transaction_indexes,
);
slice_start = next_index;
tx_batches.push(tx_batch);
}
&tx_batches[..]
};
let execute_batches_internal_metrics = execute_batches_internal(
bank,
replay_tx_thread_pool,
rebatched_txs,
transaction_status_sender,
replay_vote_sender,
log_messages_bytes_limit,
prioritization_fee_cache,
)?;
// Pass false because this code-path is never touched by unified scheduler.
timing.accumulate(execute_batches_internal_metrics, false);
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: &BankWithScheduler,
entries: Vec<Entry>,
transaction_status_sender: Option<&TransactionStatusSender>,
replay_vote_sender: Option<&ReplayVoteSender>,
) -> Result<()> {
let replay_tx_thread_pool = create_thread_pool(1);
let verify_transaction = {
let bank = bank.clone_with_scheduler();
move |versioned_tx: VersionedTransaction| -> Result<RuntimeTransaction<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 replay_entries: Vec<_> = entry::verify_transactions(
entries,
&replay_tx_thread_pool,
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,
&replay_tx_thread_pool,
replay_entries,
transaction_status_sender,
replay_vote_sender,
&mut batch_timing,
None,
&ignored_prioritization_fee_cache,
);
debug!("process_entries: {:?}", batch_timing);
result
}
fn process_entries(
bank: &BankWithScheduler,
replay_tx_thread_pool: &ThreadPool,
entries: Vec<ReplayEntry>,
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![];
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
process_batches(
bank,
replay_tx_thread_pool,
batches.drain(..),
transaction_status_sender,
replay_vote_sender,
batch_timing,
log_messages_bytes_limit,
prioritization_fee_cache,
)?;
for hash in tick_hashes.drain(..) {
bank.register_tick(&hash);
}
}
}
EntryType::Transactions(transactions) => {
queue_batches_with_lock_retry(
bank,
starting_index,
transactions,
&mut batches,
|batches| {
process_batches(
bank,
replay_tx_thread_pool,
batches,
transaction_status_sender,
replay_vote_sender,
batch_timing,
log_messages_bytes_limit,
prioritization_fee_cache,
)
},
)?;
}
}
}
process_batches(
bank,
replay_tx_thread_pool,
batches.into_iter(),
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(())
}
/// If an entry can be locked without failure, the transactions are pushed
/// as a batch to `batches`. If the lock fails, the transactions are unlocked
/// and the batches are processed.
/// The locking process is retried, and if it fails again the block is marked
/// as dead.
/// If the lock retry succeeds, then the batch is pushed into `batches`.
fn queue_batches_with_lock_retry(
bank: &Bank,
starting_index: usize,
transactions: Vec<RuntimeTransaction<SanitizedTransaction>>,
batches: &mut Vec<LockedTransactionsWithIndexes<SanitizedTransaction>>,
mut process_batches: impl FnMut(
Drain<LockedTransactionsWithIndexes<SanitizedTransaction>>,
) -> Result<()>,
) -> Result<()> {
// try to lock the accounts
let lock_results = bank.try_lock_accounts(&transactions);
let first_lock_err = first_err(&lock_results);
if first_lock_err.is_ok() {
batches.push(LockedTransactionsWithIndexes {
lock_results,
transactions,
starting_index,
});
return Ok(());
}
// We need to unlock the transactions that succeeded to lock before the
// retry.
bank.unlock_accounts(transactions.iter().zip(lock_results.iter()));
// We failed to lock, there are 2 possible reasons:
// 1. A batch already in `batches` holds the lock.
// 2. The batch is "self-conflicting" (i.e. the batch has account lock conflicts with itself)
// Use the callback to process batches, and clear them.
// Clearing the batches will `Drop` the batches which will unlock the accounts.
process_batches(batches.drain(..))?;
// Retry the lock
let lock_results = bank.try_lock_accounts(&transactions);
match first_err(&lock_results) {
Ok(()) => {
batches.push(LockedTransactionsWithIndexes {
lock_results,
transactions,
starting_index,
});
Ok(())
}
Err(err) => {
// We still may have succeeded to lock some accounts, unlock them.
bank.unlock_accounts(transactions.iter().zip(lock_results.iter()));
// 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
)
);
Err(err)
}
}
}
#[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),
#[error("set root error {0}")]
SetRootError(#[from] SetRootError),
#[error("incomplete final fec set")]
IncompleteFinalFecSet,
#[error("invalid retransmitter signature final fec set")]
InvalidRetransmitterSignatureFinalFecSet,
}
/// Callback for accessing bank state after each slot is confirmed while
/// processing the blockstore
pub type ProcessSlotCallback = 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 slot_callback: Option<ProcessSlotCallback>,
pub new_hard_forks: Option<Vec<Slot>>,
pub debug_keys: Option<Arc<HashSet<Pubkey>>>,
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_force_initial_clean: bool,
pub accounts_db_config: Option<AccountsDbConfig>,
pub verify_index: bool,
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,
#[cfg(feature = "dev-context-only-utils")]
pub hash_overrides: Option<HashOverrides>,
pub abort_on_invalid_block: bool,
pub no_block_cost_limits: bool,
}
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,
opts,
None,
None,
None,
exit,
)
.unwrap();
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(