-
Notifications
You must be signed in to change notification settings - Fork 745
/
peerdb.rs
2029 lines (1820 loc) · 78.1 KB
/
peerdb.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::{metrics, multiaddr::Multiaddr, types::Subnet, Enr, Gossipsub, PeerId};
use peer_info::{ConnectionDirection, PeerConnectionStatus, PeerInfo};
use rand::seq::SliceRandom;
use score::{PeerAction, ReportSource, Score, ScoreState};
use slog::{crit, debug, error, trace, warn};
use std::net::IpAddr;
use std::time::Instant;
use std::{cmp::Ordering, fmt::Display};
use std::{
collections::{HashMap, HashSet},
fmt::Formatter,
};
use sync_status::SyncStatus;
use types::EthSpec;
pub mod client;
pub mod peer_info;
pub mod score;
pub mod sync_status;
/// Max number of disconnected nodes to remember.
const MAX_DC_PEERS: usize = 500;
/// The maximum number of banned nodes to remember.
pub const MAX_BANNED_PEERS: usize = 1000;
/// We ban an IP if there are more than `BANNED_PEERS_PER_IP_THRESHOLD` banned peers with this IP.
const BANNED_PEERS_PER_IP_THRESHOLD: usize = 5;
/// Relative factor of peers that are allowed to have a negative gossipsub score without penalizing
/// them in lighthouse.
const ALLOWED_NEGATIVE_GOSSIPSUB_FACTOR: f32 = 0.1;
/// The time we allow peers to be in the dialing state in our PeerDb before we revert them to a
/// disconnected state.
const DIAL_TIMEOUT: u64 = 15;
/// Storage of known peers, their reputation and information
pub struct PeerDB<TSpec: EthSpec> {
/// The collection of known connected peers, their status and reputation
peers: HashMap<PeerId, PeerInfo<TSpec>>,
/// The number of disconnected nodes in the database.
disconnected_peers: usize,
/// Counts banned peers in total and per ip
banned_peers_count: BannedPeersCount,
/// Specifies if peer scoring is disabled.
disable_peer_scoring: bool,
/// PeerDB's logger
log: slog::Logger,
}
impl<TSpec: EthSpec> PeerDB<TSpec> {
pub fn new(trusted_peers: Vec<PeerId>, disable_peer_scoring: bool, log: &slog::Logger) -> Self {
// Initialize the peers hashmap with trusted peers
let peers = trusted_peers
.into_iter()
.map(|peer_id| (peer_id, PeerInfo::trusted_peer_info()))
.collect();
Self {
log: log.clone(),
disconnected_peers: 0,
banned_peers_count: BannedPeersCount::default(),
disable_peer_scoring,
peers,
}
}
/* Getters */
/// Gives the score of a peer, or default score if it is unknown.
pub fn score(&self, peer_id: &PeerId) -> f64 {
self.peers
.get(peer_id)
.map_or(&Score::default(), |info| info.score())
.score()
}
/// Returns an iterator over all peers in the db.
pub fn peers(&self) -> impl Iterator<Item = (&PeerId, &PeerInfo<TSpec>)> {
self.peers.iter()
}
/// Gives the ids of all known peers.
pub fn peer_ids(&self) -> impl Iterator<Item = &PeerId> {
self.peers.keys()
}
/// Returns a peer's info, if known.
pub fn peer_info(&self, peer_id: &PeerId) -> Option<&PeerInfo<TSpec>> {
self.peers.get(peer_id)
}
/// Returns a mutable reference to a peer's info if known.
// VISIBILITY: The peer manager is able to modify some elements of the peer info, such as sync
// status.
pub(super) fn peer_info_mut(&mut self, peer_id: &PeerId) -> Option<&mut PeerInfo<TSpec>> {
self.peers.get_mut(peer_id)
}
/// Returns if the peer is already connected.
pub fn is_connected(&self, peer_id: &PeerId) -> bool {
matches!(
self.connection_status(peer_id),
Some(PeerConnectionStatus::Connected { .. })
)
}
/// If we are connected or currently dialing the peer returns true.
pub fn is_connected_or_dialing(&self, peer_id: &PeerId) -> bool {
matches!(
self.connection_status(peer_id),
Some(PeerConnectionStatus::Connected { .. })
| Some(PeerConnectionStatus::Dialing { .. })
)
}
/// If we are connected or in the process of disconnecting
pub fn is_connected_or_disconnecting(&self, peer_id: &PeerId) -> bool {
matches!(
self.connection_status(peer_id),
Some(PeerConnectionStatus::Connected { .. })
| Some(PeerConnectionStatus::Disconnecting { .. })
)
}
/// Returns true if the peer should be dialed. This checks the connection state and the
/// score state and determines if the peer manager should dial this peer.
pub fn should_dial(&self, peer_id: &PeerId) -> bool {
matches!(
self.connection_status(peer_id),
Some(PeerConnectionStatus::Disconnected { .. })
| Some(PeerConnectionStatus::Unknown { .. })
| None
) && !self.score_state_banned_or_disconnected(peer_id)
}
/// Returns true if the peer is synced at least to our current head.
pub fn is_synced(&self, peer_id: &PeerId) -> bool {
match self.peers.get(peer_id).map(|info| info.sync_status()) {
Some(SyncStatus::Synced { .. }) => true,
Some(_) => false,
None => false,
}
}
/// Returns the current [`BanResult`] of the peer if banned. This doesn't check the connection state, rather the
/// underlying score of the peer. A peer may be banned but still in the connected state
/// temporarily.
///
/// This is used to determine if we should accept incoming connections or not.
pub fn ban_status(&self, peer_id: &PeerId) -> Option<BanResult> {
self.peers
.get(peer_id)
.and_then(|peer| match peer.score_state() {
ScoreState::Banned => Some(BanResult::BadScore),
_ => self.ip_is_banned(peer).map(BanResult::BannedIp),
})
}
/// Checks if the peer's known addresses are currently banned.
fn ip_is_banned(&self, peer: &PeerInfo<TSpec>) -> Option<IpAddr> {
peer.seen_ip_addresses()
.find(|ip| self.banned_peers_count.ip_is_banned(ip))
}
/// Returns true if the IP is banned.
pub fn is_ip_banned(&self, ip: &IpAddr) -> bool {
self.banned_peers_count.ip_is_banned(ip)
}
/// Returns true if the Peer is either banned or in the disconnected state.
fn score_state_banned_or_disconnected(&self, peer_id: &PeerId) -> bool {
if let Some(peer) = self.peers.get(peer_id) {
match peer.score_state() {
ScoreState::Banned | ScoreState::ForcedDisconnect => true,
_ => self.ip_is_banned(peer).is_some(),
}
} else {
false
}
}
/// Gives the ids and info of all known connected peers.
pub fn connected_peers(&self) -> impl Iterator<Item = (&PeerId, &PeerInfo<TSpec>)> {
self.peers.iter().filter(|(_, info)| info.is_connected())
}
/// Gives the ids of all known connected peers.
pub fn connected_peer_ids(&self) -> impl Iterator<Item = &PeerId> {
self.peers
.iter()
.filter(|(_, info)| info.is_connected())
.map(|(peer_id, _)| peer_id)
}
/// Connected or dialing peers
pub fn connected_or_dialing_peers(&self) -> impl Iterator<Item = &PeerId> {
self.peers
.iter()
.filter(|(_, info)| info.is_connected() || info.is_dialing())
.map(|(peer_id, _)| peer_id)
}
/// Connected outbound-only peers
pub fn connected_outbound_only_peers(&self) -> impl Iterator<Item = &PeerId> {
self.peers
.iter()
.filter(|(_, info)| info.is_outbound_only())
.map(|(peer_id, _)| peer_id)
}
/// Gives the `peer_id` of all known connected and synced peers.
pub fn synced_peers(&self) -> impl Iterator<Item = &PeerId> {
self.peers
.iter()
.filter(|(_, info)| {
if info.sync_status().is_synced() || info.sync_status().is_advanced() {
return info.is_connected();
}
false
})
.map(|(peer_id, _)| peer_id)
}
/// Gives the `peer_id` of all known connected and advanced peers.
pub fn advanced_peers(&self) -> impl Iterator<Item = &PeerId> {
self.peers
.iter()
.filter(|(_, info)| {
if info.sync_status().is_advanced() {
return info.is_connected();
}
false
})
.map(|(peer_id, _)| peer_id)
}
/// Gives an iterator of all peers on a given subnet.
pub fn good_peers_on_subnet(&self, subnet: Subnet) -> impl Iterator<Item = &PeerId> {
self.peers
.iter()
.filter(move |(_, info)| {
// We check both the metadata and gossipsub data as we only want to count long-lived subscribed peers
info.is_connected()
&& info.on_subnet_metadata(&subnet)
&& info.on_subnet_gossipsub(&subnet)
&& info.is_good_gossipsub_peer()
})
.map(|(peer_id, _)| peer_id)
}
/// Gives the ids of all known disconnected peers.
pub fn disconnected_peers(&self) -> impl Iterator<Item = &PeerId> {
self.peers
.iter()
.filter(|(_, info)| info.is_disconnected())
.map(|(peer_id, _)| peer_id)
}
/// Returns the ids of all known banned peers.
pub fn banned_peers(&self) -> impl Iterator<Item = &PeerId> {
self.peers
.iter()
.filter(|(_, info)| info.is_banned())
.map(|(peer_id, _)| peer_id)
}
/// Gives the ids of all known banned peers.
pub fn banned_peers_by_score(&self) -> impl Iterator<Item = &PeerId> {
self.peers
.iter()
.filter(|(_, info)| info.score_is_banned())
.map(|(peer_id, _)| peer_id)
}
/// Returns a vector of all connected peers sorted by score beginning with the worst scores.
/// Ties get broken randomly.
pub fn worst_connected_peers(&self) -> Vec<(&PeerId, &PeerInfo<TSpec>)> {
let mut connected = self
.peers
.iter()
.filter(|(_, info)| info.is_connected())
.collect::<Vec<_>>();
connected.shuffle(&mut rand::thread_rng());
connected.sort_by_key(|(_, info)| info.score());
connected
}
/// Returns a vector containing peers (their ids and info), sorted by
/// score from highest to lowest, and filtered using `is_status`
pub fn best_peers_by_status<F>(&self, is_status: F) -> Vec<(&PeerId, &PeerInfo<TSpec>)>
where
F: Fn(&PeerInfo<TSpec>) -> bool,
{
let mut by_status = self
.peers
.iter()
.filter(|(_, info)| is_status(info))
.collect::<Vec<_>>();
by_status.sort_by_key(|(_, info)| info.score());
by_status.into_iter().rev().collect()
}
/// Returns the peer with highest reputation that satisfies `is_status`
pub fn best_by_status<F>(&self, is_status: F) -> Option<&PeerId>
where
F: Fn(&PeerInfo<TSpec>) -> bool,
{
self.peers
.iter()
.filter(|(_, info)| is_status(info))
.max_by_key(|(_, info)| info.score())
.map(|(id, _)| id)
}
/// Returns the peer's connection status. Returns unknown if the peer is not in the DB.
pub fn connection_status(&self, peer_id: &PeerId) -> Option<PeerConnectionStatus> {
self.peer_info(peer_id)
.map(|info| info.connection_status().clone())
}
/* Mutability */
/// Cleans up the connection state of dialing peers.
// Libp2p dial's peerids, but sometimes the response is from another peer-id or libp2p
// returns dial errors without a peer-id attached. This function reverts peers that have a
// dialing status longer than DIAL_TIMEOUT seconds to a disconnected status. This is important because
// we count the number of dialing peers in our inbound connections.
pub fn cleanup_dialing_peers(&mut self) {
let peers_to_disconnect: Vec<_> = self
.peers
.iter()
.filter_map(|(peer_id, info)| {
if let PeerConnectionStatus::Dialing { since } = info.connection_status() {
if (*since) + std::time::Duration::from_secs(DIAL_TIMEOUT)
< std::time::Instant::now()
{
return Some(*peer_id);
}
}
None
})
.collect();
for peer_id in peers_to_disconnect {
self.update_connection_state(&peer_id, NewConnectionState::Disconnected);
}
}
/// Allows the sync module to update sync status' of peers. Returns None, if the peer doesn't
/// exist and returns Some(bool) representing if the sync state was modified.
pub fn update_sync_status(
&mut self,
peer_id: &PeerId,
sync_status: SyncStatus,
) -> Option<bool> {
let info = self.peers.get_mut(peer_id)?;
Some(info.update_sync_status(sync_status))
}
/// Updates the scores of known peers according to their connection status and the time that
/// has passed. This function returns a list of peers that have been unbanned.
/// NOTE: Peer scores cannot be penalized during the update, they can only increase. Therefore
/// it not possible to ban peers when updating scores.
#[must_use = "The unbanned peers must be sent to libp2p"]
pub(super) fn update_scores(&mut self) -> Vec<(PeerId, ScoreUpdateResult)> {
// Peer can be unbanned in this process.
// We return the result, such that the peer manager can inform the swarm to lift the libp2p
// ban on these peers.
let mut peers_to_unban = Vec::new();
let mut result = Vec::new();
for (peer_id, info) in self.peers.iter_mut() {
let previous_state = info.score_state();
// Update scores
info.score_update();
match Self::handle_score_transition(previous_state, peer_id, info, &self.log) {
// A peer should not be able to be banned from a score update.
ScoreTransitionResult::Banned => {
error!(self.log, "Peer has been banned in an update"; "peer_id" => %peer_id)
}
// A peer should not be able to transition to a disconnected state from a healthy
// state in a score update.
ScoreTransitionResult::Disconnected => {
error!(self.log, "Peer has been disconnected in an update"; "peer_id" => %peer_id)
}
ScoreTransitionResult::Unbanned => {
peers_to_unban.push(*peer_id);
}
ScoreTransitionResult::NoAction => {}
}
}
// Update the state in the peerdb
for unbanned_peer in peers_to_unban {
self.update_connection_state(&unbanned_peer, NewConnectionState::Unbanned);
let seen_ip_addresses = self
.peers
.get(&unbanned_peer)
.map(|info| {
info.seen_ip_addresses()
.filter(|ip| !self.is_ip_banned(ip))
.collect::<Vec<_>>()
})
.unwrap_or_default();
result.push((
unbanned_peer,
ScoreUpdateResult::Unbanned(seen_ip_addresses),
));
}
// Return the list so that the peer manager can update libp2p
result
}
/// Updates gossipsub scores for all peers.
#[must_use = "Score updates need to be reported to libp2p"]
pub(super) fn update_gossipsub_scores(
&mut self,
target_peers: usize,
gossipsub: &Gossipsub,
) -> Vec<(PeerId, ScoreUpdateResult)> {
let mut actions = Vec::new();
let mut results = Vec::new();
let mut peers: Vec<_> = self
.peers
.iter_mut()
.filter(|(_peer_id, info)| info.is_connected())
.filter_map(|(peer_id, info)| {
gossipsub
.peer_score(peer_id)
.map(|score| (peer_id, info, score))
})
.collect();
// sort descending by score
peers.sort_unstable_by(|(.., s1), (.., s2)| s2.partial_cmp(s1).unwrap_or(Ordering::Equal));
let mut to_ignore_negative_peers =
(target_peers as f32 * ALLOWED_NEGATIVE_GOSSIPSUB_FACTOR).ceil() as usize;
for (peer_id, info, score) in peers {
let previous_state = info.score_state();
info.update_gossipsub_score(
score,
if score < 0.0 && to_ignore_negative_peers > 0 {
to_ignore_negative_peers -= 1;
// We ignore the negative score for the best negative peers so that their
// gossipsub score can recover without getting disconnected.
true
} else {
false
},
);
actions.push((
*peer_id,
Self::handle_score_transition(previous_state, peer_id, info, &self.log),
));
}
for (peer_id, action) in actions {
let result = match action {
ScoreTransitionResult::Banned => {
// The peer was banned as a result of this action.
self.update_connection_state(&peer_id, NewConnectionState::Banned)
.into()
}
ScoreTransitionResult::Disconnected => {
// The peer needs to be disconnected
// Update the state
self.update_connection_state(
&peer_id,
NewConnectionState::Disconnecting { to_ban: false },
);
ScoreUpdateResult::Disconnect
}
ScoreTransitionResult::NoAction => ScoreUpdateResult::NoAction,
ScoreTransitionResult::Unbanned => {
self.update_connection_state(&peer_id, NewConnectionState::Unbanned);
let seen_ip_addresses = self
.peers
.get(&peer_id)
.map(|info| {
info.seen_ip_addresses()
.filter(|ip| !self.is_ip_banned(ip))
.collect::<Vec<_>>()
})
.unwrap_or_default();
ScoreUpdateResult::Unbanned(seen_ip_addresses)
}
};
// Actions to be handled by the peer manager for each peer id
if !matches!(result, ScoreUpdateResult::NoAction) {
results.push((peer_id, result));
}
}
results
}
/// Reports a peer for some action.
///
/// The action can only cause a negative effect. This can lead to disconnecting or banning a
/// specific peer. Therefore the result of this function returns if the peer needs to be banned
/// or disconnected.
///
/// If the peer doesn't exist, log a warning and insert defaults.
#[must_use = "Banned and disconnected peers need to be handled in libp2p"]
pub(super) fn report_peer(
&mut self,
peer_id: &PeerId,
action: PeerAction,
source: ReportSource,
msg: &'static str,
) -> ScoreUpdateResult {
metrics::inc_counter_vec(&metrics::REPORT_PEER_MSGS, &[msg]);
match self.peers.get_mut(peer_id) {
Some(info) => {
let previous_state = info.score_state();
info.apply_peer_action_to_score(action);
metrics::inc_counter_vec(
&metrics::PEER_ACTION_EVENTS_PER_CLIENT,
&[info.client().kind.as_ref(), action.as_ref(), source.into()],
);
let result =
Self::handle_score_transition(previous_state, peer_id, info, &self.log);
if previous_state == info.score_state() {
debug!(
self.log,
"Peer score adjusted";
"msg" => %msg,
"peer_id" => %peer_id,
"score" => %info.score()
);
}
match result {
ScoreTransitionResult::Banned => {
// The peer was banned as a result of this action.
self.update_connection_state(peer_id, NewConnectionState::Banned)
.into()
}
ScoreTransitionResult::Disconnected => {
// The peer needs to be disconnected
// Update the state
self.update_connection_state(
peer_id,
NewConnectionState::Disconnecting { to_ban: false },
);
ScoreUpdateResult::Disconnect
}
ScoreTransitionResult::NoAction => ScoreUpdateResult::NoAction,
ScoreTransitionResult::Unbanned => {
error!(
self.log,
"Report peer action lead to an unbanning";
"msg" => %msg,
"peer_id" => %peer_id
);
ScoreUpdateResult::NoAction
}
}
}
None => {
debug!(
self.log,
"Reporting a peer that doesn't exist";
"msg" => %msg,
"peer_id" =>%peer_id
);
ScoreUpdateResult::NoAction
}
}
}
/// Update min ttl of a peer.
// VISIBILITY: Only the peer manager can update the min_ttl
pub(super) fn update_min_ttl(&mut self, peer_id: &PeerId, min_ttl: Instant) {
let info = self.peers.entry(*peer_id).or_default();
// only update if the ttl is longer
if info.min_ttl().is_none() || Some(&min_ttl) > info.min_ttl() {
info.set_min_ttl(min_ttl);
let min_ttl_secs = min_ttl
.checked_duration_since(Instant::now())
.map(|duration| duration.as_secs())
.unwrap_or_else(|| 0);
debug!(self.log, "Updating the time a peer is required for"; "peer_id" => %peer_id, "future_min_ttl_secs" => min_ttl_secs);
}
}
/// Adds a gossipsub subscription to a peer in the peerdb.
// VISIBILITY: The behaviour is able to adjust subscriptions.
pub(crate) fn add_subscription(&mut self, peer_id: &PeerId, subnet: Subnet) {
if let Some(info) = self.peers.get_mut(peer_id) {
info.insert_subnet(subnet);
}
}
/// Removes a gossipsub subscription to a peer in the peerdb.
// VISIBILITY: The behaviour is able to adjust subscriptions.
pub(crate) fn remove_subscription(&mut self, peer_id: &PeerId, subnet: &Subnet) {
if let Some(info) = self.peers.get_mut(peer_id) {
info.remove_subnet(subnet);
}
}
/// Extends the ttl of all peers on the given subnet that have a shorter
/// min_ttl than what's given.
// VISIBILITY: The behaviour is able to adjust subscriptions.
pub(crate) fn extend_peers_on_subnet(&mut self, subnet: &Subnet, min_ttl: Instant) {
let log = &self.log;
self.peers.iter_mut()
.filter(move |(_, info)| {
info.is_connected() && info.on_subnet_metadata(subnet) && info.on_subnet_gossipsub(subnet)
})
.for_each(|(peer_id,info)| {
if info.min_ttl().is_none() || Some(&min_ttl) > info.min_ttl() {
info.set_min_ttl(min_ttl);
}
let min_ttl_secs = min_ttl
.checked_duration_since(Instant::now())
.map(|duration| duration.as_secs())
.unwrap_or_else(|| 0);
trace!(log, "Updating minimum duration a peer is required for"; "peer_id" => %peer_id, "min_ttl" => min_ttl_secs);
});
}
/// A peer is being dialed.
// VISIBILITY: Only the peer manager can adjust the connection state
pub(super) fn dialing_peer(&mut self, peer_id: &PeerId, enr: Option<Enr>) {
self.update_connection_state(peer_id, NewConnectionState::Dialing { enr });
}
/// Sets a peer as connected with an ingoing connection.
// VISIBILITY: Only the peer manager can adjust the connection state.
pub(super) fn connect_ingoing(
&mut self,
peer_id: &PeerId,
seen_address: Multiaddr,
enr: Option<Enr>,
) {
self.update_connection_state(
peer_id,
NewConnectionState::Connected {
enr,
seen_address,
direction: ConnectionDirection::Incoming,
},
);
}
/// Sets a peer as connected with an outgoing connection.
// VISIBILITY: Only the peer manager can adjust the connection state.
pub(super) fn connect_outgoing(
&mut self,
peer_id: &PeerId,
seen_address: Multiaddr,
enr: Option<Enr>,
) {
self.update_connection_state(
peer_id,
NewConnectionState::Connected {
enr,
seen_address,
direction: ConnectionDirection::Outgoing,
},
);
}
/// The connection state of the peer has been changed. Modify the peer in the db to ensure all
/// variables are in sync with libp2p.
/// Updating the state can lead to a `BanOperation` which needs to be processed via the peer
/// manager and should be handled in the peer manager.
// NOTE: This function is vital in keeping the connection state, and thus the peerdb size in
// check and up to date with libp2p.
fn update_connection_state(
&mut self,
peer_id: &PeerId,
new_state: NewConnectionState,
) -> Option<BanOperation> {
let log_ref = &self.log;
let info = self.peers.entry(*peer_id).or_insert_with(|| {
// If we are not creating a new connection (or dropping a current inbound connection) log a warning indicating we are updating a
// connection state for an unknown peer.
if !matches!(
new_state,
NewConnectionState::Connected { .. } // We have established a new connection (peer may not have been seen before)
| NewConnectionState::Disconnecting { .. }// We are disconnecting from a peer that may not have been registered before
| NewConnectionState::Dialing { .. } // We are dialing a potentially new peer
| NewConnectionState::Disconnected { .. } // Dialing a peer that responds by a different ID can be immediately
// disconnected without having being stored in the db before
) {
warn!(log_ref, "Updating state of unknown peer";
"peer_id" => %peer_id, "new_state" => ?new_state);
}
if self.disable_peer_scoring {
PeerInfo::trusted_peer_info()
} else {
PeerInfo::default()
}
});
// Ban the peer if the score is not already low enough.
if matches!(new_state, NewConnectionState::Banned) {
match info.score_state() {
ScoreState::Banned => {}
_ => {
// If score isn't low enough to ban, this function has been called incorrectly.
error!(self.log, "Banning a peer with a good score"; "peer_id" => %peer_id);
info.apply_peer_action_to_score(score::PeerAction::Fatal);
}
}
}
// Handle all the possible state changes
match (info.connection_status().clone(), new_state) {
/* CONNECTED
*
*
* Handles the transition to a connected state
*/
(
current_state,
NewConnectionState::Connected {
enr,
direction,
seen_address,
},
) => {
// Update the ENR if one exists
if let Some(enr) = enr {
info.set_enr(enr);
}
match current_state {
PeerConnectionStatus::Disconnected { .. } => {
self.disconnected_peers = self.disconnected_peers.saturating_sub(1);
}
PeerConnectionStatus::Banned { .. } => {
error!(self.log, "Accepted a connection from a banned peer"; "peer_id" => %peer_id);
// TODO: check if this happens and report the unban back
self.banned_peers_count
.remove_banned_peer(info.seen_ip_addresses());
}
PeerConnectionStatus::Disconnecting { .. } => {
warn!(self.log, "Connected to a disconnecting peer"; "peer_id" => %peer_id)
}
PeerConnectionStatus::Unknown
| PeerConnectionStatus::Connected { .. }
| PeerConnectionStatus::Dialing { .. } => {}
}
// Update the connection state
match direction {
ConnectionDirection::Incoming => info.connect_ingoing(seen_address),
ConnectionDirection::Outgoing => info.connect_outgoing(seen_address),
}
}
/* DIALING
*
*
* Handles the transition to a dialing state
*/
(old_state, NewConnectionState::Dialing { enr }) => {
match old_state {
PeerConnectionStatus::Banned { .. } => {
warn!(self.log, "Dialing a banned peer"; "peer_id" => %peer_id);
self.banned_peers_count
.remove_banned_peer(info.seen_ip_addresses());
}
PeerConnectionStatus::Disconnected { .. } => {
self.disconnected_peers = self.disconnected_peers.saturating_sub(1);
}
PeerConnectionStatus::Connected { .. } => {
warn!(self.log, "Dialing an already connected peer"; "peer_id" => %peer_id)
}
PeerConnectionStatus::Dialing { .. } => {
warn!(self.log, "Dialing an already dialing peer"; "peer_id" => %peer_id)
}
PeerConnectionStatus::Disconnecting { .. } => {
warn!(self.log, "Dialing a disconnecting peer"; "peer_id" => %peer_id)
}
PeerConnectionStatus::Unknown => {} // default behaviour
}
// Update the ENR if one is known.
if let Some(enr) = enr {
info.set_enr(enr);
}
if let Err(e) = info.set_dialing_peer() {
error!(self.log, "{}", e; "peer_id" => %peer_id);
}
}
/* DISCONNECTED
*
*
* Handle the transition to the disconnected state
*/
(old_state, NewConnectionState::Disconnected) => {
// Remove all subnets for disconnected peers.
info.clear_subnets();
match old_state {
PeerConnectionStatus::Banned { .. } => {}
PeerConnectionStatus::Disconnected { .. } => {}
PeerConnectionStatus::Disconnecting { to_ban } if to_ban => {
// Update the status.
info.set_connection_status(PeerConnectionStatus::Banned {
since: Instant::now(),
});
self.banned_peers_count
.add_banned_peer(info.seen_ip_addresses());
let known_banned_ips = self.banned_peers_count.banned_ips();
let banned_ips = info
.seen_ip_addresses()
.filter(|ip| known_banned_ips.contains(ip))
.collect::<Vec<_>>();
return Some(BanOperation::ReadyToBan(banned_ips));
}
PeerConnectionStatus::Disconnecting { .. } => {
// The peer has been disconnected but not banned. Inform the peer manager
// that this peer could be eligible for a temporary ban.
self.disconnected_peers += 1;
info.set_connection_status(PeerConnectionStatus::Disconnected {
since: Instant::now(),
});
return Some(BanOperation::TemporaryBan);
}
PeerConnectionStatus::Unknown
| PeerConnectionStatus::Connected { .. }
| PeerConnectionStatus::Dialing { .. } => {
self.disconnected_peers += 1;
info.set_connection_status(PeerConnectionStatus::Disconnected {
since: Instant::now(),
});
}
}
}
/* DISCONNECTING
*
*
* Handles the transition to a disconnecting state
*/
(PeerConnectionStatus::Banned { .. }, NewConnectionState::Disconnecting { to_ban }) => {
error!(self.log, "Disconnecting from a banned peer"; "peer_id" => %peer_id);
info.set_connection_status(PeerConnectionStatus::Disconnecting { to_ban });
}
(
PeerConnectionStatus::Disconnected { .. },
NewConnectionState::Disconnecting { to_ban },
) => {
// If the peer was previously disconnected and is now being disconnected, decrease
// the disconnected_peers counter.
self.disconnected_peers = self.disconnected_peers.saturating_sub(1);
info.set_connection_status(PeerConnectionStatus::Disconnecting { to_ban });
}
(_, NewConnectionState::Disconnecting { to_ban }) => {
// We overwrite all states and set this peer to be disconnecting.
// NOTE: A peer can be in the disconnected state and transition straight to a
// disconnected state. This occurs when a disconnected peer dials us, we have too
// many peers and we transition them straight to the disconnecting state.
info.set_connection_status(PeerConnectionStatus::Disconnecting { to_ban });
}
/* BANNED
*
*
* Handles the transition to a banned state
*/
(PeerConnectionStatus::Disconnected { .. }, NewConnectionState::Banned) => {
// It is possible to ban a peer that is currently disconnected. This can occur when
// there are many events that score it poorly and are processed after it has disconnected.
info.set_connection_status(PeerConnectionStatus::Banned {
since: Instant::now(),
});
self.banned_peers_count
.add_banned_peer(info.seen_ip_addresses());
self.disconnected_peers = self.disconnected_peers.saturating_sub(1);
let known_banned_ips = self.banned_peers_count.banned_ips();
let banned_ips = info
.seen_ip_addresses()
.filter(|ip| known_banned_ips.contains(ip))
.collect::<Vec<_>>();
return Some(BanOperation::ReadyToBan(banned_ips));
}
(PeerConnectionStatus::Disconnecting { .. }, NewConnectionState::Banned) => {
// NOTE: This can occur due a rapid downscore of a peer. It goes through the
// disconnection phase and straight into banning in a short time-frame.
debug!(log_ref, "Banning peer that is currently disconnecting"; "peer_id" => %peer_id);
// Ban the peer once the disconnection process completes.
info.set_connection_status(PeerConnectionStatus::Disconnecting { to_ban: true });
return Some(BanOperation::PeerDisconnecting);
}
(PeerConnectionStatus::Banned { .. }, NewConnectionState::Banned) => {
error!(log_ref, "Banning already banned peer"; "peer_id" => %peer_id);
let known_banned_ips = self.banned_peers_count.banned_ips();
let banned_ips = info
.seen_ip_addresses()
.filter(|ip| known_banned_ips.contains(ip))
.collect::<Vec<_>>();
return Some(BanOperation::ReadyToBan(banned_ips));
}
(
PeerConnectionStatus::Connected { .. } | PeerConnectionStatus::Dialing { .. },
NewConnectionState::Banned,
) => {
// update the state
info.set_connection_status(PeerConnectionStatus::Disconnecting { to_ban: true });
return Some(BanOperation::DisconnectThePeer);
}
(PeerConnectionStatus::Unknown, NewConnectionState::Banned) => {
// shift the peer straight to banned
warn!(log_ref, "Banning a peer of unknown connection state"; "peer_id" => %peer_id);
self.banned_peers_count
.add_banned_peer(info.seen_ip_addresses());
info.set_connection_status(PeerConnectionStatus::Banned {
since: Instant::now(),
});
let known_banned_ips = self.banned_peers_count.banned_ips();
let banned_ips = info
.seen_ip_addresses()
.filter(|ip| known_banned_ips.contains(ip))
.collect::<Vec<_>>();
return Some(BanOperation::ReadyToBan(banned_ips));
}
/* UNBANNED
*
*
* Handles the transition to an unbanned state
*/
(old_state, NewConnectionState::Unbanned) => {
if matches!(info.score_state(), ScoreState::Banned) {
error!(self.log, "Unbanning a banned peer"; "peer_id" => %peer_id);
}
match old_state {
PeerConnectionStatus::Unknown | PeerConnectionStatus::Connected { .. } => {
error!(self.log, "Unbanning a connected peer"; "peer_id" => %peer_id);
}
PeerConnectionStatus::Disconnected { .. }
| PeerConnectionStatus::Disconnecting { .. } => {
debug!(self.log, "Unbanning disconnected or disconnecting peer"; "peer_id" => %peer_id);
} // These are odd but fine.
PeerConnectionStatus::Dialing { .. } => {} // Also odd but acceptable
PeerConnectionStatus::Banned { since } => {
info.set_connection_status(PeerConnectionStatus::Disconnected { since });
// Increment the disconnected count and reduce the banned count
self.banned_peers_count
.remove_banned_peer(info.seen_ip_addresses());
self.disconnected_peers = self.disconnected_peers.saturating_add(1);
}
}
}
}
None
}
/// Sets the peer as disconnected. A banned peer remains banned. If the node has become banned,
/// this returns true, otherwise this is false.
// VISIBILITY: Only the peer manager can adjust the connection state.
pub(super) fn inject_disconnect(
&mut self,
peer_id: &PeerId,
) -> (Option<BanOperation>, Vec<(PeerId, Vec<IpAddr>)>) {
// A peer can be banned for disconnecting. Thus another peer could be purged
let maybe_ban_op = self.update_connection_state(peer_id, NewConnectionState::Disconnected);
let purged_peers = self.shrink_to_fit();
(maybe_ban_op, purged_peers)
}
/// The peer manager has notified us that the peer is undergoing a normal disconnect. Optionally tag
/// the peer to be banned after the disconnect.
// VISIBILITY: Only the peer manager can adjust the connection state.
pub(super) fn notify_disconnecting(&mut self, peer_id: &PeerId, to_ban: bool) {
self.update_connection_state(peer_id, NewConnectionState::Disconnecting { to_ban });
}
/// Removes banned and disconnected peers from the DB if we have reached any of our limits.
/// Drops the peers with the lowest reputation so that the number of disconnected peers is less
/// than MAX_DC_PEERS
#[must_use = "Unbanned peers need to be reported to libp2p."]
fn shrink_to_fit(&mut self) -> Vec<(PeerId, Vec<IpAddr>)> {
let excess_peers = self
.banned_peers_count
.banned_peers()
.saturating_sub(MAX_BANNED_PEERS);
let mut unbanned_peers = Vec::with_capacity(excess_peers);
// Remove excess banned peers
while self.banned_peers_count.banned_peers() > MAX_BANNED_PEERS {
if let Some((to_drop, unbanned_ips)) = if let Some((id, info, _)) = self
.peers