forked from solana-labs/solana
-
Notifications
You must be signed in to change notification settings - Fork 338
/
Copy pathcluster_info.rs
4400 lines (4150 loc) · 171 KB
/
cluster_info.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
//! The `cluster_info` module defines a data structure that is shared by all the nodes in the network over
//! a gossip control plane. The goal is to share small bits of off-chain information and detect and
//! repair partitions.
//!
//! This CRDT only supports a very limited set of types. A map of Pubkey -> Versioned Struct.
//! The last version is always picked during an update.
//!
//! The network is arranged in layers:
//!
//! * layer 0 - Leader.
//! * layer 1 - As many nodes as we can fit
//! * layer 2 - Everyone else, if layer 1 is `2^10`, layer 2 should be able to fit `2^20` number of nodes.
//!
//! Bank needs to provide an interface for us to query the stake weight
use {
crate::{
cluster_info_metrics::{
submit_gossip_stats, Counter, GossipStats, ScopedTimer, TimedGuard,
},
contact_info::{self, ContactInfo, ContactInfoQuery, Error as ContactInfoError},
crds::{Crds, Cursor, GossipRoute},
crds_data::{self, CrdsData, EpochSlotsIndex, LowestSlot, SnapshotHashes, Vote},
crds_gossip::CrdsGossip,
crds_gossip_error::CrdsGossipError,
crds_gossip_pull::{
get_max_bloom_filter_bytes, CrdsFilter, CrdsTimeouts, ProcessPullStats,
CRDS_GOSSIP_PULL_CRDS_TIMEOUT_MS,
},
crds_value::{CrdsValue, CrdsValueLabel},
duplicate_shred::DuplicateShred,
epoch_slots::EpochSlots,
epoch_specs::EpochSpecs,
gossip_error::GossipError,
ping_pong::Pong,
protocol::{
split_gossip_messages, Ping, PingCache, Protocol, PruneData,
DUPLICATE_SHRED_MAX_PAYLOAD_SIZE, MAX_INCREMENTAL_SNAPSHOT_HASHES,
MAX_PRUNE_DATA_NODES, PULL_RESPONSE_MIN_SERIALIZED_SIZE, PUSH_MESSAGE_MAX_PAYLOAD_SIZE,
},
restart_crds_values::{
RestartHeaviestFork, RestartLastVotedForkSlots, RestartLastVotedForkSlotsError,
},
weighted_shuffle::WeightedShuffle,
},
crossbeam_channel::{Receiver, RecvTimeoutError, Sender},
itertools::Itertools,
rand::{seq::SliceRandom, CryptoRng, Rng},
rayon::{prelude::*, ThreadPool, ThreadPoolBuilder},
solana_ledger::shred::Shred,
solana_measure::measure::Measure,
solana_net_utils::{
bind_common_in_range_with_config, bind_common_with_config, bind_in_range,
bind_in_range_with_config, bind_more_with_config, bind_to_localhost, bind_to_unspecified,
bind_two_in_range_with_offset_and_config, find_available_port_in_range,
multi_bind_in_range_with_config, PortRange, SocketConfig, VALIDATOR_PORT_RANGE,
},
solana_perf::{
data_budget::DataBudget,
packet::{Packet, PacketBatch, PacketBatchRecycler, PACKET_DATA_SIZE},
},
solana_rayon_threadlimit::get_thread_count,
solana_runtime::bank_forks::BankForks,
solana_sanitize::Sanitize,
solana_sdk::{
clock::{Slot, DEFAULT_MS_PER_SLOT, DEFAULT_SLOTS_PER_EPOCH},
hash::Hash,
pubkey::Pubkey,
quic::QUIC_PORT_OFFSET,
signature::{Keypair, Signable, Signature, Signer},
timing::timestamp,
transaction::Transaction,
},
solana_streamer::{
packet,
quic::DEFAULT_QUIC_ENDPOINTS,
socket::SocketAddrSpace,
streamer::{PacketBatchReceiver, PacketBatchSender},
},
solana_vote::vote_parser,
solana_vote_program::vote_state::MAX_LOCKOUT_HISTORY,
std::{
collections::{HashMap, HashSet, VecDeque},
fmt::Debug,
fs::{self, File},
io::{BufReader, BufWriter, Write},
iter::repeat,
net::{IpAddr, Ipv4Addr, SocketAddr, TcpListener, UdpSocket},
num::NonZeroUsize,
ops::{Deref, Div},
path::{Path, PathBuf},
result::Result,
sync::{
atomic::{AtomicBool, Ordering},
Arc, Mutex, RwLock, RwLockReadGuard,
},
thread::{sleep, Builder, JoinHandle},
time::{Duration, Instant},
},
thiserror::Error,
};
const DEFAULT_EPOCH_DURATION: Duration =
Duration::from_millis(DEFAULT_SLOTS_PER_EPOCH * DEFAULT_MS_PER_SLOT);
/// milliseconds we sleep for between gossip requests
pub const GOSSIP_SLEEP_MILLIS: u64 = 100;
/// A hard limit on incoming gossip messages
/// Chosen to be able to handle 1Gbps of pure gossip traffic
/// 128MB/PACKET_DATA_SIZE
const MAX_GOSSIP_TRAFFIC: usize = 128_000_000 / PACKET_DATA_SIZE;
const GOSSIP_PING_CACHE_CAPACITY: usize = 126976;
const GOSSIP_PING_CACHE_TTL: Duration = Duration::from_secs(1280);
const GOSSIP_PING_CACHE_RATE_LIMIT_DELAY: Duration = Duration::from_secs(1280 / 64);
pub const DEFAULT_CONTACT_DEBUG_INTERVAL_MILLIS: u64 = 10_000;
pub const DEFAULT_CONTACT_SAVE_INTERVAL_MILLIS: u64 = 60_000;
// Limit number of unique pubkeys in the crds table.
pub(crate) const CRDS_UNIQUE_PUBKEY_CAPACITY: usize = 8192;
/// Minimum stake that a node should have so that its CRDS values are
/// propagated through gossip (few types are exempted).
const MIN_STAKE_FOR_GOSSIP: u64 = solana_sdk::native_token::LAMPORTS_PER_SOL;
/// Minimum number of staked nodes for enforcing stakes in gossip.
const MIN_NUM_STAKED_NODES: usize = 500;
// Must have at least one socket to monitor the TVU port
// The unsafes are safe because we're using fixed, known non-zero values
pub const MINIMUM_NUM_TVU_SOCKETS: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(1) };
pub const DEFAULT_NUM_TVU_SOCKETS: NonZeroUsize = unsafe { NonZeroUsize::new_unchecked(8) };
#[derive(Debug, PartialEq, Eq, Error)]
pub enum ClusterInfoError {
#[error("NoPeers")]
NoPeers,
#[error("NoLeader")]
NoLeader,
#[error("BadContactInfo")]
BadContactInfo,
#[error("BadGossipAddress")]
BadGossipAddress,
#[error("TooManyIncrementalSnapshotHashes")]
TooManyIncrementalSnapshotHashes,
}
pub struct ClusterInfo {
/// The network
pub gossip: CrdsGossip,
/// set the keypair that will be used to sign crds values generated. It is unset only in tests.
keypair: RwLock<Arc<Keypair>>,
/// Network entrypoints
entrypoints: RwLock<Vec<ContactInfo>>,
outbound_budget: DataBudget,
my_contact_info: RwLock<ContactInfo>,
ping_cache: Mutex<PingCache>,
stats: GossipStats,
local_message_pending_push_queue: Mutex<Vec<CrdsValue>>,
contact_debug_interval: u64, // milliseconds, 0 = disabled
contact_save_interval: u64, // milliseconds, 0 = disabled
contact_info_path: PathBuf,
socket_addr_space: SocketAddrSpace,
}
struct PullData {
from_addr: SocketAddr,
caller: CrdsValue,
filter: CrdsFilter,
}
// Returns false if the CRDS value should be discarded.
#[inline]
#[must_use]
fn should_retain_crds_value(
value: &CrdsValue,
stakes: &HashMap<Pubkey, u64>,
drop_unstaked_node_instance: bool,
) -> bool {
match value.data() {
CrdsData::ContactInfo(_) => true,
CrdsData::LegacyContactInfo(_) => true,
// May Impact new validators starting up without any stake yet.
CrdsData::Vote(_, _) => true,
// Unstaked nodes can still help repair.
CrdsData::EpochSlots(_, _) => true,
// Unstaked nodes can still serve snapshots.
CrdsData::LegacySnapshotHashes(_) | CrdsData::SnapshotHashes(_) => true,
// Otherwise unstaked voting nodes will show up with no version in
// the various dashboards.
CrdsData::Version(_) => true,
CrdsData::AccountsHashes(_) => true,
CrdsData::NodeInstance(_) if !drop_unstaked_node_instance => true,
CrdsData::LowestSlot(_, _)
| CrdsData::LegacyVersion(_)
| CrdsData::DuplicateShred(_, _)
| CrdsData::RestartHeaviestFork(_)
| CrdsData::RestartLastVotedForkSlots(_)
| CrdsData::NodeInstance(_) => {
stakes.len() < MIN_NUM_STAKED_NODES || {
let stake = stakes.get(&value.pubkey()).copied();
stake.unwrap_or_default() >= MIN_STAKE_FOR_GOSSIP
}
}
}
}
impl ClusterInfo {
pub fn new(
contact_info: ContactInfo,
keypair: Arc<Keypair>,
socket_addr_space: SocketAddrSpace,
) -> Self {
assert_eq!(contact_info.pubkey(), &keypair.pubkey());
let me = Self {
gossip: CrdsGossip::default(),
keypair: RwLock::new(keypair),
entrypoints: RwLock::default(),
outbound_budget: DataBudget::default(),
my_contact_info: RwLock::new(contact_info),
ping_cache: Mutex::new(PingCache::new(
&mut rand::thread_rng(),
Instant::now(),
GOSSIP_PING_CACHE_TTL,
GOSSIP_PING_CACHE_RATE_LIMIT_DELAY,
GOSSIP_PING_CACHE_CAPACITY,
)),
stats: GossipStats::default(),
local_message_pending_push_queue: Mutex::default(),
contact_debug_interval: DEFAULT_CONTACT_DEBUG_INTERVAL_MILLIS,
contact_info_path: PathBuf::default(),
contact_save_interval: 0, // disabled
socket_addr_space,
};
me.refresh_my_gossip_contact_info();
me
}
pub fn set_contact_debug_interval(&mut self, new: u64) {
self.contact_debug_interval = new;
}
pub fn socket_addr_space(&self) -> &SocketAddrSpace {
&self.socket_addr_space
}
fn refresh_push_active_set(
&self,
recycler: &PacketBatchRecycler,
stakes: &HashMap<Pubkey, u64>,
gossip_validators: Option<&HashSet<Pubkey>>,
sender: &PacketBatchSender,
) {
let shred_version = self.my_contact_info.read().unwrap().shred_version();
let self_keypair: Arc<Keypair> = self.keypair().clone();
let mut pings = Vec::new();
self.gossip.refresh_push_active_set(
&self_keypair,
shred_version,
stakes,
gossip_validators,
&self.ping_cache,
&mut pings,
&self.socket_addr_space,
);
self.stats
.new_pull_requests_pings_count
.add_relaxed(pings.len() as u64);
let pings: Vec<_> = pings
.into_iter()
.map(|(addr, ping)| (addr, Protocol::PingMessage(ping)))
.collect();
if !pings.is_empty() {
self.stats
.packets_sent_gossip_requests_count
.add_relaxed(pings.len() as u64);
let packet_batch = PacketBatch::new_unpinned_with_recycler_data_and_dests(
recycler,
"refresh_push_active_set",
&pings,
);
let _ = sender.send(packet_batch);
}
}
// TODO kill insert_info, only used by tests
pub fn insert_info(&self, node: ContactInfo) {
let entry = CrdsValue::new(CrdsData::ContactInfo(node), &self.keypair());
if let Err(err) = {
let mut gossip_crds = self.gossip.crds.write().unwrap();
gossip_crds.insert(entry, timestamp(), GossipRoute::LocalMessage)
} {
error!("ClusterInfo.insert_info: {err:?}");
}
}
pub fn set_entrypoint(&self, entrypoint: ContactInfo) {
self.set_entrypoints(vec![entrypoint]);
}
pub fn set_entrypoints(&self, entrypoints: Vec<ContactInfo>) {
*self.entrypoints.write().unwrap() = entrypoints;
}
pub fn save_contact_info(&self) {
let _st = ScopedTimer::from(&self.stats.save_contact_info_time);
let nodes = {
let entrypoint_gossip_addrs = self
.entrypoints
.read()
.unwrap()
.iter()
.filter_map(ContactInfo::gossip)
.collect::<HashSet<_>>();
let self_pubkey = self.id();
let gossip_crds = self.gossip.crds.read().unwrap();
gossip_crds
.get_nodes()
.filter_map(|v| {
// Don't save:
// 1. Our ContactInfo. No point
// 2. Entrypoint ContactInfo. This will avoid adopting the incorrect shred
// version on restart if the entrypoint shred version changes. Also
// there's not much point in saving entrypoint ContactInfo since by
// definition that information is already available
let contact_info = v.value.contact_info().unwrap();
if contact_info.pubkey() != &self_pubkey
&& contact_info
.gossip()
.map(|addr| !entrypoint_gossip_addrs.contains(&addr))
.unwrap_or_default()
{
return Some(v.value.clone());
}
None
})
.collect::<Vec<_>>()
};
if nodes.is_empty() {
return;
}
let filename = self.contact_info_path.join("contact-info.bin");
let tmp_filename = &filename.with_extension("tmp");
match File::create(tmp_filename) {
Ok(file) => {
let mut writer = BufWriter::new(file);
if let Err(err) = bincode::serialize_into(&mut writer, &nodes) {
warn!(
"Failed to serialize contact info info {}: {}",
tmp_filename.display(),
err
);
return;
}
if let Err(err) = writer.flush() {
warn!("Failed to save contact info: {err}");
}
}
Err(err) => {
warn!("Failed to create {}: {}", tmp_filename.display(), err);
return;
}
}
match fs::rename(tmp_filename, &filename) {
Ok(()) => {
info!(
"Saved contact info for {} nodes into {}",
nodes.len(),
filename.display()
);
}
Err(err) => {
warn!(
"Failed to rename {} to {}: {}",
tmp_filename.display(),
filename.display(),
err
);
}
}
}
pub fn restore_contact_info(&mut self, contact_info_path: &Path, contact_save_interval: u64) {
self.contact_info_path = contact_info_path.into();
self.contact_save_interval = contact_save_interval;
let filename = contact_info_path.join("contact-info.bin");
if !filename.exists() {
return;
}
let nodes: Vec<CrdsValue> = match File::open(&filename) {
Ok(file) => {
bincode::deserialize_from(&mut BufReader::new(file)).unwrap_or_else(|err| {
warn!("Failed to deserialize {}: {}", filename.display(), err);
vec![]
})
}
Err(err) => {
warn!("Failed to open {}: {}", filename.display(), err);
vec![]
}
};
info!(
"Loaded contact info for {} nodes from {}",
nodes.len(),
filename.display()
);
let now = timestamp();
let mut gossip_crds = self.gossip.crds.write().unwrap();
for node in nodes {
if let Err(err) = gossip_crds.insert(node, now, GossipRoute::LocalMessage) {
warn!("crds insert failed {:?}", err);
}
}
}
pub fn id(&self) -> Pubkey {
self.keypair.read().unwrap().pubkey()
}
pub fn keypair(&self) -> RwLockReadGuard<Arc<Keypair>> {
self.keypair.read().unwrap()
}
pub fn set_keypair(&self, new_keypair: Arc<Keypair>) {
let id = new_keypair.pubkey();
*self.keypair.write().unwrap() = new_keypair;
self.my_contact_info.write().unwrap().hot_swap_pubkey(id);
self.refresh_my_gossip_contact_info();
}
pub fn set_tpu(&self, tpu_addr: SocketAddr) -> Result<(), ContactInfoError> {
self.my_contact_info.write().unwrap().set_tpu(tpu_addr)?;
self.refresh_my_gossip_contact_info();
Ok(())
}
pub fn set_tpu_forwards(&self, tpu_forwards_addr: SocketAddr) -> Result<(), ContactInfoError> {
self.my_contact_info
.write()
.unwrap()
.set_tpu_forwards(tpu_forwards_addr)?;
self.refresh_my_gossip_contact_info();
Ok(())
}
pub fn lookup_contact_info<R>(
&self,
id: &Pubkey,
query: impl ContactInfoQuery<R>,
) -> Option<R> {
let gossip_crds = self.gossip.crds.read().unwrap();
gossip_crds.get(*id).map(query)
}
pub fn lookup_contact_info_by_gossip_addr(
&self,
gossip_addr: &SocketAddr,
) -> Option<ContactInfo> {
let gossip_crds = self.gossip.crds.read().unwrap();
let mut nodes = gossip_crds.get_nodes_contact_info();
nodes
.find(|node| node.gossip() == Some(*gossip_addr))
.cloned()
}
pub fn my_contact_info(&self) -> ContactInfo {
self.my_contact_info.read().unwrap().clone()
}
pub fn my_shred_version(&self) -> u16 {
self.my_contact_info.read().unwrap().shred_version()
}
fn lookup_epoch_slots(&self, ix: EpochSlotsIndex) -> EpochSlots {
let self_pubkey = self.id();
let label = CrdsValueLabel::EpochSlots(ix, self_pubkey);
let gossip_crds = self.gossip.crds.read().unwrap();
gossip_crds
.get::<&CrdsValue>(&label)
.and_then(|v| v.epoch_slots())
.cloned()
.unwrap_or_else(|| EpochSlots::new(self_pubkey, timestamp()))
}
fn addr_to_string(&self, default_ip: &Option<IpAddr>, addr: &Option<SocketAddr>) -> String {
addr.filter(|addr| self.socket_addr_space.check(addr))
.map(|addr| {
if &Some(addr.ip()) == default_ip {
addr.port().to_string()
} else {
addr.to_string()
}
})
.unwrap_or_else(|| String::from("none"))
}
pub fn rpc_info_trace(&self) -> String {
let now = timestamp();
let my_pubkey = self.id();
let my_shred_version = self.my_shred_version();
let nodes: Vec<_> = self
.all_peers()
.into_iter()
.filter_map(|(node, last_updated)| {
let node_rpc = node
.rpc()
.filter(|addr| self.socket_addr_space.check(addr))?;
let node_version = self.get_node_version(node.pubkey());
if my_shred_version != 0
&& (node.shred_version() != 0 && node.shred_version() != my_shred_version)
{
return None;
}
let rpc_addr = node_rpc.ip();
Some(format!(
"{:15} {:2}| {:5} | {:44} |{:^9}| {:5}| {:5}| {}\n",
rpc_addr.to_string(),
if node.pubkey() == &my_pubkey {
"me"
} else {
""
},
now.saturating_sub(last_updated),
node.pubkey().to_string(),
if let Some(node_version) = node_version {
node_version.to_string()
} else {
"-".to_string()
},
self.addr_to_string(&Some(rpc_addr), &node.rpc()),
self.addr_to_string(&Some(rpc_addr), &node.rpc_pubsub()),
node.shred_version(),
))
})
.collect();
format!(
"RPC Address |Age(ms)| Node identifier \
| Version | RPC |PubSub|ShredVer\n\
------------------+-------+----------------------------------------------\
+---------+------+------+--------\n\
{}\
RPC Enabled Nodes: {}",
nodes.join(""),
nodes.len(),
)
}
pub fn contact_info_trace(&self) -> String {
let now = timestamp();
let mut shred_spy_nodes = 0usize;
let mut total_spy_nodes = 0usize;
let mut different_shred_nodes = 0usize;
let my_pubkey = self.id();
let my_shred_version = self.my_shred_version();
let nodes: Vec<_> = self
.all_peers()
.into_iter()
.filter_map(|(node, last_updated)| {
let is_spy_node = Self::is_spy_node(&node, &self.socket_addr_space);
if is_spy_node {
total_spy_nodes = total_spy_nodes.saturating_add(1);
}
let node_version = self.get_node_version(node.pubkey());
if my_shred_version != 0 && (node.shred_version() != 0 && node.shred_version() != my_shred_version) {
different_shred_nodes = different_shred_nodes.saturating_add(1);
None
} else {
if is_spy_node {
shred_spy_nodes = shred_spy_nodes.saturating_add(1);
}
let ip_addr = node.gossip().as_ref().map(SocketAddr::ip);
Some(format!(
"{:15} {:2}| {:5} | {:44} |{:^9}| {:5}| {:5}| {:5}| {:5}| {:5}| {:5}| {:5}| {}\n",
node.gossip()
.filter(|addr| self.socket_addr_space.check(addr))
.as_ref()
.map(SocketAddr::ip)
.as_ref()
.map(IpAddr::to_string)
.unwrap_or_else(|| String::from("none")),
if node.pubkey() == &my_pubkey { "me" } else { "" },
now.saturating_sub(last_updated),
node.pubkey().to_string(),
if let Some(node_version) = node_version {
node_version.to_string()
} else {
"-".to_string()
},
self.addr_to_string(&ip_addr, &node.gossip()),
self.addr_to_string(&ip_addr, &node.tpu_vote(contact_info::Protocol::UDP)),
self.addr_to_string(&ip_addr, &node.tpu(contact_info::Protocol::UDP)),
self.addr_to_string(&ip_addr, &node.tpu_forwards(contact_info::Protocol::UDP)),
self.addr_to_string(&ip_addr, &node.tvu(contact_info::Protocol::UDP)),
self.addr_to_string(&ip_addr, &node.tvu(contact_info::Protocol::QUIC)),
self.addr_to_string(&ip_addr, &node.serve_repair(contact_info::Protocol::UDP)),
node.shred_version(),
))
}
})
.collect();
format!(
"IP Address |Age(ms)| Node identifier \
| Version |Gossip|TPUvote| TPU |TPUfwd| TVU |TVU Q |ServeR|ShredVer\n\
------------------+-------+----------------------------------------------\
+---------+------+-------+------+------+------+------+------+--------\n\
{}\
Nodes: {}{}{}",
nodes.join(""),
nodes.len().saturating_sub(shred_spy_nodes),
if total_spy_nodes > 0 {
format!("\nSpies: {total_spy_nodes}")
} else {
"".to_string()
},
if different_shred_nodes > 0 {
format!("\nNodes with different shred version: {different_shred_nodes}")
} else {
"".to_string()
}
)
}
// TODO: This has a race condition if called from more than one thread.
pub fn push_lowest_slot(&self, min: Slot) {
let self_pubkey = self.id();
let last = {
let gossip_crds = self.gossip.crds.read().unwrap();
gossip_crds
.get::<&LowestSlot>(self_pubkey)
.map(|x| x.lowest)
.unwrap_or_default()
};
if min > last {
let now = timestamp();
let entry = CrdsValue::new(
CrdsData::LowestSlot(0, LowestSlot::new(self_pubkey, min, now)),
&self.keypair(),
);
self.push_message(entry);
}
}
// TODO: If two threads call into this function then epoch_slot_index has a
// race condition and the threads will overwrite each other in crds table.
pub fn push_epoch_slots(&self, mut update: &[Slot]) {
let self_pubkey = self.id();
let current_slots: Vec<_> = {
let gossip_crds =
self.time_gossip_read_lock("lookup_epoch_slots", &self.stats.epoch_slots_lookup);
(0..crds_data::MAX_EPOCH_SLOTS)
.filter_map(|ix| {
let label = CrdsValueLabel::EpochSlots(ix, self_pubkey);
let crds_value = gossip_crds.get::<&CrdsValue>(&label)?;
let epoch_slots = crds_value.epoch_slots()?;
let first_slot = epoch_slots.first_slot()?;
Some((epoch_slots.wallclock, first_slot, ix))
})
.collect()
};
let min_slot: Slot = current_slots
.iter()
.map(|(_wallclock, slot, _index)| *slot)
.min()
.unwrap_or_default();
let max_slot: Slot = update.iter().max().cloned().unwrap_or(0);
let total_slots = max_slot as isize - min_slot as isize;
// WARN if CRDS is not storing at least a full epoch worth of slots
if DEFAULT_SLOTS_PER_EPOCH as isize > total_slots
&& crds_data::MAX_EPOCH_SLOTS as usize <= current_slots.len()
{
self.stats.epoch_slots_filled.add_relaxed(1);
warn!(
"EPOCH_SLOTS are filling up FAST {}/{}",
total_slots,
current_slots.len()
);
}
let mut reset = false;
let mut epoch_slot_index = match current_slots.iter().max() {
Some((_wallclock, _slot, index)) => *index,
None => 0,
};
let mut entries = Vec::default();
let keypair = self.keypair();
while !update.is_empty() {
let ix = epoch_slot_index % crds_data::MAX_EPOCH_SLOTS;
let now = timestamp();
let mut slots = if !reset {
self.lookup_epoch_slots(ix)
} else {
EpochSlots::new(self_pubkey, now)
};
let n = slots.fill(update, now);
update = &update[n..];
if n > 0 {
let epoch_slots = CrdsData::EpochSlots(ix, slots);
let entry = CrdsValue::new(epoch_slots, &keypair);
entries.push(entry);
}
epoch_slot_index += 1;
reset = true;
}
let mut gossip_crds = self.gossip.crds.write().unwrap();
let now = timestamp();
for entry in entries {
if let Err(err) = gossip_crds.insert(entry, now, GossipRoute::LocalMessage) {
error!("push_epoch_slots failed: {:?}", err);
}
}
}
pub fn push_restart_last_voted_fork_slots(
&self,
fork: &[Slot],
last_vote_bankhash: Hash,
) -> Result<(), RestartLastVotedForkSlotsError> {
let now = timestamp();
let last_voted_fork_slots = RestartLastVotedForkSlots::new(
self.id(),
now,
fork,
last_vote_bankhash,
self.my_shred_version(),
)?;
self.push_message(CrdsValue::new(
CrdsData::RestartLastVotedForkSlots(last_voted_fork_slots),
&self.keypair(),
));
Ok(())
}
pub fn push_restart_heaviest_fork(
&self,
last_slot: Slot,
last_slot_hash: Hash,
observed_stake: u64,
) {
let restart_heaviest_fork = RestartHeaviestFork {
from: self.id(),
wallclock: timestamp(),
last_slot,
last_slot_hash,
observed_stake,
shred_version: self.my_shred_version(),
};
self.push_message(CrdsValue::new(
CrdsData::RestartHeaviestFork(restart_heaviest_fork),
&self.keypair(),
));
}
fn time_gossip_read_lock<'a>(
&'a self,
label: &'static str,
counter: &'a Counter,
) -> TimedGuard<'a, RwLockReadGuard<'a, Crds>> {
TimedGuard::new(self.gossip.crds.read().unwrap(), label, counter)
}
fn push_message(&self, message: CrdsValue) {
self.local_message_pending_push_queue
.lock()
.unwrap()
.push(message);
}
pub fn push_snapshot_hashes(
&self,
full: (Slot, Hash),
incremental: Vec<(Slot, Hash)>,
) -> Result<(), ClusterInfoError> {
if incremental.len() > MAX_INCREMENTAL_SNAPSHOT_HASHES {
return Err(ClusterInfoError::TooManyIncrementalSnapshotHashes);
}
let message = CrdsData::SnapshotHashes(SnapshotHashes {
from: self.id(),
full,
incremental,
wallclock: timestamp(),
});
self.push_message(CrdsValue::new(message, &self.keypair()));
Ok(())
}
pub fn push_vote_at_index(&self, vote: Transaction, vote_index: u8) {
assert!((vote_index as usize) < MAX_LOCKOUT_HISTORY);
let self_pubkey = self.id();
let now = timestamp();
let vote = Vote::new(self_pubkey, vote, now).unwrap();
let vote = CrdsData::Vote(vote_index, vote);
let vote = CrdsValue::new(vote, &self.keypair());
let mut gossip_crds = self.gossip.crds.write().unwrap();
if let Err(err) = gossip_crds.insert(vote, now, GossipRoute::LocalMessage) {
error!("push_vote failed: {:?}", err);
}
}
/// If there are less than `MAX_LOCKOUT_HISTORY` votes present, returns the next index
/// without a vote. If there are `MAX_LOCKOUT_HISTORY` votes:
/// - Finds the oldest wallclock vote and returns its index
/// - Otherwise returns the total amount of observed votes
///
/// If there exists a newer vote in gossip than `new_vote_slot` return `None` as this indicates
/// that we might be submitting slashable votes after an improper restart
fn find_vote_index_to_evict(&self, new_vote_slot: Slot) -> Option<u8> {
let self_pubkey = self.id();
let mut num_crds_votes = 0;
let mut exists_newer_vote = false;
let vote_index = {
let gossip_crds =
self.time_gossip_read_lock("gossip_read_push_vote", &self.stats.push_vote_read);
(0..MAX_LOCKOUT_HISTORY as u8)
.filter_map(|ix| {
let vote = CrdsValueLabel::Vote(ix, self_pubkey);
let vote: &CrdsData = gossip_crds.get(&vote)?;
num_crds_votes += 1;
match &vote {
CrdsData::Vote(_, vote) if vote.slot() < Some(new_vote_slot) => {
Some((vote.wallclock, ix))
}
CrdsData::Vote(_, _) => {
exists_newer_vote = true;
None
}
_ => panic!("this should not happen!"),
}
})
.min() // Boot the oldest evicted vote by wallclock.
.map(|(_ /*wallclock*/, ix)| ix)
};
if exists_newer_vote {
return None;
}
if num_crds_votes < MAX_LOCKOUT_HISTORY as u8 {
// Do not evict if there is space in crds
Some(num_crds_votes)
} else {
vote_index
}
}
pub fn push_vote(&self, tower: &[Slot], vote: Transaction) {
debug_assert!(tower.iter().tuple_windows().all(|(a, b)| a < b));
// Find the oldest crds vote by wallclock that has a lower slot than `tower`
// and recycle its vote-index. If the crds buffer is not full we instead add a new vote-index.
let Some(vote_index) =
self.find_vote_index_to_evict(tower.last().copied().expect("Cannot push empty vote"))
else {
// In this case we have restarted with a mangled/missing tower and are attempting
// to push an old vote. This could be a slashable offense so better to panic here.
let (_, vote, hash, _) = vote_parser::parse_vote_transaction(&vote).unwrap();
panic!(
"Submitting old vote, switch: {}, vote slots: {:?}, tower: {:?}",
hash.is_some(),
vote.slots(),
tower
);
};
debug_assert!(vote_index < MAX_LOCKOUT_HISTORY as u8);
self.push_vote_at_index(vote, vote_index);
}
pub fn refresh_vote(&self, refresh_vote: Transaction, refresh_vote_slot: Slot) {
let vote_index = {
let self_pubkey = self.id();
let gossip_crds =
self.time_gossip_read_lock("gossip_read_push_vote", &self.stats.push_vote_read);
(0..MAX_LOCKOUT_HISTORY as u8).find(|ix| {
let vote = CrdsValueLabel::Vote(*ix, self_pubkey);
let Some(vote) = gossip_crds.get::<&CrdsData>(&vote) else {
return false;
};
let CrdsData::Vote(_, prev_vote) = &vote else {
panic!("this should not happen!");
};
match prev_vote.slot() {
Some(prev_vote_slot) => prev_vote_slot == refresh_vote_slot,
None => {
error!("crds vote with no slots!");
false
}
}
})
};
// We don't write to an arbitrary index, because it may replace one of this validator's
// existing votes on the network.
if let Some(vote_index) = vote_index {
self.push_vote_at_index(refresh_vote, vote_index);
} else {
// If you don't see a vote with the same slot yet, this means you probably
// restarted, and need to repush and evict the oldest vote
let Some(vote_index) = self.find_vote_index_to_evict(refresh_vote_slot) else {
warn!(
"trying to refresh slot {} but all votes in gossip table are for newer slots",
refresh_vote_slot,
);
return;
};
debug_assert!(vote_index < MAX_LOCKOUT_HISTORY as u8);
self.push_vote_at_index(refresh_vote, vote_index);
}
}
/// Returns votes inserted since the given cursor.
pub fn get_votes(&self, cursor: &mut Cursor) -> Vec<Transaction> {
let txs: Vec<Transaction> = self
.time_gossip_read_lock("get_votes", &self.stats.get_votes)
.get_votes(cursor)
.map(|vote| {
let CrdsData::Vote(_, vote) = vote.value.data() else {
panic!("this should not happen!");
};
vote.transaction().clone()
})
.collect();
self.stats.get_votes_count.add_relaxed(txs.len() as u64);
txs
}
/// Returns votes and the associated labels inserted since the given cursor.
pub fn get_votes_with_labels(
&self,
cursor: &mut Cursor,
) -> (Vec<CrdsValueLabel>, Vec<Transaction>) {
let (labels, txs): (_, Vec<_>) = self
.time_gossip_read_lock("get_votes", &self.stats.get_votes)
.get_votes(cursor)
.map(|vote| {
let label = vote.value.label();
let CrdsData::Vote(_, vote) = vote.value.data() else {
panic!("this should not happen!");
};
(label, vote.transaction().clone())
})
.unzip();
self.stats.get_votes_count.add_relaxed(txs.len() as u64);
(labels, txs)
}
pub fn push_duplicate_shred(
&self,
shred: &Shred,
other_payload: &[u8],
) -> Result<(), GossipError> {
self.gossip.push_duplicate_shred(
&self.keypair(),
shred,
other_payload,
None::<fn(Slot) -> Option<Pubkey>>, // Leader schedule
DUPLICATE_SHRED_MAX_PAYLOAD_SIZE,
self.my_shred_version(),
)?;
Ok(())
}
pub fn get_snapshot_hashes_for_node(&self, pubkey: &Pubkey) -> Option<SnapshotHashes> {
self.gossip
.crds
.read()
.unwrap()
.get::<&SnapshotHashes>(*pubkey)
.cloned()
}
/// Returns epoch-slots inserted since the given cursor.
/// Excludes entries from nodes with unknown or different shred version.
pub fn get_epoch_slots(&self, cursor: &mut Cursor) -> Vec<EpochSlots> {
let self_shred_version = Some(self.my_shred_version());
let gossip_crds = self.gossip.crds.read().unwrap();
gossip_crds
.get_epoch_slots(cursor)
.filter(|entry| {
let origin = entry.value.pubkey();
gossip_crds.get_shred_version(&origin) == self_shred_version
})
.map(|entry| match entry.value.data() {
CrdsData::EpochSlots(_, slots) => slots.clone(),
_ => panic!("this should not happen!"),
})
.collect()
}
pub fn get_restart_last_voted_fork_slots(
&self,
cursor: &mut Cursor,
) -> Vec<RestartLastVotedForkSlots> {
let self_shred_version = self.my_shred_version();
let gossip_crds = self.gossip.crds.read().unwrap();
gossip_crds
.get_entries(cursor)
.filter_map(|entry| {