-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
main.rs
4379 lines (4171 loc) · 195 KB
/
main.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
#![allow(clippy::arithmetic_side_effects)]
use {
crate::{args::*, bigtable::*, ledger_path::*, ledger_utils::*, output::*, program::*},
chrono::{DateTime, Utc},
clap::{
crate_description, crate_name, value_t, value_t_or_exit, values_t_or_exit, App,
AppSettings, Arg, ArgMatches, SubCommand,
},
dashmap::DashMap,
itertools::Itertools,
log::*,
regex::Regex,
serde::{
ser::{SerializeSeq, Serializer},
Serialize,
},
serde_json::json,
solana_account_decoder::{UiAccount, UiAccountData, UiAccountEncoding},
solana_accounts_db::{
accounts::Accounts, accounts_db::CalcAccountsHashDataSource, accounts_index::ScanConfig,
hardened_unpack::MAX_GENESIS_ARCHIVE_UNPACKED_SIZE,
},
solana_clap_utils::{
hidden_unless_forced,
input_parsers::{cluster_type_of, pubkey_of, pubkeys_of},
input_validators::{
is_parsable, is_pow2, is_pubkey, is_pubkey_or_keypair, is_slot, is_valid_percentage,
validate_maximum_full_snapshot_archives_to_retain,
validate_maximum_incremental_snapshot_archives_to_retain,
},
},
solana_cli_output::{CliAccount, CliAccountNewConfig, OutputFormat},
solana_core::{
system_monitor_service::{SystemMonitorService, SystemMonitorStatsReportConfig},
validator::BlockVerificationMethod,
},
solana_cost_model::{cost_model::CostModel, cost_tracker::CostTracker},
solana_entry::entry::Entry,
solana_ledger::{
ancestor_iterator::AncestorIterator,
blockstore::{create_new_ledger, Blockstore, PurgeType},
blockstore_db::{self, columns as cf, Column, ColumnName, Database},
blockstore_options::{
AccessType, BlockstoreRecoveryMode, LedgerColumnOptions,
BLOCKSTORE_DIRECTORY_ROCKS_FIFO,
},
blockstore_processor::ProcessOptions,
shred::Shred,
use_snapshot_archives_at_startup::{self, UseSnapshotArchivesAtStartup},
},
solana_measure::{measure, measure::Measure},
solana_runtime::{
bank::{bank_hash_details, Bank, RewardCalculationEvent, TotalAccountsStats},
bank_forks::BankForks,
runtime_config::RuntimeConfig,
snapshot_archive_info::SnapshotArchiveInfoGetter,
snapshot_bank_utils,
snapshot_minimizer::SnapshotMinimizer,
snapshot_utils::{
ArchiveFormat, SnapshotVersion, DEFAULT_ARCHIVE_COMPRESSION,
SUPPORTED_ARCHIVE_COMPRESSION,
},
},
solana_sdk::{
account::{AccountSharedData, ReadableAccount, WritableAccount},
account_utils::StateMut,
clock::{Epoch, Slot, UnixTimestamp},
feature::{self, Feature},
feature_set::{self, FeatureSet},
genesis_config::ClusterType,
hash::Hash,
inflation::Inflation,
native_token::{lamports_to_sol, sol_to_lamports, Sol},
pubkey::Pubkey,
rent::Rent,
shred_version::compute_shred_version,
stake::{self, state::StakeStateV2},
system_program,
transaction::{
MessageHash, SanitizedTransaction, SimpleAddressLoader, VersionedTransaction,
},
},
solana_stake_program::stake_state::{self, PointValue},
solana_vote_program::{
self,
vote_state::{self, VoteState},
},
std::{
collections::{BTreeMap, BTreeSet, HashMap, HashSet},
ffi::OsStr,
fs::File,
io::{self, stdout, BufRead, BufReader, Write},
num::NonZeroUsize,
path::{Path, PathBuf},
process::{exit, Command, Stdio},
str::FromStr,
sync::{
atomic::{AtomicBool, Ordering},
Arc, RwLock,
},
time::{Duration, UNIX_EPOCH},
},
};
mod args;
mod bigtable;
mod ledger_path;
mod ledger_utils;
mod output;
mod program;
#[derive(PartialEq, Eq)]
enum LedgerOutputMethod {
Print,
Json,
}
fn get_program_ids(tx: &VersionedTransaction) -> impl Iterator<Item = &Pubkey> + '_ {
let message = &tx.message;
let account_keys = message.static_account_keys();
message
.instructions()
.iter()
.map(|ix| ix.program_id(account_keys))
}
fn parse_encoding_format(matches: &ArgMatches<'_>) -> UiAccountEncoding {
match matches.value_of("encoding") {
Some("jsonParsed") => UiAccountEncoding::JsonParsed,
Some("base64") => UiAccountEncoding::Base64,
Some("base64+zstd") => UiAccountEncoding::Base64Zstd,
_ => UiAccountEncoding::Base64,
}
}
fn output_slot_rewards(blockstore: &Blockstore, slot: Slot, method: &LedgerOutputMethod) {
// Note: rewards are not output in JSON yet
if *method == LedgerOutputMethod::Print {
if let Ok(Some(rewards)) = blockstore.read_rewards(slot) {
if !rewards.is_empty() {
println!(" Rewards:");
println!(
" {:<44} {:^15} {:<15} {:<20} {:>10}",
"Address", "Type", "Amount", "New Balance", "Commission",
);
for reward in rewards {
let sign = if reward.lamports < 0 { "-" } else { "" };
println!(
" {:<44} {:^15} {}◎{:<14.9} ◎{:<18.9} {}",
reward.pubkey,
if let Some(reward_type) = reward.reward_type {
format!("{reward_type}")
} else {
"-".to_string()
},
sign,
lamports_to_sol(reward.lamports.unsigned_abs()),
lamports_to_sol(reward.post_balance),
reward
.commission
.map(|commission| format!("{commission:>9}%"))
.unwrap_or_else(|| " -".to_string())
);
}
}
}
}
}
fn output_entry(
blockstore: &Blockstore,
method: &LedgerOutputMethod,
slot: Slot,
entry_index: usize,
entry: Entry,
) {
match method {
LedgerOutputMethod::Print => {
println!(
" Entry {} - num_hashes: {}, hash: {}, transactions: {}",
entry_index,
entry.num_hashes,
entry.hash,
entry.transactions.len()
);
for (transactions_index, transaction) in entry.transactions.into_iter().enumerate() {
println!(" Transaction {transactions_index}");
let tx_signature = transaction.signatures[0];
let tx_status_meta = blockstore
.read_transaction_status((tx_signature, slot))
.unwrap_or_else(|err| {
eprintln!(
"Failed to read transaction status for {} at slot {}: {}",
transaction.signatures[0], slot, err
);
None
})
.map(|meta| meta.into());
solana_cli_output::display::println_transaction(
&transaction,
tx_status_meta.as_ref(),
" ",
None,
None,
);
}
}
LedgerOutputMethod::Json => {
// Note: transaction status is not output in JSON yet
serde_json::to_writer(stdout(), &entry).expect("serialize entry");
stdout().write_all(b",\n").expect("newline");
}
}
}
fn output_slot(
blockstore: &Blockstore,
slot: Slot,
allow_dead_slots: bool,
method: &LedgerOutputMethod,
verbose_level: u64,
all_program_ids: &mut HashMap<Pubkey, u64>,
) -> Result<(), String> {
if blockstore.is_dead(slot) {
if allow_dead_slots {
if *method == LedgerOutputMethod::Print {
println!(" Slot is dead");
}
} else {
return Err("Dead slot".to_string());
}
}
let (entries, num_shreds, is_full) = blockstore
.get_slot_entries_with_shred_info(slot, 0, allow_dead_slots)
.map_err(|err| format!("Failed to load entries for slot {slot}: {err:?}"))?;
if *method == LedgerOutputMethod::Print {
if let Ok(Some(meta)) = blockstore.meta(slot) {
if verbose_level >= 1 {
println!(" {meta:?} is_full: {is_full}");
} else {
println!(
" num_shreds: {}, parent_slot: {:?}, next_slots: {:?}, num_entries: {}, \
is_full: {}",
num_shreds,
meta.parent_slot,
meta.next_slots,
entries.len(),
is_full,
);
}
}
}
if verbose_level >= 2 {
for (entry_index, entry) in entries.into_iter().enumerate() {
output_entry(blockstore, method, slot, entry_index, entry);
}
output_slot_rewards(blockstore, slot, method);
} else if verbose_level >= 1 {
let mut transactions = 0;
let mut num_hashes = 0;
let mut program_ids = HashMap::new();
let blockhash = if let Some(entry) = entries.last() {
entry.hash
} else {
Hash::default()
};
for entry in entries {
transactions += entry.transactions.len();
num_hashes += entry.num_hashes;
for transaction in entry.transactions {
for program_id in get_program_ids(&transaction) {
*program_ids.entry(*program_id).or_insert(0) += 1;
}
}
}
println!(" Transactions: {transactions}, hashes: {num_hashes}, block_hash: {blockhash}",);
for (pubkey, count) in program_ids.iter() {
*all_program_ids.entry(*pubkey).or_insert(0) += count;
}
println!(" Programs:");
output_sorted_program_ids(program_ids);
}
Ok(())
}
fn output_ledger(
blockstore: Blockstore,
starting_slot: Slot,
ending_slot: Slot,
allow_dead_slots: bool,
method: LedgerOutputMethod,
num_slots: Option<Slot>,
verbose_level: u64,
only_rooted: bool,
) {
let slot_iterator = blockstore
.slot_meta_iterator(starting_slot)
.unwrap_or_else(|err| {
eprintln!("Failed to load entries starting from slot {starting_slot}: {err:?}");
exit(1);
});
if method == LedgerOutputMethod::Json {
stdout().write_all(b"{\"ledger\":[\n").expect("open array");
}
let num_slots = num_slots.unwrap_or(Slot::MAX);
let mut num_printed = 0;
let mut all_program_ids = HashMap::new();
for (slot, slot_meta) in slot_iterator {
if only_rooted && !blockstore.is_root(slot) {
continue;
}
if slot > ending_slot {
break;
}
match method {
LedgerOutputMethod::Print => {
println!("Slot {} root?: {}", slot, blockstore.is_root(slot))
}
LedgerOutputMethod::Json => {
serde_json::to_writer(stdout(), &slot_meta).expect("serialize slot_meta");
stdout().write_all(b",\n").expect("newline");
}
}
if let Err(err) = output_slot(
&blockstore,
slot,
allow_dead_slots,
&method,
verbose_level,
&mut all_program_ids,
) {
eprintln!("{err}");
}
num_printed += 1;
if num_printed >= num_slots as usize {
break;
}
}
if method == LedgerOutputMethod::Json {
stdout().write_all(b"\n]}\n").expect("close array");
} else {
println!("Summary of Programs:");
output_sorted_program_ids(all_program_ids);
}
}
fn output_sorted_program_ids(program_ids: HashMap<Pubkey, u64>) {
let mut program_ids_array: Vec<_> = program_ids.into_iter().collect();
// Sort descending by count of program id
program_ids_array.sort_by(|a, b| b.1.cmp(&a.1));
for (program_id, count) in program_ids_array.iter() {
println!("{:<44}: {}", program_id.to_string(), count);
}
}
fn output_account(
pubkey: &Pubkey,
account: &AccountSharedData,
modified_slot: Option<Slot>,
print_account_data: bool,
encoding: UiAccountEncoding,
) {
println!("{pubkey}:");
println!(" balance: {} SOL", lamports_to_sol(account.lamports()));
println!(" owner: '{}'", account.owner());
println!(" executable: {}", account.executable());
if let Some(slot) = modified_slot {
println!(" slot: {slot}");
}
println!(" rent_epoch: {}", account.rent_epoch());
println!(" data_len: {}", account.data().len());
if print_account_data {
let account_data = UiAccount::encode(pubkey, account, encoding, None, None).data;
match account_data {
UiAccountData::Binary(data, data_encoding) => {
println!(" data: '{data}'");
println!(
" encoding: {}",
serde_json::to_string(&data_encoding).unwrap()
);
}
UiAccountData::Json(account_data) => {
println!(
" data: '{}'",
serde_json::to_string(&account_data).unwrap()
);
println!(" encoding: \"jsonParsed\"");
}
UiAccountData::LegacyBinary(_) => {}
};
}
}
fn render_dot(dot: String, output_file: &str, output_format: &str) -> io::Result<()> {
let mut child = Command::new("dot")
.arg(format!("-T{output_format}"))
.arg(format!("-o{output_file}"))
.stdin(Stdio::piped())
.spawn()
.map_err(|err| {
eprintln!("Failed to spawn dot: {err:?}");
err
})?;
let stdin = child.stdin.as_mut().unwrap();
stdin.write_all(&dot.into_bytes())?;
let status = child.wait_with_output()?.status;
if !status.success() {
return Err(io::Error::new(
io::ErrorKind::Other,
format!("dot failed with error {}", status.code().unwrap_or(-1)),
));
}
Ok(())
}
#[derive(Clone, Copy, Debug)]
enum GraphVoteAccountMode {
Disabled,
LastOnly,
WithHistory,
}
impl GraphVoteAccountMode {
const DISABLED: &'static str = "disabled";
const LAST_ONLY: &'static str = "last-only";
const WITH_HISTORY: &'static str = "with-history";
const ALL_MODE_STRINGS: &'static [&'static str] =
&[Self::DISABLED, Self::LAST_ONLY, Self::WITH_HISTORY];
fn is_enabled(&self) -> bool {
!matches!(self, Self::Disabled)
}
}
impl AsRef<str> for GraphVoteAccountMode {
fn as_ref(&self) -> &str {
match self {
Self::Disabled => Self::DISABLED,
Self::LastOnly => Self::LAST_ONLY,
Self::WithHistory => Self::WITH_HISTORY,
}
}
}
impl Default for GraphVoteAccountMode {
fn default() -> Self {
Self::Disabled
}
}
struct GraphVoteAccountModeError(String);
impl FromStr for GraphVoteAccountMode {
type Err = GraphVoteAccountModeError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
Self::DISABLED => Ok(Self::Disabled),
Self::LAST_ONLY => Ok(Self::LastOnly),
Self::WITH_HISTORY => Ok(Self::WithHistory),
_ => Err(GraphVoteAccountModeError(s.to_string())),
}
}
}
struct GraphConfig {
include_all_votes: bool,
vote_account_mode: GraphVoteAccountMode,
}
#[allow(clippy::cognitive_complexity)]
fn graph_forks(bank_forks: &BankForks, config: &GraphConfig) -> String {
let frozen_banks = bank_forks.frozen_banks();
let mut fork_slots: HashSet<_> = frozen_banks.keys().cloned().collect();
for (_, bank) in frozen_banks {
for parent in bank.parents() {
fork_slots.remove(&parent.slot());
}
}
// Search all forks and collect the last vote made by each validator
let mut last_votes = HashMap::new();
let default_vote_state = VoteState::default();
for fork_slot in &fork_slots {
let bank = &bank_forks[*fork_slot];
let total_stake = bank
.vote_accounts()
.iter()
.map(|(_, (stake, _))| stake)
.sum();
for (stake, vote_account) in bank.vote_accounts().values() {
let vote_state = vote_account.vote_state();
let vote_state = vote_state.unwrap_or(&default_vote_state);
if let Some(last_vote) = vote_state.votes.iter().last() {
let entry = last_votes.entry(vote_state.node_pubkey).or_insert((
last_vote.slot(),
vote_state.clone(),
*stake,
total_stake,
));
if entry.0 < last_vote.slot() {
*entry = (last_vote.slot(), vote_state.clone(), *stake, total_stake);
}
}
}
}
// Figure the stake distribution at all the nodes containing the last vote from each
// validator
let mut slot_stake_and_vote_count = HashMap::new();
for (last_vote_slot, _, stake, total_stake) in last_votes.values() {
let entry = slot_stake_and_vote_count
.entry(last_vote_slot)
.or_insert((0, 0, *total_stake));
entry.0 += 1;
entry.1 += stake;
assert_eq!(entry.2, *total_stake)
}
let mut dot = vec!["digraph {".to_string()];
// Build a subgraph consisting of all banks and links to their parent banks
dot.push(" subgraph cluster_banks {".to_string());
dot.push(" style=invis".to_string());
let mut styled_slots = HashSet::new();
let mut all_votes: HashMap<Pubkey, HashMap<Slot, VoteState>> = HashMap::new();
for fork_slot in &fork_slots {
let mut bank = bank_forks[*fork_slot].clone();
let mut first = true;
loop {
for (_, vote_account) in bank.vote_accounts().values() {
let vote_state = vote_account.vote_state();
let vote_state = vote_state.unwrap_or(&default_vote_state);
if let Some(last_vote) = vote_state.votes.iter().last() {
let validator_votes = all_votes.entry(vote_state.node_pubkey).or_default();
validator_votes
.entry(last_vote.slot())
.or_insert_with(|| vote_state.clone());
}
}
if !styled_slots.contains(&bank.slot()) {
dot.push(format!(
r#" "{}"[label="{} (epoch {})\nleader: {}{}{}",style="{}{}"];"#,
bank.slot(),
bank.slot(),
bank.epoch(),
bank.collector_id(),
if let Some(parent) = bank.parent() {
format!(
"\ntransactions: {}",
bank.transaction_count() - parent.transaction_count(),
)
} else {
"".to_string()
},
if let Some((votes, stake, total_stake)) =
slot_stake_and_vote_count.get(&bank.slot())
{
format!(
"\nvotes: {}, stake: {:.1} SOL ({:.1}%)",
votes,
lamports_to_sol(*stake),
*stake as f64 / *total_stake as f64 * 100.,
)
} else {
"".to_string()
},
if first { "filled," } else { "" },
""
));
styled_slots.insert(bank.slot());
}
first = false;
match bank.parent() {
None => {
if bank.slot() > 0 {
dot.push(format!(r#" "{}" -> "..." [dir=back]"#, bank.slot(),));
}
break;
}
Some(parent) => {
let slot_distance = bank.slot() - parent.slot();
let penwidth = if bank.epoch() > parent.epoch() {
"5"
} else {
"1"
};
let link_label = if slot_distance > 1 {
format!("label=\"{} slots\",color=red", slot_distance - 1)
} else {
"color=blue".to_string()
};
dot.push(format!(
r#" "{}" -> "{}"[{},dir=back,penwidth={}];"#,
bank.slot(),
parent.slot(),
link_label,
penwidth
));
bank = parent.clone();
}
}
}
}
dot.push(" }".to_string());
// Strafe the banks with links from validators to the bank they last voted on,
// while collecting information about the absent votes and stakes
let mut absent_stake = 0;
let mut absent_votes = 0;
let mut lowest_last_vote_slot = std::u64::MAX;
let mut lowest_total_stake = 0;
for (node_pubkey, (last_vote_slot, vote_state, stake, total_stake)) in &last_votes {
all_votes.entry(*node_pubkey).and_modify(|validator_votes| {
validator_votes.remove(last_vote_slot);
});
let maybe_styled_last_vote_slot = styled_slots.get(last_vote_slot);
if maybe_styled_last_vote_slot.is_none() {
if *last_vote_slot < lowest_last_vote_slot {
lowest_last_vote_slot = *last_vote_slot;
lowest_total_stake = *total_stake;
}
absent_votes += 1;
absent_stake += stake;
};
if config.vote_account_mode.is_enabled() {
let vote_history =
if matches!(config.vote_account_mode, GraphVoteAccountMode::WithHistory) {
format!(
"vote history:\n{}",
vote_state
.votes
.iter()
.map(|vote| format!(
"slot {} (conf={})",
vote.slot(),
vote.confirmation_count()
))
.collect::<Vec<_>>()
.join("\n")
)
} else {
format!(
"last vote slot: {}",
vote_state
.votes
.back()
.map(|vote| vote.slot().to_string())
.unwrap_or_else(|| "none".to_string())
)
};
dot.push(format!(
r#" "last vote {}"[shape=box,label="Latest validator vote: {}\nstake: {} SOL\nroot slot: {}\n{}"];"#,
node_pubkey,
node_pubkey,
lamports_to_sol(*stake),
vote_state.root_slot.unwrap_or(0),
vote_history,
));
dot.push(format!(
r#" "last vote {}" -> "{}" [style=dashed,label="latest vote"];"#,
node_pubkey,
if let Some(styled_last_vote_slot) = maybe_styled_last_vote_slot {
styled_last_vote_slot.to_string()
} else {
"...".to_string()
},
));
}
}
// Annotate the final "..." node with absent vote and stake information
if absent_votes > 0 {
dot.push(format!(
r#" "..."[label="...\nvotes: {}, stake: {:.1} SOL {:.1}%"];"#,
absent_votes,
lamports_to_sol(absent_stake),
absent_stake as f64 / lowest_total_stake as f64 * 100.,
));
}
// Add for vote information from all banks.
if config.include_all_votes {
for (node_pubkey, validator_votes) in &all_votes {
for (vote_slot, vote_state) in validator_votes {
dot.push(format!(
r#" "{} vote {}"[shape=box,style=dotted,label="validator vote: {}\nroot slot: {}\nvote history:\n{}"];"#,
node_pubkey,
vote_slot,
node_pubkey,
vote_state.root_slot.unwrap_or(0),
vote_state
.votes
.iter()
.map(|vote| format!("slot {} (conf={})", vote.slot(), vote.confirmation_count()))
.collect::<Vec<_>>()
.join("\n")
));
dot.push(format!(
r#" "{} vote {}" -> "{}" [style=dotted,label="vote"];"#,
node_pubkey,
vote_slot,
if styled_slots.contains(vote_slot) {
vote_slot.to_string()
} else {
"...".to_string()
},
));
}
}
}
dot.push("}".to_string());
dot.join("\n")
}
fn analyze_column<
C: solana_ledger::blockstore_db::Column + solana_ledger::blockstore_db::ColumnName,
>(
db: &Database,
name: &str,
) {
let mut key_len: u64 = 0;
let mut key_tot: u64 = 0;
let mut val_hist = histogram::Histogram::new();
let mut val_tot: u64 = 0;
let mut row_hist = histogram::Histogram::new();
for (key, val) in db.iter::<C>(blockstore_db::IteratorMode::Start).unwrap() {
// Key length is fixed, only need to calculate it once
if key_len == 0 {
key_len = C::key(key).len() as u64;
}
let val_len = val.len() as u64;
key_tot += key_len;
val_hist.increment(val_len).unwrap();
val_tot += val_len;
row_hist.increment(key_len + val_len).unwrap();
}
let json_result = if val_hist.entries() > 0 {
json!({
"column":name,
"entries":val_hist.entries(),
"key_stats":{
"max":key_len,
"total_bytes":key_tot,
},
"val_stats":{
"p50":val_hist.percentile(50.0).unwrap(),
"p90":val_hist.percentile(90.0).unwrap(),
"p99":val_hist.percentile(99.0).unwrap(),
"p999":val_hist.percentile(99.9).unwrap(),
"min":val_hist.minimum().unwrap(),
"max":val_hist.maximum().unwrap(),
"stddev":val_hist.stddev().unwrap(),
"total_bytes":val_tot,
},
"row_stats":{
"p50":row_hist.percentile(50.0).unwrap(),
"p90":row_hist.percentile(90.0).unwrap(),
"p99":row_hist.percentile(99.0).unwrap(),
"p999":row_hist.percentile(99.9).unwrap(),
"min":row_hist.minimum().unwrap(),
"max":row_hist.maximum().unwrap(),
"stddev":row_hist.stddev().unwrap(),
"total_bytes":key_tot + val_tot,
},
})
} else {
json!({
"column":name,
"entries":val_hist.entries(),
"key_stats":{
"max":key_len,
"total_bytes":0,
},
"val_stats":{
"total_bytes":0,
},
"row_stats":{
"total_bytes":0,
},
})
};
println!("{}", serde_json::to_string_pretty(&json_result).unwrap());
}
fn analyze_storage(database: &Database) {
use blockstore_db::columns::*;
analyze_column::<SlotMeta>(database, "SlotMeta");
analyze_column::<Orphans>(database, "Orphans");
analyze_column::<DeadSlots>(database, "DeadSlots");
analyze_column::<DuplicateSlots>(database, "DuplicateSlots");
analyze_column::<ErasureMeta>(database, "ErasureMeta");
analyze_column::<BankHash>(database, "BankHash");
analyze_column::<Root>(database, "Root");
analyze_column::<Index>(database, "Index");
analyze_column::<ShredData>(database, "ShredData");
analyze_column::<ShredCode>(database, "ShredCode");
analyze_column::<TransactionStatus>(database, "TransactionStatus");
analyze_column::<AddressSignatures>(database, "AddressSignatures");
analyze_column::<TransactionMemos>(database, "TransactionMemos");
analyze_column::<TransactionStatusIndex>(database, "TransactionStatusIndex");
analyze_column::<Rewards>(database, "Rewards");
analyze_column::<Blocktime>(database, "Blocktime");
analyze_column::<PerfSamples>(database, "PerfSamples");
analyze_column::<BlockHeight>(database, "BlockHeight");
analyze_column::<ProgramCosts>(database, "ProgramCosts");
analyze_column::<OptimisticSlots>(database, "OptimisticSlots");
}
fn raw_key_to_slot(key: &[u8], column_name: &str) -> Option<Slot> {
match column_name {
cf::SlotMeta::NAME => Some(cf::SlotMeta::slot(cf::SlotMeta::index(key))),
cf::Orphans::NAME => Some(cf::Orphans::slot(cf::Orphans::index(key))),
cf::DeadSlots::NAME => Some(cf::SlotMeta::slot(cf::SlotMeta::index(key))),
cf::DuplicateSlots::NAME => Some(cf::SlotMeta::slot(cf::SlotMeta::index(key))),
cf::ErasureMeta::NAME => Some(cf::ErasureMeta::slot(cf::ErasureMeta::index(key))),
cf::BankHash::NAME => Some(cf::BankHash::slot(cf::BankHash::index(key))),
cf::Root::NAME => Some(cf::Root::slot(cf::Root::index(key))),
cf::Index::NAME => Some(cf::Index::slot(cf::Index::index(key))),
cf::ShredData::NAME => Some(cf::ShredData::slot(cf::ShredData::index(key))),
cf::ShredCode::NAME => Some(cf::ShredCode::slot(cf::ShredCode::index(key))),
cf::TransactionStatus::NAME => Some(cf::TransactionStatus::slot(
cf::TransactionStatus::index(key),
)),
cf::AddressSignatures::NAME => Some(cf::AddressSignatures::slot(
cf::AddressSignatures::index(key),
)),
cf::TransactionMemos::NAME => None, // does not implement slot()
cf::TransactionStatusIndex::NAME => None, // does not implement slot()
cf::Rewards::NAME => Some(cf::Rewards::slot(cf::Rewards::index(key))),
cf::Blocktime::NAME => Some(cf::Blocktime::slot(cf::Blocktime::index(key))),
cf::PerfSamples::NAME => Some(cf::PerfSamples::slot(cf::PerfSamples::index(key))),
cf::BlockHeight::NAME => Some(cf::BlockHeight::slot(cf::BlockHeight::index(key))),
cf::ProgramCosts::NAME => None, // does not implement slot()
cf::OptimisticSlots::NAME => {
Some(cf::OptimisticSlots::slot(cf::OptimisticSlots::index(key)))
}
&_ => None,
}
}
fn print_blockstore_file_metadata(
blockstore: &Blockstore,
file_name: &Option<&str>,
) -> Result<(), String> {
let live_files = blockstore
.live_files_metadata()
.map_err(|err| format!("{err:?}"))?;
// All files under live_files_metadata are prefixed with "/".
let sst_file_name = file_name.as_ref().map(|name| format!("/{name}"));
for file in live_files {
if sst_file_name.is_none() || file.name.eq(sst_file_name.as_ref().unwrap()) {
println!(
"[{}] cf_name: {}, level: {}, start_slot: {:?}, end_slot: {:?}, size: {}, \
num_entries: {}",
file.name,
file.column_family_name,
file.level,
raw_key_to_slot(&file.start_key.unwrap(), &file.column_family_name),
raw_key_to_slot(&file.end_key.unwrap(), &file.column_family_name),
file.size,
file.num_entries,
);
if sst_file_name.is_some() {
return Ok(());
}
}
}
if sst_file_name.is_some() {
return Err(format!(
"Failed to find or load the metadata of the specified file {file_name:?}"
));
}
Ok(())
}
fn compute_slot_cost(blockstore: &Blockstore, slot: Slot) -> Result<(), String> {
if blockstore.is_dead(slot) {
return Err("Dead slot".to_string());
}
let (entries, _num_shreds, _is_full) = blockstore
.get_slot_entries_with_shred_info(slot, 0, false)
.map_err(|err| format!(" Slot: {slot}, Failed to load entries, err {err:?}"))?;
let num_entries = entries.len();
let mut num_transactions = 0;
let mut num_programs = 0;
let mut program_ids = HashMap::new();
let mut cost_tracker = CostTracker::default();
for entry in entries {
num_transactions += entry.transactions.len();
entry
.transactions
.into_iter()
.filter_map(|transaction| {
SanitizedTransaction::try_create(
transaction,
MessageHash::Compute,
None,
SimpleAddressLoader::Disabled,
)
.map_err(|err| {
warn!("Failed to compute cost of transaction: {:?}", err);
})
.ok()
})
.for_each(|transaction| {
num_programs += transaction.message().instructions().len();
let tx_cost = CostModel::calculate_cost(&transaction, &FeatureSet::all_enabled());
let result = cost_tracker.try_add(&tx_cost);
if result.is_err() {
println!(
"Slot: {slot}, CostModel rejected transaction {transaction:?}, reason \
{result:?}",
);
}
for (program_id, _instruction) in transaction.message().program_instructions_iter()
{
*program_ids.entry(*program_id).or_insert(0) += 1;
}
});
}
println!(
"Slot: {slot}, Entries: {num_entries}, Transactions: {num_transactions}, Programs \
{num_programs}",
);
println!(" Programs: {program_ids:?}");
Ok(())
}
/// Returns true if the supplied slot contains any nonvote transactions
fn slot_contains_nonvote_tx(blockstore: &Blockstore, slot: Slot) -> bool {
let (entries, _, _) = blockstore
.get_slot_entries_with_shred_info(slot, 0, false)
.expect("Failed to get slot entries");
let contains_nonvote = entries
.iter()
.flat_map(|entry| entry.transactions.iter())
.flat_map(get_program_ids)
.any(|program_id| *program_id != solana_vote_program::id());
contains_nonvote
}
type OptimisticSlotInfo = (Slot, Option<(Hash, UnixTimestamp)>, bool);
/// Return the latest `num_slots` optimistically confirmed slots, including
/// ancestors of optimistically confirmed slots that may not have been marked
/// as optimistically confirmed themselves.
fn get_latest_optimistic_slots(
blockstore: &Blockstore,
num_slots: usize,
exclude_vote_only_slots: bool,
) -> Vec<OptimisticSlotInfo> {
// Consider a chain X -> Y -> Z where X and Z have been optimistically
// confirmed. Given that Y is an ancestor of Z, Y can implicitly be
// considered as optimistically confirmed. However, there isn't an explicit
// guarantee that Y will be marked as optimistically confirmed in the
// blockstore.
//
// Because retrieving optimistically confirmed slots is an important part
// of cluster restarts, exercise caution in this function and manually walk
// the ancestors of the latest optimistically confirmed slot instead of
// solely relying on the contents of the optimistically confirmed column.
let Some(latest_slot) = blockstore