Skip to main content

reth_network/
peers.rs

1//! Peer related implementations
2
3use crate::{
4    cache::LruMap,
5    error::SessionError,
6    session::{Direction, PendingSessionHandshakeError},
7    swarm::NetworkConnectionState,
8    trusted_peers_resolver::TrustedPeersResolver,
9};
10use alloy_primitives::map::{hash_map::Entry, FbBuildHasher, HashMap, HashSet};
11use futures::StreamExt;
12
13use rand::Rng;
14use reth_eth_wire::{
15    errors::{EthStreamError, P2PHandshakeError, P2PStreamError},
16    DisconnectReason,
17};
18use reth_ethereum_forks::ForkId;
19use reth_net_banlist::{is_global, BanList};
20use reth_network_api::test_utils::{PeerCommand, PeersHandle};
21use reth_network_peers::{NodeRecord, PeerId, TrustedPeer};
22use reth_network_types::{
23    is_connection_failed_reputation,
24    peers::{
25        config::{PeerBackoffDurations, PEER_ROTATION_MIN_UPTIME},
26        reputation::{DEFAULT_REPUTATION, MAX_TRUSTED_PEER_REPUTATION_CHANGE},
27    },
28    BackoffKind, ConnectionsConfig, Peer, PeerAddr, PeerConnectionState, PeerKind, PeersConfig,
29    PersistedPeerInfo, ReputationChangeKind, ReputationChangeOutcome, ReputationChangeWeights,
30};
31use std::{
32    collections::VecDeque,
33    fmt::Display,
34    io,
35    net::{IpAddr, SocketAddr},
36    pin::Pin,
37    task::{Context, Poll},
38    time::Duration,
39};
40use thiserror::Error;
41use tokio::{
42    sync::mpsc,
43    time::{Instant, Interval, Sleep},
44};
45use tokio_stream::wrappers::UnboundedReceiverStream;
46use tracing::{trace, warn};
47
48/// Bound admission-time throttling independently of long-lived security bans.
49const MAX_INCOMING_IP_THROTTLE_ENTRIES: u32 = 16_384;
50
51/// Maintains the state of _all_ the peers known to the network.
52///
53/// This is supposed to be owned by the network itself, but can be reached via the [`PeersHandle`].
54/// From this type, connections to peers are established or disconnected, see [`PeerAction`].
55///
56/// The [`PeersManager`] will be notified on peer related changes
57#[derive(Debug)]
58pub struct PeersManager {
59    /// All peers known to the network
60    peers: HashMap<PeerId, Peer, FbBuildHasher<64>>,
61    /// The set of trusted peer ids.
62    ///
63    /// This tracks peer ids that are considered trusted, but for which we don't necessarily have
64    /// an address: [`Self::add_trusted_peer_id`]
65    trusted_peer_ids: HashSet<PeerId, FbBuildHasher<64>>,
66    /// A resolver used to periodically resolve DNS names for trusted peers. This updates the
67    /// peer's address when the DNS records change.
68    trusted_peers_resolver: TrustedPeersResolver,
69    /// Copy of the sender half, so new [`PeersHandle`] can be created on demand.
70    manager_tx: mpsc::UnboundedSender<PeerCommand>,
71    /// Receiver half of the command channel.
72    handle_rx: UnboundedReceiverStream<PeerCommand>,
73    /// Buffered actions until the manager is polled.
74    queued_actions: VecDeque<PeerAction>,
75    /// Interval for triggering connections if there are free slots.
76    refill_slots_interval: Interval,
77    /// How to weigh reputation changes
78    reputation_weights: ReputationChangeWeights,
79    /// Tracks current slot stats.
80    connection_info: ConnectionInfo,
81    /// Tracks unwanted ips/peer ids.
82    ban_list: BanList,
83    /// Bounded recent-source throttle, separate from security bans.
84    incoming_ip_throttle: LruMap<IpAddr, std::time::Instant>,
85    /// Tracks currently backed off peers.
86    backed_off_peers: HashMap<PeerId, std::time::Instant, FbBuildHasher<64>>,
87    /// Interval at which to check for peers to unban and release from the backoff map.
88    release_interval: Interval,
89    /// How long to ban bad peers.
90    ban_duration: Duration,
91    /// How long peers to which we could not connect for non-fatal reasons, e.g.
92    /// [`DisconnectReason::TooManyPeers`], are put in time out.
93    backoff_durations: PeerBackoffDurations,
94    /// If non-trusted peers should be connected to, or the connection from non-trusted
95    /// incoming peers should be accepted.
96    trusted_nodes_only: bool,
97    /// Timestamp of the last time [`Self::tick`] was called.
98    last_tick: Instant,
99    /// Maximum number of backoff attempts before we give up on a peer and dropping.
100    max_backoff_count: u8,
101    /// Tracks the connection state of the node
102    net_connection_state: NetworkConnectionState,
103    /// How long to temporarily ban ip on an incoming connection attempt.
104    incoming_ip_throttle_duration: Duration,
105    /// IP address filter for restricting network connections to specific IP ranges.
106    ip_filter: reth_net_banlist::IpFilter,
107    /// If true, discovered peers without a confirmed ENR fork ID will not be added until their
108    /// fork ID is verified via EIP-868.
109    enforce_enr_fork_id: bool,
110    /// One-shot sleep that fires when it's time to rotate a peer; reset with jitter after each
111    /// fire. `None` when rotation is disabled.
112    peer_rotation_sleep: Option<Pin<Box<Sleep>>>,
113    /// Mean duration for computing jittered rotation intervals. `None` when rotation is disabled.
114    peer_rotation_mean: Option<Duration>,
115}
116
117impl PeersManager {
118    /// Create a new instance with the given config
119    pub fn new(config: PeersConfig) -> Self {
120        let PeersConfig {
121            refill_slots_interval,
122            connection_info,
123            reputation_weights,
124            ban_list,
125            ban_duration,
126            backoff_durations,
127            trusted_nodes,
128            trusted_nodes_only,
129            trusted_nodes_resolution_interval,
130            basic_nodes,
131            persisted_peers,
132            max_backoff_count,
133            incoming_ip_throttle_duration,
134            ip_filter,
135            enforce_enr_fork_id,
136            peer_rotation_interval,
137        } = config;
138        let (manager_tx, handle_rx) = mpsc::unbounded_channel();
139        let now = Instant::now();
140
141        // We use half of the interval to decrease the max duration to `150%` in worst case
142        let unban_interval = ban_duration.min(backoff_durations.low) / 2;
143
144        // Persisted rows are not counted, since filtered ones would keep their space reserved.
145        let mut peers: HashMap<PeerId, Peer, FbBuildHasher<64>> = HashMap::with_capacity_and_hasher(
146            trusted_nodes.len() + basic_nodes.len(),
147            Default::default(),
148        );
149        let mut trusted_peer_ids: HashSet<PeerId, FbBuildHasher<64>> =
150            HashSet::with_capacity_and_hasher(trusted_nodes.len(), Default::default());
151
152        for trusted_peer in &trusted_nodes {
153            // Tracked even if resolution fails or the address is filtered, otherwise the resolver's
154            // later results for this peer are discarded as revoked.
155            trusted_peer_ids.insert(trusted_peer.id);
156            match trusted_peer.resolve_blocking() {
157                Ok(NodeRecord { address, tcp_port, udp_port, id }) => {
158                    if !ip_filter.is_allowed(&address) {
159                        trace!(target: "net::peers", ?id, ?address, "Skipping trusted peer address not in allowed ranges");
160                        continue
161                    }
162                    peers.entry(id).or_insert_with(|| {
163                        Peer::trusted(PeerAddr::new_with_ports(address, tcp_port, Some(udp_port)))
164                    });
165                }
166                Err(err) => {
167                    warn!(target: "net::peers", ?err, "Failed to resolve trusted peer");
168                }
169            }
170        }
171
172        for PersistedPeerInfo { record, kind, fork_id, reputation } in persisted_peers {
173            // When enforce_enr_fork_id is enabled, skip persisted peers that don't have a
174            // confirmed fork ID. These were likely accumulated from a different network during
175            // a prior run without the flag.
176            if enforce_enr_fork_id && fork_id.is_none() {
177                continue
178            }
179            let NodeRecord { address, tcp_port, udp_port, id } = record;
180            // Filtering an address does not revoke the peer's trusted identity.
181            if kind.is_trusted() {
182                trusted_peer_ids.insert(id);
183            }
184            if !ip_filter.is_allowed(&address) {
185                trace!(target: "net::peers", ?id, ?address, "Skipping persisted peer from IP not in allowed ranges");
186                continue
187            }
188            peers.entry(id).or_insert_with(|| {
189                let mut peer = Peer::with_kind(
190                    PeerAddr::new_with_ports(address, tcp_port, Some(udp_port)),
191                    kind,
192                );
193                peer.fork_id = fork_id.map(Box::new);
194                peer.reputation = reputation;
195                peer
196            });
197        }
198
199        for NodeRecord { address, tcp_port, udp_port, id } in basic_nodes {
200            if !ip_filter.is_allowed(&address) {
201                trace!(target: "net::peers", ?id, ?address, "Skipping basic peer from IP not in allowed ranges");
202                continue
203            }
204            peers.entry(id).or_insert_with(|| {
205                Peer::new(PeerAddr::new_with_ports(address, tcp_port, Some(udp_port)))
206            });
207        }
208
209        // A trusted peer with an unresolved or filtered address has no trusted entry yet, so any
210        // persisted or basic fallback record must inherit its trusted kind.
211        for id in &trusted_peer_ids {
212            if let Some(peer) = peers.get_mut(id) {
213                peer.kind = PeerKind::Trusted;
214            }
215        }
216
217        trace!(target: "net::peers", trusted_peers=?trusted_peer_ids, "Initialized peers manager");
218
219        Self {
220            peers,
221            trusted_peer_ids,
222            trusted_peers_resolver: TrustedPeersResolver::new(
223                trusted_nodes,
224                tokio::time::interval(trusted_nodes_resolution_interval), // 1 hour
225            ),
226            manager_tx,
227            handle_rx: UnboundedReceiverStream::new(handle_rx),
228            queued_actions: Default::default(),
229            reputation_weights,
230            refill_slots_interval: tokio::time::interval(refill_slots_interval),
231            release_interval: tokio::time::interval_at(now + unban_interval, unban_interval),
232            connection_info: ConnectionInfo::new(connection_info),
233            ban_list,
234            incoming_ip_throttle: LruMap::new(MAX_INCOMING_IP_THROTTLE_ENTRIES),
235            backed_off_peers: Default::default(),
236            ban_duration,
237            backoff_durations,
238            trusted_nodes_only,
239            last_tick: Instant::now(),
240            max_backoff_count,
241            net_connection_state: NetworkConnectionState::default(),
242            incoming_ip_throttle_duration,
243            ip_filter,
244            enforce_enr_fork_id,
245            peer_rotation_sleep: peer_rotation_interval
246                .map(|mean| Box::pin(tokio::time::sleep(jitter_rotation_interval(mean)))),
247            peer_rotation_mean: peer_rotation_interval,
248        }
249    }
250
251    /// Returns a new [`PeersHandle`] that can send commands to this type.
252    pub(crate) fn handle(&self) -> PeersHandle {
253        PeersHandle::new(self.manager_tx.clone())
254    }
255
256    /// Returns `true` if discovered peers must have a confirmed ENR fork ID before being added.
257    pub(crate) const fn enforce_enr_fork_id(&self) -> bool {
258        self.enforce_enr_fork_id
259    }
260
261    /// Returns the number of peers in the peer set
262    #[inline]
263    pub(crate) fn num_known_peers(&self) -> usize {
264        self.peers.len()
265    }
266
267    /// Returns an iterator over all peers as [`NodeRecord`]s.
268    pub(crate) fn iter_peers(&self) -> impl Iterator<Item = NodeRecord> + '_ {
269        self.peers.iter().map(|(peer_id, v)| {
270            NodeRecord::new_with_ports(
271                v.addr.tcp().ip(),
272                v.addr.tcp().port(),
273                v.addr.udp().map(|addr| addr.port()),
274                *peer_id,
275            )
276        })
277    }
278
279    /// Returns an iterator over peers suitable for persisting to disk.
280    ///
281    /// Filters out backed-off and banned peers, and untrusted peers tracked only until their
282    /// session ends, and includes metadata like kind, fork ID, and reputation.
283    pub(crate) fn persistable_peers(&self) -> impl Iterator<Item = PersistedPeerInfo> + '_ {
284        self.peers
285            .iter()
286            .filter(|(_, peer)| !peer.is_backed_off() && !peer.is_banned() && !peer.is_temporary())
287            .map(|(peer_id, peer)| PersistedPeerInfo {
288                record: NodeRecord::new_with_ports(
289                    peer.addr.tcp().ip(),
290                    peer.addr.tcp().port(),
291                    peer.addr.udp().map(|addr| addr.port()),
292                    *peer_id,
293                ),
294                kind: peer.kind,
295                fork_id: peer.fork_id.as_deref().copied(),
296                reputation: peer.reputation,
297            })
298    }
299
300    /// Returns the `NodeRecord` and `PeerKind` for the given peer id
301    pub(crate) fn peer_by_id(&self, peer_id: PeerId) -> Option<(NodeRecord, PeerKind)> {
302        self.peers.get(&peer_id).map(|v| {
303            (
304                NodeRecord::new_with_ports(
305                    v.addr.tcp().ip(),
306                    v.addr.tcp().port(),
307                    v.addr.udp().map(|addr| addr.port()),
308                    peer_id,
309                ),
310                v.kind,
311            )
312        })
313    }
314
315    /// Returns `true` if the given peer is connected via an inbound session.
316    pub(crate) fn is_inbound_peer(&self, peer_id: &PeerId) -> bool {
317        self.peers.get(peer_id).is_some_and(|p| {
318            matches!(p.state, PeerConnectionState::In | PeerConnectionState::DisconnectingIn)
319        })
320    }
321
322    /// Returns an iterator over all peer ids for peers with the given kind
323    pub(crate) fn peers_by_kind(&self, kind: PeerKind) -> impl Iterator<Item = PeerId> + '_ {
324        self.peers.iter().filter_map(move |(peer_id, peer)| (peer.kind == kind).then_some(*peer_id))
325    }
326
327    /// Returns the number of currently active inbound connections.
328    #[inline]
329    pub(crate) const fn num_inbound_connections(&self) -> usize {
330        self.connection_info.num_inbound
331    }
332
333    /// Returns the number of currently __active__ outbound connections.
334    #[inline]
335    pub(crate) const fn num_outbound_connections(&self) -> usize {
336        self.connection_info.num_outbound
337    }
338
339    /// Returns the number of currently pending outbound connections.
340    #[inline]
341    pub(crate) const fn num_pending_outbound_connections(&self) -> usize {
342        self.connection_info.num_pending_out
343    }
344
345    /// Returns the number of currently backed off peers.
346    #[inline]
347    pub(crate) fn num_backed_off_peers(&self) -> usize {
348        self.backed_off_peers.len()
349    }
350
351    /// Invoked when a new _incoming_ tcp connection is accepted.
352    ///
353    /// returns an error if the inbound ip address is on the ban list
354    pub(crate) fn on_incoming_pending_session(
355        &mut self,
356        addr: IpAddr,
357    ) -> Result<(), InboundConnectionError> {
358        // Check if the IP is in the allowed ranges (netrestrict)
359        if !self.ip_filter.is_allowed(&addr) {
360            trace!(target: "net", ?addr, "Rejecting connection from IP not in allowed ranges");
361            return Err(InboundConnectionError::IpBanned)
362        }
363
364        if self.ban_list.is_banned_ip(&addr) ||
365            self.incoming_ip_throttle
366                .get(&addr)
367                .is_some_and(|until| *until > std::time::Instant::now())
368        {
369            return Err(InboundConnectionError::IpBanned)
370        }
371
372        // check if we even have slots for a new incoming connection
373        if !self.connection_info.has_in_capacity() {
374            if self.trusted_peer_ids.is_empty() {
375                // if we don't have any incoming slots and no trusted peers, we don't accept any new
376                // connections
377                return Err(InboundConnectionError::ExceedsCapacity)
378            }
379
380            // there's an edge case here where no incoming connections besides from trusted peers
381            // are allowed (max_inbound == 0), in which case we still need to allow new pending
382            // incoming connections until all trusted peers are connected. The identity of a pending
383            // connection is not known yet, so this is bounded by the number of trusted peers.
384            let max_inbound =
385                self.trusted_peer_ids.len().max(self.connection_info.config.max_inbound);
386            if self.connection_info.num_pending_in < max_inbound {
387                // Rate limit these admissions as well, otherwise a single host could keep
388                // the pending slots occupied once the inbound slots are taken.
389                self.throttle_incoming_ip(addr);
390                self.connection_info.inc_pending_in();
391                return Ok(())
392            }
393
394            // all trusted peers are either connected or connecting
395            return Err(InboundConnectionError::ExceedsCapacity)
396        }
397
398        // also cap the incoming connections we can process at once
399        if !self.connection_info.has_in_pending_capacity() {
400            return Err(InboundConnectionError::ExceedsCapacity)
401        }
402
403        // apply the rate limit
404        self.throttle_incoming_ip(addr);
405
406        self.connection_info.inc_pending_in();
407        Ok(())
408    }
409
410    /// Invoked when a previous call to [`Self::on_incoming_pending_session`] succeeded but it was
411    /// rejected.
412    pub(crate) const fn on_incoming_pending_session_rejected_internally(&mut self) {
413        self.connection_info.decr_pending_in();
414    }
415
416    /// Invoked when a pending session was closed.
417    pub(crate) const fn on_incoming_pending_session_gracefully_closed(&mut self) {
418        self.connection_info.decr_pending_in()
419    }
420
421    /// Invoked when a pending session was closed.
422    pub(crate) fn on_incoming_pending_session_dropped(
423        &mut self,
424        remote_addr: SocketAddr,
425        err: &PendingSessionHandshakeError,
426    ) {
427        if err.is_fatal_protocol_error() {
428            self.ban_ip(remote_addr.ip());
429
430            if err.merits_discovery_ban() {
431                self.queued_actions
432                    .push_back(PeerAction::DiscoveryBanIp { ip_addr: remote_addr.ip() })
433            }
434        }
435
436        self.connection_info.decr_pending_in();
437    }
438
439    /// Called when a new _incoming_ active session was established to the given peer.
440    ///
441    /// This will update the state of the peer if not yet tracked.
442    ///
443    /// If the reputation of the peer is below the `BANNED_REPUTATION` threshold, a disconnect will
444    /// be scheduled.
445    pub(crate) fn on_incoming_session_established(&mut self, peer_id: PeerId, addr: SocketAddr) {
446        self.connection_info.decr_pending_in();
447
448        // we only need to check the peer id here as the ip address will have been checked at
449        // on_incoming_pending_session. We also check if the peer is in the backoff list here.
450        if self.ban_list.is_banned_peer(&peer_id) {
451            self.queued_actions.push_back(PeerAction::DisconnectBannedIncoming { peer_id });
452            return
453        }
454
455        // check if the peer is trustable or not
456        let is_trusted = self.trusted_peer_ids.contains(&peer_id);
457        if self.trusted_nodes_only && !is_trusted {
458            self.queued_actions.push_back(PeerAction::DisconnectUntrustedIncoming { peer_id });
459            return
460        }
461
462        // Reward the connected peers before the new one joins them. Less than a second carries
463        // over to the next tick, so the new peer gains at most one point for time before its
464        // session.
465        self.tick();
466
467        match self.peers.entry(peer_id) {
468            Entry::Occupied(mut entry) => {
469                let peer = entry.get_mut();
470                if peer.is_banned() {
471                    self.queued_actions.push_back(PeerAction::DisconnectBannedIncoming { peer_id });
472                    return
473                }
474                // it might be the case that we're also trying to connect to this peer at the same
475                // time, so we need to adjust the state here
476                if peer.state.is_pending_out() {
477                    self.connection_info.decr_state(peer.state);
478                }
479
480                peer.state = PeerConnectionState::In;
481                peer.mark_connected();
482            }
483            Entry::Vacant(entry) => {
484                // peer is missing in the table, we add it but mark it as to be removed after
485                // disconnect, because we only know the outgoing port
486                let mut peer = Peer::with_state(PeerAddr::from_tcp(addr), PeerConnectionState::In);
487                peer.mark_connected();
488                peer.remove_after_disconnect = true;
489                if is_trusted {
490                    peer.kind = PeerKind::Trusted;
491                }
492                entry.insert(peer);
493                self.queued_actions.push_back(PeerAction::PeerAdded(peer_id));
494            }
495        }
496
497        let has_in_capacity = self.has_inbound_capacity(peer_id);
498        // increment new incoming connection
499        self.connection_info.inc_in();
500
501        // disconnect the peer if we don't have capacity for more inbound connections
502        if !has_in_capacity {
503            self.queued_actions.push_back(PeerAction::Disconnect {
504                peer_id,
505                reason: Some(DisconnectReason::TooManyPeers),
506            });
507        }
508    }
509
510    /// Checks capacity before an incoming session can supersede an outbound attempt.
511    pub(crate) fn has_inbound_capacity(&self, peer_id: PeerId) -> bool {
512        self.connection_info.has_in_capacity() ||
513            self.trusted_peer_ids.contains(&peer_id) ||
514            self.peers.get(&peer_id).is_some_and(|peer| peer.is_trusted())
515    }
516
517    /// Returns the reason to reject an incoming session before it is activated, or `None` if the
518    /// session may become active.
519    pub(crate) fn inbound_session_rejection(&self, peer_id: PeerId) -> Option<DisconnectReason> {
520        if self.ban_list.is_banned_peer(&peer_id) ||
521            self.peers.get(&peer_id).is_some_and(|peer| peer.is_banned()) ||
522            (self.trusted_nodes_only && !self.trusted_peer_ids.contains(&peer_id))
523        {
524            return Some(DisconnectReason::DisconnectRequested)
525        }
526        (!self.has_inbound_capacity(peer_id)).then_some(DisconnectReason::TooManyPeers)
527    }
528
529    /// Bans the peer temporarily with the configured ban timeout
530    fn ban_peer(&mut self, peer_id: PeerId) {
531        let ban_duration = if let Some(peer) = self.peers.get(&peer_id) &&
532            (peer.is_trusted() || peer.is_static())
533        {
534            // For misbehaving trusted or static peers, we provide a bit more leeway when
535            // penalizing them.
536            self.backoff_durations.low / 2
537        } else {
538            self.ban_duration
539        };
540
541        self.ban_list.ban_peer_until(peer_id, std::time::Instant::now() + ban_duration);
542        self.queued_actions.push_back(PeerAction::BanPeer { peer_id });
543    }
544
545    /// Bans the IP temporarily with the configured ban timeout
546    fn ban_ip(&mut self, ip: IpAddr) {
547        self.ban_list.ban_ip_until(ip, std::time::Instant::now() + self.ban_duration);
548    }
549
550    /// Rate limits recent global sources without allowing the throttle state to grow unbounded.
551    fn throttle_incoming_ip(&mut self, ip: IpAddr) {
552        if is_global(&ip) {
553            // Evict the least recently used throttle when full. Security bans are never evicted,
554            // and a new source still gets throttled without blocking unrelated admissions.
555            self.incoming_ip_throttle
556                .insert(ip, std::time::Instant::now() + self.incoming_ip_throttle_duration);
557        }
558    }
559
560    /// Temporarily puts the peer in timeout by inserting it into the backedoff peers set
561    fn backoff_peer_until(&mut self, peer_id: PeerId, until: std::time::Instant) {
562        trace!(target: "net::peers", ?peer_id, "backing off");
563
564        if let Some(peer) = self.peers.get_mut(&peer_id) {
565            peer.backed_off = true;
566            self.backed_off_peers.insert(peer_id, until);
567        }
568    }
569
570    /// Clears the peer's unauthenticated dial failures, e.g. after its address changed or it became
571    /// trusted or static, and shortens a pending backoff to the base delay those failures extended.
572    fn reset_unauthenticated_dial_failures(&mut self, peer_id: PeerId) {
573        if let Some(peer) = self.peers.get_mut(&peer_id) &&
574            peer.unauthenticated_dial_failures > 0
575        {
576            peer.unauthenticated_dial_failures = 0;
577            let base = self.backoff_durations.backoff_until(BackoffKind::Low, 0);
578            if let Some(until) = self.backed_off_peers.get_mut(&peer_id) {
579                *until = (*until).min(base);
580            }
581        }
582    }
583
584    /// Unbans the peer
585    fn unban_peer(&mut self, peer_id: PeerId) {
586        self.ban_list.unban_peer(&peer_id);
587        self.queued_actions.push_back(PeerAction::UnBanPeer { peer_id });
588    }
589
590    /// Tick function to update reputation of all connected peers.
591    /// Peers are rewarded with reputation increases for the time they are connected since the last
592    /// tick. This is to prevent peers from being disconnected eventually due to slashed
593    /// reputation because of some bad messages (most likely transaction related)
594    ///
595    /// Only whole seconds are rewarded. The rest of the elapsed time stays with the next tick, so
596    /// callers that tick more than once per second neither lose it nor scan the peers again.
597    fn tick(&mut self) {
598        let now = Instant::now();
599        // Determine the number of seconds since the last tick.
600        // Ensuring that now is always greater than last_tick to account for issues with system
601        // time.
602        let secs_since_last_tick =
603            if self.last_tick > now { 0 } else { (now - self.last_tick).as_secs() };
604        if secs_since_last_tick == 0 {
605            return
606        }
607        self.last_tick += Duration::from_secs(secs_since_last_tick);
608        let secs_since_last_tick = i32::try_from(secs_since_last_tick).unwrap_or(i32::MAX);
609
610        // update reputation via seconds connected
611        for peer in self.peers.iter_mut().filter(|(_, peer)| peer.state.is_connected()) {
612            // update reputation via seconds connected, but keep the target _around_ the default
613            // reputation.
614            if peer.1.reputation < DEFAULT_REPUTATION {
615                peer.1.reputation =
616                    peer.1.reputation.saturating_add(secs_since_last_tick).min(DEFAULT_REPUTATION);
617            }
618        }
619    }
620
621    /// Returns the tracked reputation for a peer.
622    pub(crate) fn get_reputation(&self, peer_id: &PeerId) -> Option<i32> {
623        self.peers.get(peer_id).map(|peer| peer.reputation)
624    }
625
626    /// Apply the corresponding reputation change to the given peer.
627    ///
628    /// If the peer is a trusted peer, it will be exempt from reputation slashing for certain
629    /// reputation changes that can be attributed to network conditions. If the peer is a
630    /// trusted peer, it will also be less strict with the reputation slashing.
631    pub(crate) fn apply_reputation_change(&mut self, peer_id: &PeerId, rep: ReputationChangeKind) {
632        trace!(target: "net::peers", ?peer_id, reputation=?rep, "applying reputation change");
633
634        let reputation_change = if rep.is_reset() {
635            None
636        } else {
637            let reputation_change = self.reputation_weights.change(rep).as_i32();
638            if reputation_change == 0 {
639                return
640            }
641            Some(reputation_change)
642        };
643
644        let outcome = if let Some(peer) = self.peers.get_mut(peer_id) {
645            if let Some(mut reputation_change) = reputation_change {
646                if peer.is_trusted() || peer.is_static() {
647                    // exempt trusted and static peers from reputation slashing for
648                    if matches!(
649                        rep,
650                        ReputationChangeKind::Dropped |
651                            ReputationChangeKind::BadAnnouncement |
652                            ReputationChangeKind::Timeout |
653                            ReputationChangeKind::AlreadySeenTransaction
654                    ) {
655                        return
656                    }
657
658                    // also be less strict with the reputation slashing for trusted peers
659                    if reputation_change < MAX_TRUSTED_PEER_REPUTATION_CHANGE {
660                        // this caps the reputation change to the maximum allowed for trusted peers
661                        reputation_change = MAX_TRUSTED_PEER_REPUTATION_CHANGE;
662                    }
663                }
664                peer.apply_reputation(reputation_change, rep)
665            } else {
666                peer.reset_reputation()
667            }
668        } else {
669            return
670        };
671
672        match outcome {
673            ReputationChangeOutcome::None => {}
674            ReputationChangeOutcome::Ban => {
675                self.ban_peer(*peer_id);
676            }
677            ReputationChangeOutcome::Unban => self.unban_peer(*peer_id),
678            ReputationChangeOutcome::DisconnectAndBan => {
679                self.queued_actions.push_back(PeerAction::Disconnect {
680                    peer_id: *peer_id,
681                    reason: Some(DisconnectReason::DisconnectRequested),
682                });
683                self.ban_peer(*peer_id);
684            }
685        }
686    }
687
688    /// Gracefully disconnected a pending _outgoing_ session
689    pub(crate) fn on_outgoing_pending_session_gracefully_closed(&mut self, peer_id: &PeerId) {
690        if let Some(peer) = self.peers.get_mut(peer_id) &&
691            peer.state.is_pending_out()
692        {
693            self.connection_info.decr_state(peer.state);
694            if peer.is_temporary() {
695                // a temporary peer is removed however its dial ends
696                self.peers.remove(peer_id);
697                self.queued_actions.push_back(PeerAction::PeerRemoved(*peer_id));
698                return
699            }
700            peer.state = PeerConnectionState::Idle;
701            peer.mark_disconnected();
702        }
703    }
704
705    /// Invoked when an _outgoing_ pending session was closed during authentication or the
706    /// handshake.
707    pub(crate) fn on_outgoing_pending_session_dropped(
708        &mut self,
709        remote_addr: &SocketAddr,
710        peer_id: &PeerId,
711        err: &PendingSessionHandshakeError,
712    ) {
713        if matches!(
714            err,
715            PendingSessionHandshakeError::Ecies(_) | PendingSessionHandshakeError::Timeout
716        ) || matches!(
717            err,
718            PendingSessionHandshakeError::Eth(EthStreamError::P2PStreamError(
719                P2PStreamError::HandshakeError(
720                    P2PHandshakeError::Timeout | P2PHandshakeError::NoResponse
721                )
722            ))
723        ) || matches!(err, PendingSessionHandshakeError::Eth(error) if error.as_io().is_some())
724        {
725            // ACK, transport, and Hello timeout errors can precede the first authenticated frame.
726            // The outer timeout carries no handshake phase, so it is also treated conservatively.
727            // Back off the attempt without penalizing that identity or its discovery record.
728            if let Some(peer) = self.peers.get_mut(peer_id) &&
729                peer.state.is_pending_out()
730            {
731                // Basic peers back off longer after each consecutive failure so that repeatedly
732                // failing peers don't keep taking precedence over untried candidates.
733                // A late failure from a previous address says nothing about the current one.
734                let failures = if peer.is_trusted() ||
735                    peer.is_static() ||
736                    self.trusted_peer_ids.contains(peer_id) ||
737                    peer.addr.tcp() != *remote_addr
738                {
739                    0
740                } else {
741                    peer.unauthenticated_dial_failures =
742                        peer.unauthenticated_dial_failures.saturating_add(1);
743                    peer.unauthenticated_dial_failures - 1
744                };
745                self.on_outgoing_pending_session_gracefully_closed(peer_id);
746                self.backoff_peer_until(
747                    *peer_id,
748                    self.backoff_durations.backoff_until(BackoffKind::Low, failures),
749                );
750                self.fill_outbound_slots();
751            }
752            return
753        }
754        self.on_connection_failure(remote_addr, peer_id, err, ReputationChangeKind::FailedToConnect)
755    }
756
757    /// Gracefully disconnected an active session
758    pub(crate) fn on_active_session_gracefully_closed(&mut self, peer_id: PeerId) {
759        match self.peers.entry(peer_id) {
760            Entry::Occupied(mut entry) => {
761                trace!(target: "net::peers", ?peer_id, direction=?entry.get().state, "active session gracefully closed");
762                self.connection_info.decr_state(entry.get().state);
763
764                if entry.get().is_temporary() {
765                    // this peer should be removed from the set
766                    entry.remove();
767                    self.queued_actions.push_back(PeerAction::PeerRemoved(peer_id));
768                } else {
769                    let peer = entry.get_mut();
770                    // reset the peer's state
771                    // we reset the backoff counter since we're able to establish a successful
772                    // session to that peer
773                    peer.severe_backoff_counter = 0;
774                    peer.state = PeerConnectionState::Idle;
775                    peer.mark_disconnected();
776
777                    // but we're backing off slightly to avoid dialing the peer again right away, to
778                    // give the remote time to also properly register the closed session and clean
779                    // up and to avoid any issues with ip throttling on the remote in case this
780                    // session was terminated right away.
781                    peer.backed_off = true;
782                    self.backed_off_peers.insert(
783                        peer_id,
784                        std::time::Instant::now() + self.incoming_ip_throttle_duration,
785                    );
786                    trace!(target: "net::peers", ?peer_id, kind=?peer.kind, duration=?self.incoming_ip_throttle_duration, "backing off on gracefully closed session");
787                }
788            }
789            Entry::Vacant(_) => return,
790        }
791
792        self.fill_outbound_slots();
793    }
794
795    /// Called when a _pending_ outbound connection is successful.
796    pub(crate) fn on_active_outgoing_established(&mut self, peer_id: PeerId) {
797        let at_capacity = self.connection_info.is_outbound_at_capacity();
798        if let Some(peer) = self.peers.get_mut(&peer_id) {
799            trace!(target: "net::peers", ?peer_id, "established active outgoing connection");
800            self.connection_info.decr_state(peer.state);
801            self.connection_info.inc_out();
802            peer.state = PeerConnectionState::Out;
803            peer.mark_connected();
804            if peer.is_temporary() {
805                // `Self::remove_peer` ran during the dial, when there was no session to disconnect.
806                peer.state.disconnect();
807                self.queued_actions.push_back(PeerAction::Disconnect {
808                    peer_id,
809                    reason: Some(DisconnectReason::DisconnectRequested),
810                });
811            } else if at_capacity &&
812                !peer.is_trusted() &&
813                !peer.is_static() &&
814                !self.trusted_peer_ids.contains(&peer_id)
815            {
816                self.queued_actions.push_back(PeerAction::Disconnect {
817                    peer_id,
818                    reason: Some(DisconnectReason::TooManyPeers),
819                });
820            }
821        }
822    }
823
824    /// Called when an _active_ session to a peer was forcefully dropped due to an error.
825    ///
826    /// Depending on whether the error is fatal, the peer will be removed from the peer set
827    /// otherwise its reputation is slashed. A peer tracked only until its session ends is removed
828    /// from the set as well.
829    pub(crate) fn on_active_session_dropped(
830        &mut self,
831        remote_addr: &SocketAddr,
832        peer_id: &PeerId,
833        err: &EthStreamError,
834    ) {
835        self.on_connection_failure(remote_addr, peer_id, err, ReputationChangeKind::Dropped)
836    }
837
838    /// Called when an attempt to create an _outgoing_ pending session failed while setting up a tcp
839    /// connection.
840    pub(crate) fn on_outgoing_connection_failure(
841        &mut self,
842        remote_addr: &SocketAddr,
843        peer_id: &PeerId,
844        err: &io::Error,
845    ) {
846        // there's a race condition where we accepted an incoming connection while we were trying to
847        // connect to the same peer at the same time. if the outgoing connection failed
848        // after the incoming connection was accepted, we can ignore this error
849        if let Some(peer) = self.peers.get(peer_id) {
850            if peer.state.is_incoming() {
851                // we already have an active connection to the peer, so we can ignore this error
852                return
853            }
854
855            if peer.is_trusted() && is_connection_failed_reputation(peer.reputation) {
856                // trigger resolution task for trusted peer since multiple connection failures
857                // occurred
858                self.trusted_peers_resolver.interval.reset_immediately();
859            }
860        }
861
862        self.on_connection_failure(remote_addr, peer_id, err, ReputationChangeKind::FailedToConnect)
863    }
864
865    fn on_connection_failure(
866        &mut self,
867        remote_addr: &SocketAddr,
868        peer_id: &PeerId,
869        err: impl SessionError,
870        reputation_change: ReputationChangeKind,
871    ) {
872        trace!(target: "net::peers", ?remote_addr, ?peer_id, %err, "handling failed connection");
873
874        if err.is_fatal_protocol_error() {
875            trace!(target: "net::peers", ?remote_addr, ?peer_id, %err, "fatal connection error");
876            // remove the peer to which we can't establish a connection due to protocol related
877            // issues.
878            if let Entry::Occupied(mut entry) = self.peers.entry(*peer_id) {
879                self.connection_info.decr_state(entry.get().state);
880                // only remove if the peer is not trusted
881                if entry.get().is_trusted() {
882                    let peer = entry.get_mut();
883                    peer.state = PeerConnectionState::Idle;
884                    peer.mark_disconnected();
885                } else {
886                    entry.remove();
887                    self.queued_actions.push_back(PeerAction::PeerRemoved(*peer_id));
888                    // If the error is caused by a peer that should be banned from discovery
889                    if err.merits_discovery_ban() {
890                        self.queued_actions.push_back(PeerAction::DiscoveryBanPeerId {
891                            peer_id: *peer_id,
892                            ip_addr: remote_addr.ip(),
893                        })
894                    }
895                }
896            }
897
898            // ban the peer
899            self.ban_peer(*peer_id);
900        } else {
901            let mut backoff_until = None;
902            let mut remove_peer = false;
903
904            if let Some(peer) = self.peers.get_mut(peer_id) {
905                if let Some(kind) = err.should_backoff() {
906                    if peer.is_trusted() || peer.is_static() {
907                        // provide a bit more leeway for trusted peers and use a lower backoff so
908                        // that we keep re-trying them after backing off shortly, but we should at
909                        // least backoff for the low duration to not violate the ip based inbound
910                        // connection throttle that peer has in place, because this peer might not
911                        // have us registered as a trusted peer.
912                        let backoff = self.backoff_durations.low;
913                        backoff_until = Some(std::time::Instant::now() + backoff);
914                        trace!(target: "net::peers", ?peer_id, ?backoff, "backing off trusted peer");
915                    } else {
916                        // This backoff replaces any escalated one, so a later reset must not
917                        // shorten it.
918                        peer.unauthenticated_dial_failures = 0;
919                        // Increment peer.backoff_counter
920                        if kind.is_severe() {
921                            peer.severe_backoff_counter =
922                                peer.severe_backoff_counter.saturating_add(1);
923                        }
924                        trace!(target: "net::peers", ?peer_id, ?kind, severe_backoff_counter=peer.severe_backoff_counter, "backing off basic peer");
925
926                        let backoff_time =
927                            self.backoff_durations.backoff_until(kind, peer.severe_backoff_counter);
928
929                        // The peer has signaled that it is currently unable to process any more
930                        // connections, so we will hold off on attempting any new connections for a
931                        // while
932                        backoff_until = Some(backoff_time);
933                    }
934                } else {
935                    // If the error was not a backoff error, we reduce the peer's reputation
936                    let reputation_change = self.reputation_weights.change(reputation_change);
937                    peer.reputation = peer.reputation.saturating_add(reputation_change.as_i32());
938                };
939
940                // a temporary peer is removed however its session ends
941                remove_peer = peer.is_temporary();
942
943                self.connection_info.decr_state(peer.state);
944                peer.state = PeerConnectionState::Idle;
945                peer.mark_disconnected();
946
947                if peer.severe_backoff_counter > self.max_backoff_count &&
948                    !peer.is_trusted() &&
949                    !peer.is_static()
950                {
951                    // mark peer for removal if it has been backoff too many times and is _not_
952                    // trusted or static
953                    remove_peer = true;
954                }
955            }
956
957            // remove peer if it has been marked for removal
958            if remove_peer {
959                trace!(target: "net", ?peer_id, "removed peer after failed connection");
960                let (peer_id, _) = self.peers.remove_entry(peer_id).expect("peer must exist");
961                self.queued_actions.push_back(PeerAction::PeerRemoved(peer_id));
962            } else if let Some(backoff_until) = backoff_until {
963                // otherwise, backoff the peer if marked as such
964                self.backoff_peer_until(*peer_id, backoff_until);
965            }
966        }
967
968        self.fill_outbound_slots();
969    }
970
971    /// Invoked if a pending session was disconnected because there's already a connection to the
972    /// peer.
973    ///
974    /// If the session was an outgoing connection, this means that the peer initiated a connection
975    /// to us at the same time and this connection is already established.
976    pub(crate) const fn on_already_connected(&mut self, direction: Direction) {
977        match direction {
978            Direction::Incoming => {
979                // need to decrement the ingoing counter
980                self.connection_info.decr_pending_in();
981            }
982            Direction::Outgoing(_) => {
983                // cleanup is handled when the incoming active session is activated in
984                // `on_incoming_session_established`
985            }
986        }
987    }
988
989    /// Called for a newly discovered peer.
990    ///
991    /// If the peer already exists, then the address, kind and `fork_id` will be updated.
992    pub(crate) fn add_peer(&mut self, peer_id: PeerId, addr: PeerAddr, fork_id: Option<ForkId>) {
993        self.add_peer_kind(peer_id, None, addr, fork_id)
994    }
995
996    /// Marks the given peer as trusted.
997    pub(crate) fn add_trusted_peer_id(&mut self, peer_id: PeerId) {
998        self.trusted_peer_ids.insert(peer_id);
999        if let Some(peer) = self.peers.get_mut(&peer_id) {
1000            peer.kind = PeerKind::Trusted;
1001        }
1002        self.reset_unauthenticated_dial_failures(peer_id);
1003    }
1004
1005    /// Called for a newly discovered trusted peer.
1006    ///
1007    /// If the peer already exists, then the address and kind will be updated.
1008    #[cfg_attr(not(test), expect(dead_code))]
1009    pub(crate) fn add_trusted_peer(&mut self, peer_id: PeerId, addr: PeerAddr) {
1010        self.add_peer_kind(peer_id, Some(PeerKind::Trusted), addr, None)
1011    }
1012
1013    /// Adds a trusted peer that may use a hostname instead of an IP address.
1014    ///
1015    /// An already tracked peer is marked as trusted right away.
1016    pub(crate) fn add_trusted_peer_node(&mut self, trusted: TrustedPeer) {
1017        let peer_id = trusted.id;
1018        self.add_trusted_peer_id(peer_id);
1019        self.trusted_peers_resolver.remove(peer_id);
1020        self.trusted_peers_resolver.trusted_peers.push(trusted);
1021        self.trusted_peers_resolver.interval.reset_immediately();
1022    }
1023
1024    /// Called for a newly discovered peer.
1025    ///
1026    /// If the peer already exists, then the address, kind and `fork_id` will be updated.
1027    /// If the peer exists and a [`PeerKind`] is provided then the peer's kind is updated.
1028    /// New peers without an explicit kind inherit trust registered for their ID.
1029    pub(crate) fn add_peer_kind(
1030        &mut self,
1031        peer_id: PeerId,
1032        kind: Option<PeerKind>,
1033        addr: PeerAddr,
1034        fork_id: Option<ForkId>,
1035    ) {
1036        let ip_addr = addr.tcp().ip();
1037
1038        // Check if the IP is in the allowed ranges (netrestrict)
1039        if !self.ip_filter.is_allowed(&ip_addr) {
1040            trace!(target: "net", ?peer_id, ?ip_addr, "Skipping peer from IP not in allowed ranges");
1041            return
1042        }
1043
1044        if self.ban_list.is_banned(&peer_id, &ip_addr) {
1045            return
1046        }
1047
1048        let mut reset_dial_failures = false;
1049        match self.peers.entry(peer_id) {
1050            Entry::Occupied(mut entry) => {
1051                let peer = entry.get_mut();
1052                reset_dial_failures = peer.addr.tcp() != addr.tcp() ||
1053                    kind.is_some_and(|kind| kind.is_trusted() || kind.is_static());
1054                peer.fork_id = fork_id.map(Box::new);
1055                peer.addr = addr;
1056
1057                if let Some(kind) = kind {
1058                    peer.kind = kind;
1059                }
1060
1061                if peer.state.is_incoming() {
1062                    // now that we have an actual discovered address, for that peer and not just the
1063                    // ip of the incoming connection, we don't need to remove the peer after
1064                    // disconnecting, See `on_incoming_session_established`
1065                    peer.remove_after_disconnect = false;
1066                }
1067            }
1068            Entry::Vacant(entry) => {
1069                trace!(target: "net::peers", ?peer_id, addr=?addr.tcp(), "discovered new node");
1070                let kind = kind.unwrap_or_else(|| {
1071                    if self.trusted_peer_ids.contains(&peer_id) {
1072                        PeerKind::Trusted
1073                    } else {
1074                        PeerKind::Basic
1075                    }
1076                });
1077                let mut peer = Peer::with_kind(addr, kind);
1078                peer.fork_id = fork_id.map(Box::new);
1079                entry.insert(peer);
1080                self.queued_actions.push_back(PeerAction::PeerAdded(peer_id));
1081            }
1082        }
1083
1084        if kind.is_some_and(|kind| kind.is_trusted()) {
1085            // also track the peer in the peer id set
1086            self.trusted_peer_ids.insert(peer_id);
1087        }
1088
1089        if reset_dial_failures {
1090            self.reset_unauthenticated_dial_failures(peer_id);
1091        }
1092    }
1093
1094    /// Called for a peer that was explicitly requested, e.g. via `admin_addPeer`.
1095    ///
1096    /// Same as [`Self::add_peer_kind`], but the peer is dialed right away if there's an outbound
1097    /// slot instead of on the next refill tick like discovered peers.
1098    pub(crate) fn add_requested_peer(
1099        &mut self,
1100        peer_id: PeerId,
1101        kind: Option<PeerKind>,
1102        addr: PeerAddr,
1103    ) {
1104        self.add_peer_kind(peer_id, kind, addr, None);
1105        self.fill_outbound_slots();
1106    }
1107
1108    /// Removes the tracked node from the set.
1109    pub(crate) fn remove_peer(&mut self, peer_id: PeerId) {
1110        let Entry::Occupied(mut entry) = self.peers.entry(peer_id) else { return };
1111        if entry.get().is_trusted() {
1112            return
1113        }
1114        if matches!(
1115            entry.get().state,
1116            PeerConnectionState::DisconnectingIn | PeerConnectionState::DisconnectingOut
1117        ) {
1118            // a previous removal already queued the disconnect and `PeerRemoved`, the entry must
1119            // stay so the session close handler can release its slot
1120            entry.get_mut().remove_after_disconnect = true;
1121            return
1122        }
1123        let mut peer = entry.remove();
1124
1125        trace!(target: "net::peers", ?peer_id, "remove discovered node");
1126        self.queued_actions.push_back(PeerAction::PeerRemoved(peer_id));
1127
1128        if peer.state.is_connected() {
1129            trace!(target: "net::peers", ?peer_id, "disconnecting on remove from discovery");
1130            // we terminate the active session here, but only remove the peer after the session
1131            // was disconnected, this prevents the case where the session is scheduled for
1132            // disconnect but the node is immediately rediscovered, See also
1133            // [`Self::on_disconnected()`]
1134            peer.remove_after_disconnect = true;
1135            peer.state.disconnect();
1136            self.peers.insert(peer_id, peer);
1137            self.queued_actions.push_back(PeerAction::Disconnect {
1138                peer_id,
1139                reason: Some(DisconnectReason::DisconnectRequested),
1140            })
1141        }
1142    }
1143
1144    /// Bans the peer indefinitely and removes it from the peer set.
1145    ///
1146    /// This follows [`Self::remove_peer`] and does not override trusted status. Remove trusted
1147    /// peers from the trusted set before banning them.
1148    pub(crate) fn ban_peer_by_admin(&mut self, peer_id: PeerId) {
1149        if self.trusted_peer_ids.contains(&peer_id) ||
1150            self.peers.get(&peer_id).is_some_and(Peer::is_trusted)
1151        {
1152            return
1153        }
1154
1155        self.remove_peer(peer_id);
1156        self.ban_list.ban_peer(peer_id);
1157    }
1158
1159    /// Removes the peer from the ban list and resets its reputation.
1160    pub(crate) fn unban_peer_by_admin(&mut self, peer_id: PeerId) {
1161        self.ban_list.unban_peer(&peer_id);
1162        if let Some(peer) = self.peers.get_mut(&peer_id) &&
1163            peer.is_banned()
1164        {
1165            peer.unban();
1166            self.queued_actions.push_back(PeerAction::UnBanPeer { peer_id });
1167        }
1168    }
1169
1170    /// Connect to the given peer. NOTE: if the maximum number of outbound sessions is reached,
1171    /// this won't do anything. See `reth_network::SessionManager::dial_outbound`.
1172    #[cfg_attr(not(test), expect(dead_code))]
1173    pub(crate) fn add_and_connect(
1174        &mut self,
1175        peer_id: PeerId,
1176        addr: PeerAddr,
1177        fork_id: Option<ForkId>,
1178    ) {
1179        self.add_and_connect_kind(peer_id, PeerKind::Basic, addr, fork_id)
1180    }
1181
1182    /// Connects a peer and its address with the given kind.
1183    ///
1184    /// Note: This is invoked on demand via an external command received by the manager
1185    pub(crate) fn add_and_connect_kind(
1186        &mut self,
1187        peer_id: PeerId,
1188        kind: PeerKind,
1189        addr: PeerAddr,
1190        fork_id: Option<ForkId>,
1191    ) {
1192        let ip_addr = addr.tcp().ip();
1193
1194        // Check if the IP is in the allowed ranges (netrestrict)
1195        if !self.ip_filter.is_allowed(&ip_addr) {
1196            trace!(target: "net", ?peer_id, ?ip_addr, "Skipping outbound connection to IP not in allowed ranges");
1197            return
1198        }
1199
1200        if self.ban_list.is_banned(&peer_id, &ip_addr) {
1201            return
1202        }
1203
1204        match self.peers.entry(peer_id) {
1205            Entry::Occupied(mut entry) => {
1206                let peer = entry.get_mut();
1207                peer.kind = kind;
1208                peer.fork_id = fork_id.map(Box::new);
1209                peer.addr = addr;
1210                // the given address is a listening endpoint, so the peer is kept unless it is
1211                // already being disconnected by `Self::remove_peer`
1212                if !matches!(
1213                    peer.state,
1214                    PeerConnectionState::DisconnectingIn | PeerConnectionState::DisconnectingOut
1215                ) {
1216                    peer.remove_after_disconnect = false;
1217                }
1218
1219                if peer.state.is_idle() {
1220                    // Try connecting again.
1221                    peer.state = PeerConnectionState::PendingOut;
1222                    self.connection_info.inc_pending_out();
1223                    self.queued_actions
1224                        .push_back(PeerAction::Connect { peer_id, remote_addr: addr.tcp() });
1225                }
1226            }
1227            Entry::Vacant(entry) => {
1228                trace!(target: "net::peers", ?peer_id, addr=?addr.tcp(), "connects new node");
1229                let mut peer = Peer::with_kind(addr, kind);
1230                peer.state = PeerConnectionState::PendingOut;
1231                peer.fork_id = fork_id.map(Box::new);
1232                entry.insert(peer);
1233                self.connection_info.inc_pending_out();
1234                self.queued_actions
1235                    .push_back(PeerAction::Connect { peer_id, remote_addr: addr.tcp() });
1236            }
1237        }
1238
1239        if kind.is_trusted() {
1240            self.trusted_peer_ids.insert(peer_id);
1241        }
1242    }
1243
1244    /// Removes the tracked node from the trusted set.
1245    pub(crate) fn remove_peer_from_trusted_set(&mut self, peer_id: PeerId) {
1246        self.trusted_peers_resolver.remove(peer_id);
1247        self.trusted_peer_ids.remove(&peer_id);
1248        if let Some(peer) = self.peers.get_mut(&peer_id) &&
1249            peer.is_trusted()
1250        {
1251            peer.kind = PeerKind::Basic;
1252        }
1253    }
1254
1255    /// Returns the best idle peer to connect to.
1256    ///
1257    /// Peers that are `trusted` or `static`, see [`PeerKind`], are prioritized as long as they're
1258    /// not currently marked as banned or backed off.
1259    ///
1260    /// Among remaining peers, the one with the highest reputation is selected. When reputation is
1261    /// equal, a peer with a discovered `fork_id` is preferred since it indicates a compatible fork.
1262    ///
1263    /// If `trusted_nodes_only` is enabled, see [`PeersConfig`], then this will only consider
1264    /// `trusted` peers, including registered trusted IDs whose addresses were discovered before
1265    /// hostname resolution. The same restriction applies when `trusted_only` is set.
1266    ///
1267    /// Returns `None` if no peer is available.
1268    fn best_unconnected(&mut self, trusted_only: bool) -> Option<(PeerId, &mut Peer)> {
1269        let mut unconnected = self.peers.iter_mut().filter(|(peer_id, peer)| {
1270            !peer.is_backed_off() &&
1271                !peer.is_banned() &&
1272                peer.state.is_unconnected() &&
1273                (!(self.trusted_nodes_only || trusted_only) ||
1274                    peer.is_trusted() ||
1275                    self.trusted_peer_ids.contains(*peer_id))
1276        });
1277
1278        // keep track of the best peer, if there's one
1279        let mut best_peer = unconnected.next()?;
1280
1281        if best_peer.1.is_trusted() ||
1282            best_peer.1.is_static() ||
1283            self.trusted_peer_ids.contains(best_peer.0)
1284        {
1285            return Some((*best_peer.0, best_peer.1))
1286        }
1287
1288        for maybe_better in unconnected {
1289            // if the peer is trusted or static, return it immediately
1290            if maybe_better.1.is_trusted() ||
1291                maybe_better.1.is_static() ||
1292                self.trusted_peer_ids.contains(maybe_better.0)
1293            {
1294                return Some((*maybe_better.0, maybe_better.1))
1295            }
1296
1297            // prefer higher reputation, break ties by fork_id presence
1298            match maybe_better.1.reputation.cmp(&best_peer.1.reputation) {
1299                std::cmp::Ordering::Greater => best_peer = maybe_better,
1300                std::cmp::Ordering::Equal
1301                    if maybe_better.1.fork_id.is_some() && best_peer.1.fork_id.is_none() =>
1302                {
1303                    best_peer = maybe_better
1304                }
1305                _ => {}
1306            }
1307        }
1308        Some((*best_peer.0, best_peer.1))
1309    }
1310
1311    /// Disconnects one eligible peer (inbound or outbound) to open a slot for new nodes,
1312    /// mirroring Geth's peer dropper logic:
1313    /// <https://github.com/ethereum/go-ethereum/blob/c5c75977ab55e4d7ea6147cc0e221b588e5e3754/eth/dropper.go#L106-L138>
1314    ///
1315    /// A peer is eligible when its pool (inbound or outbound) is at capacity, the peer is not
1316    /// trusted or static, and it has been connected for at least [`PEER_ROTATION_MIN_UPTIME`].
1317    fn try_rotate_peer(&mut self) {
1318        let outbound_at_capacity = self.connection_info.is_outbound_at_capacity();
1319        let inbound_at_capacity = self.connection_info.is_inbound_at_capacity();
1320
1321        if !outbound_at_capacity && !inbound_at_capacity {
1322            return
1323        }
1324
1325        let now = std::time::Instant::now();
1326
1327        let candidates = self
1328            .peers
1329            .iter()
1330            .filter_map(|(peer_id, peer)| {
1331                let eligible = match peer.state {
1332                    PeerConnectionState::Out => outbound_at_capacity,
1333                    PeerConnectionState::In => inbound_at_capacity,
1334                    _ => false,
1335                };
1336                (eligible &&
1337                    !peer.is_trusted() &&
1338                    !peer.is_static() &&
1339                    !self.trusted_peer_ids.contains(peer_id) &&
1340                    peer.connected_for_at_least(now, PEER_ROTATION_MIN_UPTIME))
1341                .then_some(*peer_id)
1342            })
1343            .collect::<Vec<_>>();
1344
1345        if candidates.is_empty() {
1346            return
1347        }
1348        let peer_id = candidates[rand::rng().random_range(0..candidates.len())];
1349
1350        trace!(target: "net::peers", ?peer_id, "rotating peer to open slot for new nodes");
1351
1352        self.queued_actions.push_back(PeerAction::Disconnect {
1353            peer_id,
1354            reason: Some(DisconnectReason::UselessPeer),
1355        });
1356    }
1357
1358    /// If there's capacity for new outbound connections, this will queue new
1359    /// [`PeerAction::Connect`] actions.
1360    ///
1361    /// New connections are only initiated, if slots are available and appropriate peers are
1362    /// available.
1363    fn fill_outbound_slots(&mut self) {
1364        self.tick();
1365
1366        if !self.net_connection_state.is_active() {
1367            // nothing to fill
1368            return
1369        }
1370
1371        // as long as there are slots available fill them with the best peers
1372        while self.connection_info.has_out_dial_capacity() {
1373            // Trusted peers are dialed even when all outbound slots are taken, so discovered
1374            // peers can never crowd them out; only the concurrent dial limit applies to them.
1375            let has_out_capacity = self.connection_info.has_out_capacity();
1376            let action = {
1377                let Some((peer_id, peer)) = self.best_unconnected(!has_out_capacity) else { break };
1378
1379                trace!(target: "net::peers", ?peer_id, addr=?peer.addr, "schedule outbound connection");
1380
1381                peer.state = PeerConnectionState::PendingOut;
1382                PeerAction::Connect { peer_id, remote_addr: peer.addr.tcp() }
1383            };
1384
1385            self.connection_info.inc_pending_out();
1386
1387            self.queued_actions.push_back(action);
1388        }
1389    }
1390
1391    fn on_resolved_peer(&mut self, peer_id: PeerId, new_record: NodeRecord) {
1392        if !self.trusted_peer_ids.contains(&peer_id) {
1393            trace!(target: "net::peers", ?peer_id, "Ignoring resolved trusted peer after removal");
1394            return
1395        }
1396
1397        if !self.ip_filter.is_allowed(&new_record.address) {
1398            trace!(target: "net::peers", ?peer_id, address=?new_record.address, "Ignoring resolved trusted peer address not in allowed ranges");
1399            return
1400        }
1401
1402        let new_addr = PeerAddr::new_with_ports(
1403            new_record.address,
1404            new_record.tcp_port,
1405            Some(new_record.udp_port),
1406        );
1407
1408        if let Some(peer) = self.peers.get_mut(&peer_id) {
1409            // The peer may have been added as basic by discovery or an inbound session before the
1410            // first successful resolution.
1411            peer.kind = PeerKind::Trusted;
1412            if peer.state.is_incoming() {
1413                // the resolved address replaces the inbound one, see `add_peer_kind`
1414                peer.remove_after_disconnect = false;
1415            }
1416            if peer.addr != new_addr {
1417                peer.addr = new_addr;
1418                trace!(target: "net::peers", ?peer_id, addr=?peer.addr, "Updated resolved trusted peer address");
1419            }
1420        } else {
1421            trace!(target: "net::peers", ?peer_id, ?new_addr, "Adding trusted peer after first successful resolution");
1422            self.add_peer_kind(peer_id, Some(PeerKind::Trusted), new_addr, None);
1423        }
1424    }
1425
1426    /// Keeps track of network state changes.
1427    pub const fn on_network_state_change(&mut self, state: NetworkConnectionState) {
1428        self.net_connection_state = state;
1429    }
1430
1431    /// Returns the current network connection state.
1432    pub const fn connection_state(&self) -> &NetworkConnectionState {
1433        &self.net_connection_state
1434    }
1435
1436    /// Sets `net_connection_state` to `ShuttingDown`.
1437    pub const fn on_shutdown(&mut self) {
1438        self.net_connection_state = NetworkConnectionState::ShuttingDown;
1439    }
1440
1441    /// Returns how long a peer or ip is banned for.
1442    pub(crate) const fn ban_duration(&self) -> Duration {
1443        self.ban_duration
1444    }
1445
1446    /// Advances the state.
1447    ///
1448    /// Event hooks invoked externally may trigger a new [`PeerAction`] that are buffered until
1449    /// [`PeersManager`] is polled.
1450    pub fn poll(&mut self, cx: &mut Context<'_>) -> Poll<PeerAction> {
1451        loop {
1452            // drain buffered actions
1453            if let Some(action) = self.queued_actions.pop_front() {
1454                return Poll::Ready(action)
1455            }
1456
1457            while let Poll::Ready(Some(cmd)) = self.handle_rx.poll_next_unpin(cx) {
1458                match cmd {
1459                    PeerCommand::Add(peer_id, addr) => {
1460                        self.add_requested_peer(peer_id, None, PeerAddr::from_tcp(addr));
1461                    }
1462                    PeerCommand::Remove(peer) => self.remove_peer(peer),
1463                    PeerCommand::ReputationChange(peer_id, rep) => {
1464                        self.apply_reputation_change(&peer_id, rep)
1465                    }
1466                    PeerCommand::GetPeer(peer, tx) => {
1467                        let _ = tx.send(self.peers.get(&peer).cloned());
1468                    }
1469                    PeerCommand::GetPeers(tx) => {
1470                        let _ = tx.send(self.iter_peers().collect());
1471                    }
1472                }
1473            }
1474
1475            if self.release_interval.poll_tick(cx).is_ready() {
1476                let now = std::time::Instant::now();
1477                let (_, unbanned_peers) = self.ban_list.evict(now);
1478
1479                for peer_id in unbanned_peers {
1480                    if let Some(peer) = self.peers.get_mut(&peer_id) {
1481                        peer.unban();
1482                        self.queued_actions.push_back(PeerAction::UnBanPeer { peer_id });
1483                    }
1484                }
1485
1486                // clear the backoff list of expired backoffs, and mark the relevant peers as
1487                // ready to be dialed
1488                self.backed_off_peers.retain(|peer_id, until| {
1489                    if now > *until {
1490                        if let Some(peer) = self.peers.get_mut(peer_id) {
1491                            peer.backed_off = false;
1492                        }
1493                        return false
1494                    }
1495                    true
1496                })
1497            }
1498
1499            while self.refill_slots_interval.poll_tick(cx).is_ready() {
1500                self.fill_outbound_slots();
1501            }
1502
1503            if let Poll::Ready((peer_id, new_record)) = self.trusted_peers_resolver.poll(cx) {
1504                self.on_resolved_peer(peer_id, new_record);
1505            }
1506
1507            // Poll the jittered rotation timer and rotate one eligible peer when ready.
1508            let rotation_ready = self
1509                .peer_rotation_sleep
1510                .as_mut()
1511                .is_some_and(|sleep| sleep.as_mut().poll(cx).is_ready());
1512            if rotation_ready {
1513                self.try_rotate_peer();
1514                if let Some((mean, sleep)) =
1515                    self.peer_rotation_mean.zip(self.peer_rotation_sleep.as_mut())
1516                {
1517                    sleep
1518                        .as_mut()
1519                        .reset(tokio::time::Instant::now() + jitter_rotation_interval(mean));
1520                }
1521            }
1522
1523            if self.queued_actions.is_empty() {
1524                return Poll::Pending
1525            }
1526        }
1527    }
1528}
1529
1530impl Default for PeersManager {
1531    fn default() -> Self {
1532        Self::new(Default::default())
1533    }
1534}
1535
1536/// Tracks stats about connected nodes
1537#[derive(Debug, Clone, PartialEq, Eq, Default)]
1538pub struct ConnectionInfo {
1539    /// Counter for currently occupied slots for active outbound connections.
1540    num_outbound: usize,
1541    /// Counter for pending outbound connections.
1542    num_pending_out: usize,
1543    /// Counter for currently occupied slots for active inbound connections.
1544    num_inbound: usize,
1545    /// Counter for pending inbound connections.
1546    num_pending_in: usize,
1547    /// Restrictions on number of connections.
1548    config: ConnectionsConfig,
1549}
1550
1551// === impl ConnectionInfo ===
1552
1553impl ConnectionInfo {
1554    /// Returns a new [`ConnectionInfo`] with the given config.
1555    const fn new(config: ConnectionsConfig) -> Self {
1556        Self { config, num_outbound: 0, num_pending_out: 0, num_inbound: 0, num_pending_in: 0 }
1557    }
1558
1559    ///  Returns `true` if there's still capacity to perform an outgoing connection.
1560    const fn has_out_capacity(&self) -> bool {
1561        self.has_out_dial_capacity() &&
1562            self.num_pending_out < self.config.max_outbound.saturating_sub(self.num_outbound)
1563    }
1564
1565    /// Returns `true` if all active outbound slots are occupied (ignoring pending dials).
1566    const fn is_outbound_at_capacity(&self) -> bool {
1567        self.num_outbound >= self.config.max_outbound
1568    }
1569
1570    /// Returns `true` if all active inbound slots are occupied.
1571    const fn is_inbound_at_capacity(&self) -> bool {
1572        self.num_inbound >= self.config.max_inbound
1573    }
1574
1575    ///  Returns `true` if there's still capacity to accept a new incoming connection.
1576    const fn has_in_capacity(&self) -> bool {
1577        self.num_inbound < self.config.max_inbound
1578    }
1579
1580    /// Returns `true` if we can handle an additional incoming pending connection.
1581    const fn has_in_pending_capacity(&self) -> bool {
1582        self.num_pending_in < self.config.max_inbound
1583    }
1584
1585    /// Returns `true` if another outgoing dial can be started without exceeding the concurrent
1586    /// dial limit.
1587    const fn has_out_dial_capacity(&self) -> bool {
1588        self.num_pending_out < self.config.max_concurrent_outbound_dials
1589    }
1590
1591    const fn decr_state(&mut self, state: PeerConnectionState) {
1592        match state {
1593            PeerConnectionState::Idle => {}
1594            PeerConnectionState::DisconnectingIn | PeerConnectionState::In => self.decr_in(),
1595            PeerConnectionState::DisconnectingOut | PeerConnectionState::Out => self.decr_out(),
1596            PeerConnectionState::PendingOut => self.decr_pending_out(),
1597        }
1598    }
1599
1600    const fn decr_out(&mut self) {
1601        self.num_outbound -= 1;
1602    }
1603
1604    const fn inc_out(&mut self) {
1605        self.num_outbound += 1;
1606    }
1607
1608    const fn inc_pending_out(&mut self) {
1609        self.num_pending_out += 1;
1610    }
1611
1612    const fn inc_in(&mut self) {
1613        self.num_inbound += 1;
1614    }
1615
1616    const fn inc_pending_in(&mut self) {
1617        self.num_pending_in += 1;
1618    }
1619
1620    const fn decr_in(&mut self) {
1621        self.num_inbound -= 1;
1622    }
1623
1624    const fn decr_pending_out(&mut self) {
1625        self.num_pending_out -= 1;
1626    }
1627
1628    const fn decr_pending_in(&mut self) {
1629        self.num_pending_in -= 1;
1630    }
1631}
1632
1633/// Actions the peer manager can trigger.
1634#[derive(Debug)]
1635pub enum PeerAction {
1636    /// Start a new connection to a peer.
1637    Connect {
1638        /// The peer to connect to.
1639        peer_id: PeerId,
1640        /// Where to reach the node
1641        remote_addr: SocketAddr,
1642    },
1643    /// Disconnect an existing connection.
1644    Disconnect {
1645        /// The peer ID of the established connection.
1646        peer_id: PeerId,
1647        /// An optional reason for the disconnect.
1648        reason: Option<DisconnectReason>,
1649    },
1650    /// Disconnect an existing incoming connection, because the peers reputation is below the
1651    /// banned threshold or is on the [`BanList`]
1652    DisconnectBannedIncoming {
1653        /// The peer ID of the established connection.
1654        peer_id: PeerId,
1655    },
1656    /// Disconnect an untrusted incoming connection when trust-node-only is enabled.
1657    DisconnectUntrustedIncoming {
1658        /// The peer ID.
1659        peer_id: PeerId,
1660    },
1661    /// Ban the peer in discovery.
1662    DiscoveryBanPeerId {
1663        /// The peer ID.
1664        peer_id: PeerId,
1665        /// The IP address.
1666        ip_addr: IpAddr,
1667    },
1668    /// Ban the IP in discovery.
1669    DiscoveryBanIp {
1670        /// The IP address.
1671        ip_addr: IpAddr,
1672    },
1673    /// Ban the peer temporarily
1674    BanPeer {
1675        /// The peer ID.
1676        peer_id: PeerId,
1677    },
1678    /// Unban the peer temporarily
1679    UnBanPeer {
1680        /// The peer ID.
1681        peer_id: PeerId,
1682    },
1683    /// Emit peerAdded event
1684    PeerAdded(PeerId),
1685    /// Emit peerRemoved event
1686    PeerRemoved(PeerId),
1687}
1688
1689/// Error thrown when an incoming connection is rejected right away
1690#[derive(Debug, Error, PartialEq, Eq)]
1691pub enum InboundConnectionError {
1692    /// The remote's ip address is banned
1693    IpBanned,
1694    /// No capacity for new inbound connections
1695    ExceedsCapacity,
1696}
1697
1698impl Display for InboundConnectionError {
1699    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1700        write!(f, "{self:?}")
1701    }
1702}
1703
1704/// The reason a peer was backed off.
1705#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1706pub enum BackoffReason {
1707    /// The remote peer responded with `TooManyPeers` (0x04).
1708    TooManyPeers,
1709    /// The session was gracefully closed and we're backing off briefly.
1710    GracefulClose,
1711    /// A connection or protocol-level error occurred.
1712    ConnectionError,
1713}
1714
1715impl BackoffReason {
1716    /// Derives the backoff reason from an optional [`DisconnectReason`].
1717    pub const fn from_disconnect(reason: Option<DisconnectReason>) -> Self {
1718        match reason {
1719            Some(DisconnectReason::TooManyPeers) => Self::TooManyPeers,
1720            _ => Self::ConnectionError,
1721        }
1722    }
1723}
1724
1725/// Returns a random duration uniformly distributed in `[mean * 3/5, mean * 7/5]`.
1726///
1727/// With the default 5-minute mean this gives `[3 min, 7 min]`, matching Geth's peer dropper:
1728/// <https://github.com/ethereum/go-ethereum/blob/c5c75977ab55e4d7ea6147cc0e221b588e5e3754/eth/dropper.go#L32-L36>
1729fn jitter_rotation_interval(mean: Duration) -> Duration {
1730    let min_nanos = (mean * 3 / 5).as_nanos() as u64;
1731    let max_nanos = (mean * 7 / 5).as_nanos() as u64;
1732    Duration::from_nanos(rand::rng().random_range(min_nanos..=max_nanos))
1733}
1734
1735#[cfg(test)]
1736mod tests {
1737    use super::*;
1738    use alloy_primitives::B512;
1739    use reth_ecies::ECIESErrorImpl;
1740    use reth_eth_wire::{
1741        errors::{EthHandshakeError, EthStreamError, P2PHandshakeError, P2PStreamError},
1742        DisconnectReason,
1743    };
1744    use reth_ethereum_forks::{ForkHash, ForkId};
1745    use reth_net_banlist::BanList;
1746    use reth_network_api::Direction;
1747    use reth_network_peers::{NodeRecord, PeerId, TrustedPeer};
1748    use reth_network_types::{
1749        peers::reputation::{BANNED_REPUTATION, DEFAULT_REPUTATION},
1750        BackoffKind, Peer, PeerKind, ReputationChangeKind,
1751    };
1752    use std::{
1753        future::{poll_fn, Future},
1754        io,
1755        net::{IpAddr, Ipv4Addr, SocketAddr},
1756        pin::Pin,
1757        task::{Context, Poll, Waker},
1758        time::Duration,
1759    };
1760    use url::Host;
1761
1762    use crate::{
1763        error::SessionError,
1764        peers::{
1765            ConnectionInfo, InboundConnectionError, PeerAction, PeerAddr, PeerBackoffDurations,
1766            PeerConnectionState, MAX_INCOMING_IP_THROTTLE_ENTRIES,
1767        },
1768        session::PendingSessionHandshakeError,
1769        PeersConfig,
1770    };
1771    use reth_net_banlist::IpFilter;
1772
1773    struct PeerActionFuture<'a> {
1774        peers: &'a mut PeersManager,
1775    }
1776
1777    impl Future for PeerActionFuture<'_> {
1778        type Output = PeerAction;
1779
1780        fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1781            self.get_mut().peers.poll(cx)
1782        }
1783    }
1784
1785    macro_rules! event {
1786        ($peers:expr) => {
1787            PeerActionFuture { peers: &mut $peers }.await
1788        };
1789    }
1790
1791    fn set_connected_at(
1792        peers: &mut PeersManager,
1793        peer_id: PeerId,
1794        connected_at: std::time::Instant,
1795    ) {
1796        peers.peers.get_mut(&peer_id).expect("peer exists").connected_at = Some(connected_at);
1797    }
1798
1799    /// Polls the manager once without waiting for an action.
1800    fn poll_now(peers: &mut PeersManager) -> Poll<PeerAction> {
1801        peers.poll(&mut Context::from_waker(Waker::noop()))
1802    }
1803
1804    #[tokio::test]
1805    async fn test_insert() {
1806        let peer = PeerId::random();
1807        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
1808        let mut peers = PeersManager::default();
1809        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
1810
1811        match event!(peers) {
1812            PeerAction::PeerAdded(peer_id) => {
1813                assert_eq!(peer_id, peer);
1814            }
1815            _ => unreachable!(),
1816        }
1817        match event!(peers) {
1818            PeerAction::Connect { peer_id, remote_addr } => {
1819                assert_eq!(peer_id, peer);
1820                assert_eq!(remote_addr, socket_addr);
1821            }
1822            _ => unreachable!(),
1823        }
1824
1825        let (record, _) = peers.peer_by_id(peer).unwrap();
1826        assert_eq!(record.tcp_addr(), socket_addr);
1827        assert_eq!(record.udp_addr(), socket_addr);
1828    }
1829
1830    #[tokio::test]
1831    async fn test_insert_udp() {
1832        let peer = PeerId::random();
1833        let tcp_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
1834        let udp_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
1835        let mut peers = PeersManager::default();
1836        peers.add_peer(peer, PeerAddr::new(tcp_addr, Some(udp_addr)), None);
1837
1838        match event!(peers) {
1839            PeerAction::PeerAdded(peer_id) => {
1840                assert_eq!(peer_id, peer);
1841            }
1842            _ => unreachable!(),
1843        }
1844        match event!(peers) {
1845            PeerAction::Connect { peer_id, remote_addr } => {
1846                assert_eq!(peer_id, peer);
1847                assert_eq!(remote_addr, tcp_addr);
1848            }
1849            _ => unreachable!(),
1850        }
1851
1852        let (record, _) = peers.peer_by_id(peer).unwrap();
1853        assert_eq!(record.tcp_addr(), tcp_addr);
1854        assert_eq!(record.udp_addr(), udp_addr);
1855    }
1856
1857    #[tokio::test]
1858    async fn test_ban() {
1859        let peer = PeerId::random();
1860        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
1861        let mut peers = PeersManager::default();
1862        peers.ban_peer(peer);
1863        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
1864
1865        match event!(peers) {
1866            PeerAction::BanPeer { peer_id } => {
1867                assert_eq!(peer_id, peer);
1868            }
1869            _ => unreachable!(),
1870        }
1871
1872        poll_fn(|cx| {
1873            assert!(peers.poll(cx).is_pending());
1874            Poll::Ready(())
1875        })
1876        .await;
1877    }
1878
1879    #[tokio::test]
1880    async fn test_unban() {
1881        let peer = PeerId::random();
1882        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
1883        let mut peers = PeersManager::default();
1884        peers.ban_peer(peer);
1885        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
1886
1887        match event!(peers) {
1888            PeerAction::BanPeer { peer_id } => {
1889                assert_eq!(peer_id, peer);
1890            }
1891            _ => unreachable!(),
1892        }
1893
1894        poll_fn(|cx| {
1895            assert!(peers.poll(cx).is_pending());
1896            Poll::Ready(())
1897        })
1898        .await;
1899
1900        peers.unban_peer(peer);
1901
1902        match event!(peers) {
1903            PeerAction::UnBanPeer { peer_id } => {
1904                assert_eq!(peer_id, peer);
1905            }
1906            _ => unreachable!(),
1907        }
1908
1909        poll_fn(|cx| {
1910            assert!(peers.poll(cx).is_pending());
1911            Poll::Ready(())
1912        })
1913        .await;
1914    }
1915
1916    #[tokio::test]
1917    async fn test_admin_ban_removes_peer_and_bans_indefinitely() {
1918        let peer = PeerId::random();
1919        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
1920        let mut peers = PeersManager::default();
1921        peers.peers.insert(peer, Peer::new(PeerAddr::from_tcp(socket_addr)));
1922
1923        peers.ban_peer_by_admin(peer);
1924
1925        assert!(peers.ban_list.is_banned_peer(&peer));
1926        assert!(peers.peer_by_id(peer).is_none());
1927
1928        match peers.queued_actions.pop_front() {
1929            Some(PeerAction::PeerRemoved(peer_id)) => assert_eq!(peer_id, peer),
1930            other => panic!("unexpected action: {other:?}"),
1931        }
1932
1933        let (_, unbanned_peers) =
1934            peers.ban_list.evict(std::time::Instant::now() + Duration::from_secs(1));
1935        assert!(unbanned_peers.is_empty());
1936    }
1937
1938    #[tokio::test]
1939    async fn test_admin_ban_does_not_override_trusted_peer() {
1940        let peer = PeerId::random();
1941        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
1942        let mut peers = PeersManager::default();
1943        peers.peers.insert(peer, Peer::trusted(PeerAddr::from_tcp(socket_addr)));
1944
1945        peers.ban_peer_by_admin(peer);
1946
1947        assert!(!peers.ban_list.is_banned_peer(&peer));
1948        assert!(peers.peer_by_id(peer).is_some());
1949        assert!(peers.queued_actions.is_empty());
1950    }
1951
1952    #[tokio::test]
1953    async fn test_admin_unban_resets_reputation() {
1954        let peer = PeerId::random();
1955        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
1956        let mut peers = PeersManager::default();
1957        let mut peer_info = Peer::new(PeerAddr::from_tcp(socket_addr));
1958        peer_info.reputation = i32::MIN;
1959        peers.peers.insert(peer, peer_info);
1960        peers.ban_list.ban_peer(peer);
1961        assert!(peers.peers.get(&peer).is_some_and(Peer::is_banned));
1962
1963        peers.unban_peer_by_admin(peer);
1964
1965        assert!(!peers.ban_list.is_banned_peer(&peer));
1966        assert!(!peers.peers.get(&peer).is_some_and(Peer::is_banned));
1967        assert!(matches!(
1968            peers.queued_actions.pop_front(),
1969            Some(PeerAction::UnBanPeer { peer_id }) if peer_id == peer
1970        ));
1971    }
1972
1973    #[tokio::test]
1974    async fn test_backoff_on_busy() {
1975        let peer = PeerId::random();
1976        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
1977
1978        let mut peers = PeersManager::new(PeersConfig::test());
1979        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
1980
1981        match event!(peers) {
1982            PeerAction::PeerAdded(peer_id) => {
1983                assert_eq!(peer_id, peer);
1984            }
1985            _ => unreachable!(),
1986        }
1987        match event!(peers) {
1988            PeerAction::Connect { peer_id, .. } => {
1989                assert_eq!(peer_id, peer);
1990            }
1991            _ => unreachable!(),
1992        }
1993
1994        poll_fn(|cx| {
1995            assert!(peers.poll(cx).is_pending());
1996            Poll::Ready(())
1997        })
1998        .await;
1999
2000        peers.on_active_session_dropped(
2001            &socket_addr,
2002            &peer,
2003            &EthStreamError::P2PStreamError(P2PStreamError::Disconnected(
2004                DisconnectReason::TooManyPeers,
2005            )),
2006        );
2007
2008        poll_fn(|cx| {
2009            assert!(peers.poll(cx).is_pending());
2010            Poll::Ready(())
2011        })
2012        .await;
2013
2014        assert!(peers.backed_off_peers.contains_key(&peer));
2015        assert!(peers.peers.get(&peer).unwrap().is_backed_off());
2016
2017        tokio::time::sleep(peers.backoff_durations.low).await;
2018
2019        match event!(peers) {
2020            PeerAction::Connect { peer_id, .. } => {
2021                assert_eq!(peer_id, peer);
2022            }
2023            _ => unreachable!(),
2024        }
2025
2026        assert!(!peers.backed_off_peers.contains_key(&peer));
2027        assert!(!peers.peers.get(&peer).unwrap().is_backed_off());
2028    }
2029
2030    #[tokio::test]
2031    async fn test_backoff_on_no_response() {
2032        let peer = PeerId::random();
2033        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2034
2035        let backoff_durations = PeerBackoffDurations::test();
2036        let config = PeersConfig { backoff_durations, ..PeersConfig::test() };
2037        let mut peers = PeersManager::new(config);
2038        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2039
2040        match event!(peers) {
2041            PeerAction::PeerAdded(peer_id) => {
2042                assert_eq!(peer_id, peer);
2043            }
2044            _ => unreachable!(),
2045        }
2046        match event!(peers) {
2047            PeerAction::Connect { peer_id, .. } => {
2048                assert_eq!(peer_id, peer);
2049            }
2050            _ => unreachable!(),
2051        }
2052
2053        poll_fn(|cx| {
2054            assert!(peers.poll(cx).is_pending());
2055            Poll::Ready(())
2056        })
2057        .await;
2058
2059        peers.on_outgoing_pending_session_dropped(
2060            &socket_addr,
2061            &peer,
2062            &PendingSessionHandshakeError::Eth(EthStreamError::EthHandshakeError(
2063                EthHandshakeError::NoResponse,
2064            )),
2065        );
2066
2067        poll_fn(|cx| {
2068            assert!(peers.poll(cx).is_pending());
2069            Poll::Ready(())
2070        })
2071        .await;
2072
2073        assert!(peers.backed_off_peers.contains_key(&peer));
2074        assert!(peers.peers.get(&peer).unwrap().is_backed_off());
2075
2076        tokio::time::sleep(backoff_durations.high).await;
2077
2078        match event!(peers) {
2079            PeerAction::Connect { peer_id, .. } => {
2080                assert_eq!(peer_id, peer);
2081            }
2082            _ => unreachable!(),
2083        }
2084
2085        assert!(!peers.backed_off_peers.contains_key(&peer));
2086        assert!(!peers.peers.get(&peer).unwrap().is_backed_off());
2087    }
2088
2089    #[tokio::test]
2090    async fn test_low_backoff() {
2091        let peer = PeerId::random();
2092        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2093        let config = PeersConfig::test();
2094        let mut peers = PeersManager::new(config);
2095        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2096        let peer_struct = peers.peers.get_mut(&peer).unwrap();
2097
2098        let backoff_timestamp = peers
2099            .backoff_durations
2100            .backoff_until(BackoffKind::Low, peer_struct.severe_backoff_counter);
2101
2102        let expected = std::time::Instant::now() + peers.backoff_durations.low;
2103        assert!(backoff_timestamp <= expected);
2104    }
2105
2106    #[tokio::test]
2107    async fn test_multiple_backoff_calculations() {
2108        let peer = PeerId::random();
2109        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2110        let config = PeersConfig::default();
2111        let mut peers = PeersManager::new(config);
2112        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2113        let peer_struct = peers.peers.get_mut(&peer).unwrap();
2114
2115        // Simulate a peer that was already backed off once
2116        peer_struct.severe_backoff_counter = 1;
2117
2118        let now = std::time::Instant::now();
2119
2120        // Simulate the increment that happens in on_connection_failure
2121        peer_struct.severe_backoff_counter += 1;
2122        // Get official backoff time
2123        let backoff_time = peers
2124            .backoff_durations
2125            .backoff_until(BackoffKind::High, peer_struct.severe_backoff_counter);
2126
2127        // Duration of the backoff should be 2 * 15 minutes = 30 minutes
2128        let backoff_duration = std::time::Duration::new(30 * 60, 0);
2129
2130        // We can't use assert_eq! since there is a very small diff in the nano secs
2131        // Usually it is 1800s != 1799.9999996s
2132        assert!(backoff_time.duration_since(now) > backoff_duration);
2133    }
2134
2135    #[tokio::test]
2136    async fn test_ban_on_active_drop() {
2137        let peer = PeerId::random();
2138        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2139        let mut peers = PeersManager::default();
2140        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2141
2142        match event!(peers) {
2143            PeerAction::PeerAdded(peer_id) => {
2144                assert_eq!(peer_id, peer);
2145            }
2146            _ => unreachable!(),
2147        }
2148        match event!(peers) {
2149            PeerAction::Connect { peer_id, .. } => {
2150                assert_eq!(peer_id, peer);
2151            }
2152            _ => unreachable!(),
2153        }
2154
2155        poll_fn(|cx| {
2156            assert!(peers.poll(cx).is_pending());
2157            Poll::Ready(())
2158        })
2159        .await;
2160
2161        peers.on_active_session_dropped(
2162            &socket_addr,
2163            &peer,
2164            &EthStreamError::P2PStreamError(P2PStreamError::Disconnected(
2165                DisconnectReason::ProtocolBreach,
2166            )),
2167        );
2168
2169        match event!(peers) {
2170            PeerAction::PeerRemoved(peer_id) => {
2171                assert_eq!(peer_id, peer);
2172            }
2173            _ => unreachable!(),
2174        }
2175        match event!(peers) {
2176            PeerAction::BanPeer { peer_id } => {
2177                assert_eq!(peer_id, peer);
2178            }
2179            _ => unreachable!(),
2180        }
2181
2182        poll_fn(|cx| {
2183            assert!(peers.poll(cx).is_pending());
2184            Poll::Ready(())
2185        })
2186        .await;
2187
2188        assert!(!peers.peers.contains_key(&peer));
2189    }
2190
2191    #[tokio::test]
2192    async fn test_remove_on_max_backoff_count() {
2193        let peer = PeerId::random();
2194        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2195        let config = PeersConfig::test();
2196        let mut peers = PeersManager::new(config.clone());
2197        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2198        let peer_struct = peers.peers.get_mut(&peer).unwrap();
2199
2200        // Simulate a peer that was already backed off once
2201        peer_struct.severe_backoff_counter = config.max_backoff_count;
2202
2203        match event!(peers) {
2204            PeerAction::PeerAdded(peer_id) => {
2205                assert_eq!(peer_id, peer);
2206            }
2207            _ => unreachable!(),
2208        }
2209        match event!(peers) {
2210            PeerAction::Connect { peer_id, .. } => {
2211                assert_eq!(peer_id, peer);
2212            }
2213            _ => unreachable!(),
2214        }
2215
2216        poll_fn(|cx| {
2217            assert!(peers.poll(cx).is_pending());
2218            Poll::Ready(())
2219        })
2220        .await;
2221
2222        peers.on_outgoing_connection_failure(
2223            &socket_addr,
2224            &peer,
2225            &io::Error::new(io::ErrorKind::ConnectionRefused, "peer unreachable"),
2226        );
2227
2228        match event!(peers) {
2229            PeerAction::PeerRemoved(peer_id) => {
2230                assert_eq!(peer_id, peer);
2231            }
2232            _ => unreachable!(),
2233        }
2234
2235        poll_fn(|cx| {
2236            assert!(peers.poll(cx).is_pending());
2237            Poll::Ready(())
2238        })
2239        .await;
2240
2241        assert!(!peers.peers.contains_key(&peer));
2242    }
2243
2244    #[tokio::test]
2245    async fn test_remove_disconnecting_peer_on_active_drop() {
2246        let peer = PeerId::random();
2247        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2248        let mut peers = PeersManager::default();
2249        peers.add_and_connect(peer, PeerAddr::from_tcp(socket_addr), None);
2250        peers.on_active_outgoing_established(peer);
2251
2252        peers.remove_peer(peer);
2253        assert_eq!(peers.peers.get(&peer).unwrap().state, PeerConnectionState::DisconnectingOut);
2254
2255        peers.on_active_session_dropped(
2256            &socket_addr,
2257            &peer,
2258            &EthStreamError::P2PStreamError(P2PStreamError::Disconnected(
2259                DisconnectReason::TooManyPeers,
2260            )),
2261        );
2262
2263        assert!(!peers.peers.contains_key(&peer));
2264        assert_eq!(peers.connection_info.num_outbound, 0);
2265    }
2266
2267    #[tokio::test]
2268    async fn test_keep_banned_static_peer_on_active_drop() {
2269        let peer = PeerId::random();
2270        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2271        let mut peers = PeersManager::default();
2272        peers.add_and_connect_kind(peer, PeerKind::Static, PeerAddr::from_tcp(socket_addr), None);
2273        peers.on_active_outgoing_established(peer);
2274
2275        peers.peers.get_mut(&peer).unwrap().reputation = BANNED_REPUTATION;
2276        peers.apply_reputation_change(&peer, ReputationChangeKind::BadMessage);
2277        assert_eq!(peers.peers.get(&peer).unwrap().state, PeerConnectionState::DisconnectingOut);
2278
2279        peers.on_active_session_dropped(
2280            &socket_addr,
2281            &peer,
2282            &EthStreamError::P2PStreamError(P2PStreamError::Disconnected(
2283                DisconnectReason::TooManyPeers,
2284            )),
2285        );
2286
2287        assert_eq!(peers.peers.get(&peer).unwrap().state, PeerConnectionState::Idle);
2288        assert_eq!(peers.connection_info.num_outbound, 0);
2289    }
2290
2291    #[tokio::test]
2292    async fn test_ban_on_pending_drop() {
2293        let peer = PeerId::random();
2294        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2295        let mut peers = PeersManager::default();
2296        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2297
2298        match event!(peers) {
2299            PeerAction::PeerAdded(peer_id) => {
2300                assert_eq!(peer_id, peer);
2301            }
2302            _ => unreachable!(),
2303        }
2304        match event!(peers) {
2305            PeerAction::Connect { peer_id, .. } => {
2306                assert_eq!(peer_id, peer);
2307            }
2308            _ => unreachable!(),
2309        }
2310
2311        poll_fn(|cx| {
2312            assert!(peers.poll(cx).is_pending());
2313            Poll::Ready(())
2314        })
2315        .await;
2316
2317        peers.on_outgoing_pending_session_dropped(
2318            &socket_addr,
2319            &peer,
2320            &PendingSessionHandshakeError::Eth(EthStreamError::P2PStreamError(
2321                P2PStreamError::Disconnected(DisconnectReason::UselessPeer),
2322            )),
2323        );
2324
2325        match event!(peers) {
2326            PeerAction::PeerRemoved(peer_id) => {
2327                assert_eq!(peer_id, peer);
2328            }
2329            _ => unreachable!(),
2330        }
2331        match event!(peers) {
2332            PeerAction::BanPeer { peer_id } => {
2333                assert_eq!(peer_id, peer);
2334            }
2335            _ => unreachable!(),
2336        }
2337
2338        poll_fn(|cx| {
2339            assert!(peers.poll(cx).is_pending());
2340            Poll::Ready(())
2341        })
2342        .await;
2343
2344        assert!(!peers.peers.contains_key(&peer));
2345    }
2346
2347    #[tokio::test]
2348    async fn test_internally_closed_incoming() {
2349        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2350        let mut peers = PeersManager::default();
2351
2352        assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2353        assert_eq!(peers.connection_info.num_pending_in, 1);
2354        peers.on_incoming_pending_session_rejected_internally();
2355        assert_eq!(peers.connection_info.num_pending_in, 0);
2356    }
2357
2358    #[tokio::test]
2359    async fn test_reject_incoming_at_pending_capacity() {
2360        let mut peers = PeersManager::default();
2361
2362        for count in 1..=peers.connection_info.config.max_inbound {
2363            let socket_addr =
2364                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, count as u8)), 8008);
2365            assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2366            assert_eq!(peers.connection_info.num_pending_in, count);
2367        }
2368        assert!(peers.connection_info.has_in_capacity());
2369        assert!(!peers.connection_info.has_in_pending_capacity());
2370
2371        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 100)), 8008);
2372        assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_err());
2373    }
2374
2375    #[tokio::test]
2376    async fn test_reject_incoming_at_pending_capacity_trusted_peers() {
2377        let mut peers = PeersManager::new(PeersConfig::test().with_max_inbound(2));
2378        let trusted = PeerId::random();
2379        peers.add_trusted_peer_id(trusted);
2380
2381        // connect the trusted peer
2382        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 0)), 8008);
2383        assert!(peers.on_incoming_pending_session(addr.ip()).is_ok());
2384        peers.on_incoming_session_established(trusted, addr);
2385
2386        match event!(peers) {
2387            PeerAction::PeerAdded(id) => {
2388                assert_eq!(id, trusted);
2389            }
2390            _ => unreachable!(),
2391        }
2392
2393        // saturate the remaining inbound slots with untrusted peers
2394        let mut connected_untrusted_peer_ids = Vec::new();
2395        for i in 0..(peers.connection_info.config.max_inbound - 1) {
2396            let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, (i + 1) as u8)), 8008);
2397            assert!(peers.on_incoming_pending_session(addr.ip()).is_ok());
2398            let peer_id = PeerId::random();
2399            peers.on_incoming_session_established(peer_id, addr);
2400            connected_untrusted_peer_ids.push(peer_id);
2401
2402            match event!(peers) {
2403                PeerAction::PeerAdded(id) => {
2404                    assert_eq!(id, peer_id);
2405                }
2406                _ => unreachable!(),
2407            }
2408        }
2409
2410        let mut pending_addrs = Vec::new();
2411
2412        // saturate available slots
2413        for i in 0..2 {
2414            let socket_addr =
2415                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, (i + 10) as u8)), 8008);
2416            assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2417
2418            pending_addrs.push(socket_addr);
2419        }
2420
2421        assert_eq!(peers.connection_info.num_pending_in, 2);
2422
2423        // try to handle additional incoming connections at capacity
2424        for i in 0..2 {
2425            let socket_addr =
2426                SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, (i + 20) as u8)), 8008);
2427            assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_err());
2428        }
2429
2430        let err = PendingSessionHandshakeError::Eth(EthStreamError::P2PStreamError(
2431            P2PStreamError::HandshakeError(P2PHandshakeError::Disconnected(
2432                DisconnectReason::UselessPeer,
2433            )),
2434        ));
2435
2436        // Remove all pending peers
2437        for pending_addr in pending_addrs {
2438            peers.on_incoming_pending_session_dropped(pending_addr, &err);
2439        }
2440
2441        println!("num_pending_in: {}", peers.connection_info.num_pending_in);
2442
2443        println!(
2444            "num_inbound: {}, has_in_capacity: {}",
2445            peers.connection_info.num_inbound,
2446            peers.connection_info.has_in_capacity()
2447        );
2448
2449        // disconnect a connected peer
2450        peers.on_active_session_gracefully_closed(connected_untrusted_peer_ids[0]);
2451
2452        println!(
2453            "num_inbound: {}, has_in_capacity: {}",
2454            peers.connection_info.num_inbound,
2455            peers.connection_info.has_in_capacity()
2456        );
2457
2458        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 99)), 8008);
2459        assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2460    }
2461
2462    #[tokio::test]
2463    async fn test_closed_incoming() {
2464        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2465        let mut peers = PeersManager::default();
2466
2467        assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2468        assert_eq!(peers.connection_info.num_pending_in, 1);
2469        peers.on_incoming_pending_session_gracefully_closed();
2470        assert_eq!(peers.connection_info.num_pending_in, 0);
2471    }
2472
2473    #[tokio::test]
2474    async fn test_dropped_incoming() {
2475        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(1, 0, 1, 2)), 8008);
2476        let ban_duration = Duration::from_millis(500);
2477        let config = PeersConfig {
2478            ban_duration,
2479            incoming_ip_throttle_duration: ban_duration,
2480            ..PeersConfig::test()
2481        };
2482        let mut peers = PeersManager::new(config);
2483
2484        assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2485        assert_eq!(peers.connection_info.num_pending_in, 1);
2486        let err = PendingSessionHandshakeError::Eth(EthStreamError::P2PStreamError(
2487            P2PStreamError::HandshakeError(P2PHandshakeError::Disconnected(
2488                DisconnectReason::UselessPeer,
2489            )),
2490        ));
2491
2492        peers.on_incoming_pending_session_dropped(socket_addr, &err);
2493        assert_eq!(peers.connection_info.num_pending_in, 0);
2494        assert!(peers.ban_list.is_banned_ip(&socket_addr.ip()));
2495
2496        assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_err());
2497
2498        // unbanned after timeout
2499        tokio::time::sleep(ban_duration).await;
2500
2501        poll_fn(|cx| {
2502            let _ = peers.poll(cx);
2503            Poll::Ready(())
2504        })
2505        .await;
2506
2507        assert!(!peers.ban_list.is_banned_ip(&socket_addr.ip()));
2508        assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2509    }
2510
2511    #[tokio::test]
2512    async fn test_reputation_change_connected() {
2513        let peer = PeerId::random();
2514        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2515        let mut peers = PeersManager::default();
2516        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2517
2518        match event!(peers) {
2519            PeerAction::PeerAdded(peer_id) => {
2520                assert_eq!(peer_id, peer);
2521            }
2522            _ => unreachable!(),
2523        }
2524        match event!(peers) {
2525            PeerAction::Connect { peer_id, remote_addr } => {
2526                assert_eq!(peer_id, peer);
2527                assert_eq!(remote_addr, socket_addr);
2528            }
2529            _ => unreachable!(),
2530        }
2531
2532        let p = peers.peers.get_mut(&peer).unwrap();
2533        assert_eq!(p.state, PeerConnectionState::PendingOut);
2534
2535        peers.apply_reputation_change(&peer, ReputationChangeKind::BadProtocol);
2536
2537        let p = peers.peers.get(&peer).unwrap();
2538        assert_eq!(p.state, PeerConnectionState::PendingOut);
2539        assert!(p.is_banned());
2540
2541        peers.on_active_session_gracefully_closed(peer);
2542
2543        let p = peers.peers.get(&peer).unwrap();
2544        assert_eq!(p.state, PeerConnectionState::Idle);
2545        assert!(p.is_banned());
2546
2547        match event!(peers) {
2548            PeerAction::Disconnect { peer_id, .. } => {
2549                assert_eq!(peer_id, peer);
2550            }
2551            _ => unreachable!(),
2552        }
2553    }
2554
2555    #[tokio::test]
2556    async fn retain_trusted_status() {
2557        let _socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 99)), 8008);
2558        let trusted = PeerId::random();
2559        let mut peers =
2560            PeersManager::new(PeersConfig::test().with_trusted_nodes(vec![TrustedPeer {
2561                host: Host::Ipv4(Ipv4Addr::new(127, 0, 1, 2)),
2562                tcp_port: 8008,
2563                udp_port: 8008,
2564                id: trusted,
2565            }]));
2566        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2567        peers.add_peer(trusted, PeerAddr::from_tcp(socket_addr), None);
2568        assert!(peers.peers.get(&trusted).unwrap().is_trusted());
2569    }
2570
2571    #[tokio::test]
2572    async fn accept_incoming_trusted_unknown_peer_address() {
2573        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 99)), 8008);
2574        let mut peers = PeersManager::new(PeersConfig::test().with_max_inbound(2));
2575        // try to connect trusted peer
2576        let trusted = PeerId::random();
2577        peers.add_trusted_peer_id(trusted);
2578
2579        // saturate the inbound slots
2580        for i in 0..peers.connection_info.config.max_inbound {
2581            let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, i as u8)), 8008);
2582            assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2583            let peer_id = PeerId::random();
2584            peers.on_incoming_session_established(peer_id, addr);
2585
2586            match event!(peers) {
2587                PeerAction::PeerAdded(id) => {
2588                    assert_eq!(id, peer_id);
2589                }
2590                _ => unreachable!(),
2591            }
2592        }
2593
2594        // try to connect untrusted peer
2595        let untrusted = PeerId::random();
2596        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 99)), 8008);
2597        assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2598        peers.on_incoming_session_established(untrusted, socket_addr);
2599
2600        match event!(peers) {
2601            PeerAction::PeerAdded(id) => {
2602                assert_eq!(id, untrusted);
2603            }
2604            _ => unreachable!(),
2605        }
2606
2607        match event!(peers) {
2608            PeerAction::Disconnect { peer_id, reason } => {
2609                assert_eq!(peer_id, untrusted);
2610                assert_eq!(reason, Some(DisconnectReason::TooManyPeers));
2611            }
2612            _ => unreachable!(),
2613        }
2614
2615        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 100)), 8008);
2616        assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2617        peers.on_incoming_session_established(trusted, socket_addr);
2618
2619        match event!(peers) {
2620            PeerAction::PeerAdded(id) => {
2621                assert_eq!(id, trusted);
2622            }
2623            _ => unreachable!(),
2624        }
2625
2626        poll_fn(|cx| {
2627            assert!(peers.poll(cx).is_pending());
2628            Poll::Ready(())
2629        })
2630        .await;
2631
2632        let peer = peers.peers.get(&trusted).unwrap();
2633        assert_eq!(peer.state, PeerConnectionState::In);
2634    }
2635
2636    #[tokio::test]
2637    async fn test_already_connected() {
2638        let peer = PeerId::random();
2639        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2640        let mut peers = PeersManager::default();
2641
2642        // Attempt to establish an incoming session, expecting `num_pending_in` to increase by 1
2643        assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2644        assert_eq!(peers.connection_info.num_pending_in, 1);
2645
2646        // Establish a session with the peer, expecting the peer to be added and the `num_inbound`
2647        // to increase by 1
2648        peers.on_incoming_session_established(peer, socket_addr);
2649        let p = peers.peers.get_mut(&peer).expect("peer not found");
2650        assert_eq!(p.addr.tcp(), socket_addr);
2651        assert_eq!(peers.connection_info.num_pending_in, 0);
2652        assert_eq!(peers.connection_info.num_inbound, 1);
2653
2654        // Attempt to establish another incoming session, expecting the `num_pending_in` to increase
2655        // by 1
2656        assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
2657        assert_eq!(peers.connection_info.num_pending_in, 1);
2658
2659        // Simulate a rejection due to an already established connection, expecting the
2660        // `num_pending_in` to decrease by 1. The peer should remain connected and the `num_inbound`
2661        // should not be changed.
2662        peers.on_already_connected(Direction::Incoming);
2663
2664        let p = peers.peers.get_mut(&peer).expect("peer not found");
2665        assert_eq!(p.addr.tcp(), socket_addr);
2666        assert_eq!(peers.connection_info.num_pending_in, 0);
2667        assert_eq!(peers.connection_info.num_inbound, 1);
2668    }
2669
2670    #[tokio::test]
2671    async fn test_reputation_change_trusted_peer() {
2672        let peer = PeerId::random();
2673        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2674        let mut peers = PeersManager::default();
2675        peers.add_trusted_peer(peer, PeerAddr::from_tcp(socket_addr));
2676
2677        match event!(peers) {
2678            PeerAction::PeerAdded(peer_id) => {
2679                assert_eq!(peer_id, peer);
2680            }
2681            _ => unreachable!(),
2682        }
2683        match event!(peers) {
2684            PeerAction::Connect { peer_id, remote_addr } => {
2685                assert_eq!(peer_id, peer);
2686                assert_eq!(remote_addr, socket_addr);
2687            }
2688            _ => unreachable!(),
2689        }
2690
2691        assert_eq!(peers.peers.get_mut(&peer).unwrap().state, PeerConnectionState::PendingOut);
2692        peers.on_active_outgoing_established(peer);
2693        assert_eq!(peers.peers.get_mut(&peer).unwrap().state, PeerConnectionState::Out);
2694
2695        peers.apply_reputation_change(&peer, ReputationChangeKind::BadMessage);
2696
2697        {
2698            let p = peers.peers.get(&peer).unwrap();
2699            assert_eq!(p.state, PeerConnectionState::Out);
2700            // not banned yet
2701            assert!(!p.is_banned());
2702        }
2703
2704        // ensure peer is banned eventually
2705        loop {
2706            peers.apply_reputation_change(&peer, ReputationChangeKind::BadMessage);
2707
2708            let p = peers.peers.get(&peer).unwrap();
2709            if p.is_banned() {
2710                break
2711            }
2712        }
2713
2714        match event!(peers) {
2715            PeerAction::Disconnect { peer_id, .. } => {
2716                assert_eq!(peer_id, peer);
2717            }
2718            _ => unreachable!(),
2719        }
2720    }
2721
2722    #[tokio::test]
2723    async fn test_reputation_management() {
2724        let peer = PeerId::random();
2725        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2726        let mut peers = PeersManager::default();
2727        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2728        assert_eq!(peers.get_reputation(&peer), Some(0));
2729
2730        peers.apply_reputation_change(&peer, ReputationChangeKind::Other(1024));
2731        assert_eq!(peers.get_reputation(&peer), Some(1024));
2732
2733        peers.apply_reputation_change(&peer, ReputationChangeKind::Reset);
2734        assert_eq!(peers.get_reputation(&peer), Some(0));
2735    }
2736
2737    #[tokio::test]
2738    async fn test_remove_discovered_active() {
2739        let peer = PeerId::random();
2740        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2741        let mut peers = PeersManager::default();
2742        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2743
2744        match event!(peers) {
2745            PeerAction::PeerAdded(peer_id) => {
2746                assert_eq!(peer_id, peer);
2747            }
2748            _ => unreachable!(),
2749        }
2750        match event!(peers) {
2751            PeerAction::Connect { peer_id, remote_addr } => {
2752                assert_eq!(peer_id, peer);
2753                assert_eq!(remote_addr, socket_addr);
2754            }
2755            _ => unreachable!(),
2756        }
2757
2758        let p = peers.peers.get(&peer).unwrap();
2759        assert_eq!(p.state, PeerConnectionState::PendingOut);
2760
2761        peers.remove_peer(peer);
2762
2763        match event!(peers) {
2764            PeerAction::PeerRemoved(peer_id) => {
2765                assert_eq!(peer_id, peer);
2766            }
2767            _ => unreachable!(),
2768        }
2769        match event!(peers) {
2770            PeerAction::Disconnect { peer_id, .. } => {
2771                assert_eq!(peer_id, peer);
2772            }
2773            _ => unreachable!(),
2774        }
2775
2776        let p = peers.peers.get(&peer).unwrap();
2777        assert_eq!(p.state, PeerConnectionState::PendingOut);
2778
2779        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2780        let p = peers.peers.get(&peer).unwrap();
2781        assert_eq!(p.state, PeerConnectionState::PendingOut);
2782
2783        peers.on_active_session_gracefully_closed(peer);
2784        assert!(!peers.peers.contains_key(&peer));
2785    }
2786
2787    #[tokio::test]
2788    async fn test_fatal_outgoing_connection_error_trusted() {
2789        let peer = PeerId::random();
2790        let config = PeersConfig::test()
2791            .with_trusted_nodes(vec![TrustedPeer {
2792                host: Host::Ipv4(Ipv4Addr::new(127, 0, 1, 2)),
2793                tcp_port: 8008,
2794                udp_port: 8008,
2795                id: peer,
2796            }])
2797            .with_trusted_nodes_only(true);
2798        let mut peers = PeersManager::new(config);
2799        let socket_addr = peers.peers.get(&peer).unwrap().addr.tcp();
2800
2801        match event!(peers) {
2802            PeerAction::Connect { peer_id, remote_addr } => {
2803                assert_eq!(peer_id, peer);
2804                assert_eq!(remote_addr, socket_addr);
2805            }
2806            _ => unreachable!(),
2807        }
2808
2809        let p = peers.peers.get(&peer).unwrap();
2810        assert_eq!(p.state, PeerConnectionState::PendingOut);
2811
2812        assert_eq!(peers.num_outbound_connections(), 0);
2813
2814        let err = PendingSessionHandshakeError::Eth(EthStreamError::EthHandshakeError(
2815            EthHandshakeError::NonStatusMessageInHandshake,
2816        ));
2817        assert!(err.is_fatal_protocol_error());
2818
2819        peers.on_outgoing_pending_session_dropped(&socket_addr, &peer, &err);
2820        assert_eq!(peers.num_outbound_connections(), 0);
2821
2822        // try tmp ban peer
2823        match event!(peers) {
2824            PeerAction::BanPeer { peer_id } => {
2825                assert_eq!(peer_id, peer);
2826            }
2827            err => unreachable!("{err:?}"),
2828        }
2829
2830        // ensure we still have trusted peer
2831        assert!(peers.peers.contains_key(&peer));
2832
2833        // await for the ban to expire
2834        tokio::time::sleep(peers.backoff_durations.medium).await;
2835
2836        match event!(peers) {
2837            PeerAction::Connect { peer_id, remote_addr } => {
2838                assert_eq!(peer_id, peer);
2839                assert_eq!(remote_addr, socket_addr);
2840            }
2841            err => unreachable!("{err:?}"),
2842        }
2843    }
2844
2845    #[tokio::test]
2846    async fn test_outgoing_connection_error() {
2847        let peer = PeerId::random();
2848        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2849        let mut peers = PeersManager::default();
2850        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2851
2852        match event!(peers) {
2853            PeerAction::PeerAdded(peer_id) => {
2854                assert_eq!(peer_id, peer);
2855            }
2856            _ => unreachable!(),
2857        }
2858        match event!(peers) {
2859            PeerAction::Connect { peer_id, remote_addr } => {
2860                assert_eq!(peer_id, peer);
2861                assert_eq!(remote_addr, socket_addr);
2862            }
2863            _ => unreachable!(),
2864        }
2865
2866        let p = peers.peers.get(&peer).unwrap();
2867        assert_eq!(p.state, PeerConnectionState::PendingOut);
2868
2869        assert_eq!(peers.num_outbound_connections(), 0);
2870
2871        peers.on_outgoing_connection_failure(
2872            &socket_addr,
2873            &peer,
2874            &io::Error::new(io::ErrorKind::ConnectionRefused, ""),
2875        );
2876
2877        assert_eq!(peers.num_outbound_connections(), 0);
2878    }
2879
2880    #[tokio::test]
2881    async fn test_outgoing_connection_gracefully_closed() {
2882        let peer = PeerId::random();
2883        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
2884        let mut peers = PeersManager::default();
2885        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
2886
2887        match event!(peers) {
2888            PeerAction::PeerAdded(peer_id) => {
2889                assert_eq!(peer_id, peer);
2890            }
2891            _ => unreachable!(),
2892        }
2893        match event!(peers) {
2894            PeerAction::Connect { peer_id, remote_addr } => {
2895                assert_eq!(peer_id, peer);
2896                assert_eq!(remote_addr, socket_addr);
2897            }
2898            _ => unreachable!(),
2899        }
2900
2901        let p = peers.peers.get(&peer).unwrap();
2902        assert_eq!(p.state, PeerConnectionState::PendingOut);
2903
2904        assert_eq!(peers.num_outbound_connections(), 0);
2905
2906        peers.on_outgoing_pending_session_gracefully_closed(&peer);
2907
2908        assert_eq!(peers.num_outbound_connections(), 0);
2909        assert_eq!(peers.connection_info.num_pending_out, 0);
2910    }
2911
2912    #[tokio::test]
2913    async fn test_discovery_ban_list() {
2914        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2));
2915        let socket_addr = SocketAddr::new(ip, 8008);
2916        let ban_list = BanList::new(vec![], vec![ip]);
2917        let config = PeersConfig::default().with_ban_list(ban_list);
2918        let mut peer_manager = PeersManager::new(config);
2919        peer_manager.add_peer(B512::default(), PeerAddr::from_tcp(socket_addr), None);
2920
2921        assert!(peer_manager.peers.is_empty());
2922    }
2923
2924    #[tokio::test]
2925    async fn test_on_pending_ban_list() {
2926        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2));
2927        let socket_addr = SocketAddr::new(ip, 8008);
2928        let ban_list = BanList::new(vec![], vec![ip]);
2929        let config = PeersConfig::test().with_ban_list(ban_list);
2930        let mut peer_manager = PeersManager::new(config);
2931        let a = peer_manager.on_incoming_pending_session(socket_addr.ip());
2932        // because we have no active peers this should be fine for testings
2933        match a {
2934            Ok(_) => panic!(),
2935            Err(err) => match err {
2936                InboundConnectionError::IpBanned => {
2937                    assert_eq!(peer_manager.connection_info.num_pending_in, 0)
2938                }
2939                _ => unreachable!(),
2940            },
2941        }
2942    }
2943
2944    #[tokio::test]
2945    async fn test_on_active_inbound_ban_list() {
2946        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2));
2947        let socket_addr = SocketAddr::new(ip, 8008);
2948        let given_peer_id = PeerId::random();
2949        let ban_list = BanList::new(vec![given_peer_id], vec![]);
2950        let config = PeersConfig::test().with_ban_list(ban_list);
2951        let mut peer_manager = PeersManager::new(config);
2952        assert!(peer_manager.on_incoming_pending_session(socket_addr.ip()).is_ok());
2953        // non-trusted nodes should also increase pending_in
2954        assert_eq!(peer_manager.connection_info.num_pending_in, 1);
2955        assert_eq!(
2956            peer_manager.inbound_session_rejection(given_peer_id),
2957            Some(DisconnectReason::DisconnectRequested)
2958        );
2959        peer_manager.on_incoming_session_established(given_peer_id, socket_addr);
2960        // after the connection is established, the peer should be removed, the num_pending_in
2961        // should be decreased, and the num_inbound should not be increased
2962        assert_eq!(peer_manager.connection_info.num_pending_in, 0);
2963        assert_eq!(peer_manager.connection_info.num_inbound, 0);
2964
2965        let Some(PeerAction::DisconnectBannedIncoming { peer_id }) =
2966            peer_manager.queued_actions.pop_front()
2967        else {
2968            panic!()
2969        };
2970
2971        assert_eq!(peer_id, given_peer_id)
2972    }
2973
2974    #[test]
2975    fn test_connection_limits() {
2976        let mut info = ConnectionInfo::default();
2977        info.inc_in();
2978        assert_eq!(info.num_inbound, 1);
2979        assert_eq!(info.num_outbound, 0);
2980        assert!(info.has_in_capacity());
2981
2982        info.decr_in();
2983        assert_eq!(info.num_inbound, 0);
2984        assert_eq!(info.num_outbound, 0);
2985
2986        info.inc_out();
2987        assert_eq!(info.num_inbound, 0);
2988        assert_eq!(info.num_outbound, 1);
2989        assert!(info.has_out_capacity());
2990
2991        info.decr_out();
2992        assert_eq!(info.num_inbound, 0);
2993        assert_eq!(info.num_outbound, 0);
2994    }
2995
2996    #[test]
2997    fn test_connection_peer_state() {
2998        let mut info = ConnectionInfo::default();
2999        info.inc_in();
3000
3001        info.decr_state(PeerConnectionState::In);
3002        assert_eq!(info.num_inbound, 0);
3003        assert_eq!(info.num_outbound, 0);
3004
3005        info.inc_out();
3006
3007        info.decr_state(PeerConnectionState::Out);
3008        assert_eq!(info.num_inbound, 0);
3009        assert_eq!(info.num_outbound, 0);
3010    }
3011
3012    #[tokio::test]
3013    async fn test_trusted_peers_are_prioritized() {
3014        let trusted_peer = PeerId::random();
3015        let trusted_sock = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
3016        let config = PeersConfig::test().with_trusted_nodes(vec![TrustedPeer {
3017            host: Host::Ipv4(Ipv4Addr::new(127, 0, 1, 2)),
3018            tcp_port: 8008,
3019            udp_port: 8008,
3020            id: trusted_peer,
3021        }]);
3022        let mut peers = PeersManager::new(config);
3023
3024        let basic_peer = PeerId::random();
3025        let basic_sock = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3026        peers.add_peer(basic_peer, PeerAddr::from_tcp(basic_sock), None);
3027
3028        match event!(peers) {
3029            PeerAction::PeerAdded(peer_id) => {
3030                assert_eq!(peer_id, basic_peer);
3031            }
3032            _ => unreachable!(),
3033        }
3034        match event!(peers) {
3035            PeerAction::Connect { peer_id, remote_addr } => {
3036                assert_eq!(peer_id, trusted_peer);
3037                assert_eq!(remote_addr, trusted_sock);
3038            }
3039            _ => unreachable!(),
3040        }
3041        match event!(peers) {
3042            PeerAction::Connect { peer_id, remote_addr } => {
3043                assert_eq!(peer_id, basic_peer);
3044                assert_eq!(remote_addr, basic_sock);
3045            }
3046            _ => unreachable!(),
3047        }
3048    }
3049
3050    #[tokio::test]
3051    async fn test_trusted_peers_bypass_outbound_capacity() {
3052        let mut peers = PeersManager::new(PeersConfig::test().with_max_outbound(1));
3053
3054        // an untrusted peer takes the only outbound slot
3055        let basic_peer = PeerId::random();
3056        let basic_sock = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
3057        peers.add_peer(basic_peer, PeerAddr::from_tcp(basic_sock), None);
3058        peers.fill_outbound_slots();
3059        peers.on_active_outgoing_established(basic_peer);
3060        assert!(!peers.connection_info.has_out_capacity());
3061        peers.queued_actions.clear();
3062
3063        let static_peer = PeerId::random();
3064        peers.add_peer_kind(
3065            static_peer,
3066            Some(PeerKind::Static),
3067            PeerAddr::from_tcp(basic_sock),
3068            None,
3069        );
3070        assert!(peers.best_unconnected(true).is_none());
3071        peers.queued_actions.clear();
3072
3073        // a trusted peer is dialed regardless
3074        let trusted_peer = PeerId::random();
3075        let trusted_sock = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 3)), 8008);
3076        peers.add_trusted_peer(trusted_peer, PeerAddr::from_tcp(trusted_sock));
3077        peers.queued_actions.clear();
3078        peers.fill_outbound_slots();
3079        match peers.queued_actions.pop_front() {
3080            Some(PeerAction::Connect { peer_id, remote_addr }) => {
3081                assert_eq!(peer_id, trusted_peer);
3082                assert_eq!(remote_addr, trusted_sock);
3083            }
3084            action => panic!("expected the trusted peer to be dialed, got {action:?}"),
3085        }
3086        assert!(peers.queued_actions.is_empty());
3087        peers.on_active_outgoing_established(trusted_peer);
3088
3089        // untrusted peers still wait for a free slot
3090        let other_peer = PeerId::random();
3091        let other_sock = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 4)), 8008);
3092        peers.add_peer(other_peer, PeerAddr::from_tcp(other_sock), None);
3093        peers.queued_actions.clear();
3094        peers.fill_outbound_slots();
3095        assert!(peers.queued_actions.is_empty());
3096        assert!(peers.peers[&other_peer].state.is_idle());
3097    }
3098
3099    #[tokio::test]
3100    async fn test_connect_trusted_nodes_only() {
3101        let trusted_peer = PeerId::random();
3102        let trusted_sock = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
3103        let config = PeersConfig::test()
3104            .with_trusted_nodes(vec![TrustedPeer {
3105                host: Host::Ipv4(Ipv4Addr::new(127, 0, 1, 2)),
3106                tcp_port: 8008,
3107                udp_port: 8008,
3108                id: trusted_peer,
3109            }])
3110            .with_trusted_nodes_only(true);
3111        let mut peers = PeersManager::new(config);
3112
3113        let basic_peer = PeerId::random();
3114        let basic_sock = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3115        peers.add_peer(basic_peer, PeerAddr::from_tcp(basic_sock), None);
3116
3117        match event!(peers) {
3118            PeerAction::PeerAdded(peer_id) => {
3119                assert_eq!(peer_id, basic_peer);
3120            }
3121            _ => unreachable!(),
3122        }
3123        match event!(peers) {
3124            PeerAction::Connect { peer_id, remote_addr } => {
3125                assert_eq!(peer_id, trusted_peer);
3126                assert_eq!(remote_addr, trusted_sock);
3127            }
3128            _ => unreachable!(),
3129        }
3130        poll_fn(|cx| {
3131            assert!(peers.poll(cx).is_pending());
3132            Poll::Ready(())
3133        })
3134        .await;
3135    }
3136
3137    #[tokio::test]
3138    async fn test_incoming_with_trusted_nodes_only() {
3139        let trusted_peer = PeerId::random();
3140        let config = PeersConfig::test()
3141            .with_trusted_nodes(vec![TrustedPeer {
3142                host: Host::Ipv4(Ipv4Addr::new(127, 0, 1, 2)),
3143                tcp_port: 8008,
3144                udp_port: 8008,
3145                id: trusted_peer,
3146            }])
3147            .with_trusted_nodes_only(true);
3148        let mut peers = PeersManager::new(config);
3149
3150        let basic_peer = PeerId::random();
3151        let basic_sock = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3152        assert!(peers.on_incoming_pending_session(basic_sock.ip()).is_ok());
3153        // non-trusted nodes should also increase pending_in
3154        assert_eq!(peers.connection_info.num_pending_in, 1);
3155        assert_eq!(
3156            peers.inbound_session_rejection(basic_peer),
3157            Some(DisconnectReason::DisconnectRequested)
3158        );
3159        assert_eq!(peers.inbound_session_rejection(trusted_peer), None);
3160        peers.on_incoming_session_established(basic_peer, basic_sock);
3161        // after the connection is established, the peer should be removed, the num_pending_in
3162        // should be decreased, and the num_inbound mut not be increased
3163        assert_eq!(peers.connection_info.num_pending_in, 0);
3164        assert_eq!(peers.connection_info.num_inbound, 0);
3165
3166        let Some(PeerAction::DisconnectUntrustedIncoming { peer_id }) =
3167            peers.queued_actions.pop_front()
3168        else {
3169            panic!()
3170        };
3171        assert_eq!(basic_peer, peer_id);
3172        assert!(!peers.peers.contains_key(&basic_peer));
3173    }
3174
3175    #[tokio::test]
3176    async fn test_incoming_without_trusted_nodes_only() {
3177        let trusted_peer = PeerId::random();
3178        let config = PeersConfig::test()
3179            .with_trusted_nodes(vec![TrustedPeer {
3180                host: Host::Ipv4(Ipv4Addr::new(127, 0, 1, 2)),
3181                tcp_port: 8008,
3182                udp_port: 8008,
3183                id: trusted_peer,
3184            }])
3185            .with_trusted_nodes_only(false);
3186        let mut peers = PeersManager::new(config);
3187
3188        let basic_peer = PeerId::random();
3189        let basic_sock = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3190        assert!(peers.on_incoming_pending_session(basic_sock.ip()).is_ok());
3191
3192        // non-trusted nodes should also increase pending_in
3193        assert_eq!(peers.connection_info.num_pending_in, 1);
3194        peers.on_incoming_session_established(basic_peer, basic_sock);
3195        // after the connection is established, the peer should be removed, the num_pending_in
3196        // should be decreased, and the num_inbound must be increased
3197        assert_eq!(peers.connection_info.num_pending_in, 0);
3198        assert_eq!(peers.connection_info.num_inbound, 1);
3199        assert!(peers.peers.contains_key(&basic_peer));
3200    }
3201
3202    #[tokio::test]
3203    async fn test_incoming_at_capacity() {
3204        let mut config = PeersConfig::test();
3205        config.connection_info.max_inbound = 1;
3206        let mut peers = PeersManager::new(config);
3207
3208        let peer = PeerId::random();
3209        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3210        assert!(peers.on_incoming_pending_session(addr.ip()).is_ok());
3211
3212        peers.on_incoming_session_established(peer, addr);
3213
3214        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3215        assert_eq!(
3216            peers.on_incoming_pending_session(addr.ip()).unwrap_err(),
3217            InboundConnectionError::ExceedsCapacity
3218        );
3219    }
3220
3221    #[tokio::test]
3222    async fn test_incoming_rate_limit() {
3223        for max_inbound in [0, 1] {
3224            let config = PeersConfig {
3225                incoming_ip_throttle_duration: Duration::from_millis(100),
3226                ..PeersConfig::test().with_max_inbound(max_inbound)
3227            };
3228            let mut peers = PeersManager::new(config);
3229            peers.add_trusted_peer_id(PeerId::random());
3230
3231            let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(168, 0, 1, 2)), 8009);
3232            peers.on_incoming_pending_session(addr.ip()).unwrap();
3233            peers.on_incoming_pending_session_gracefully_closed();
3234            assert_eq!(
3235                peers.on_incoming_pending_session(addr.ip()).unwrap_err(),
3236                InboundConnectionError::IpBanned
3237            );
3238
3239            peers.release_interval.reset_immediately();
3240            tokio::time::sleep(peers.incoming_ip_throttle_duration).await;
3241
3242            // await unban
3243            poll_fn(|cx| loop {
3244                if peers.poll(cx).is_pending() {
3245                    return Poll::Ready(());
3246                }
3247            })
3248            .await;
3249
3250            peers.on_incoming_pending_session(addr.ip()).unwrap();
3251            peers.on_incoming_pending_session_gracefully_closed();
3252            assert_eq!(
3253                peers.on_incoming_pending_session(addr.ip()).unwrap_err(),
3254                InboundConnectionError::IpBanned
3255            );
3256        }
3257    }
3258
3259    #[tokio::test]
3260    async fn test_incoming_throttle_capacity() {
3261        for max_inbound in [0, 1] {
3262            let mut peers = PeersManager::new(PeersConfig::test().with_max_inbound(max_inbound));
3263            peers.add_trusted_peer_id(PeerId::random());
3264            peers.ban_list = BanList::new(
3265                [],
3266                (0..MAX_INCOMING_IP_THROTTLE_ENTRIES)
3267                    .map(|i| IpAddr::V4(Ipv4Addr::from(0x0800_0000 + i))),
3268            );
3269            for i in 0..MAX_INCOMING_IP_THROTTLE_ENTRIES {
3270                peers.throttle_incoming_ip(IpAddr::V4(Ipv4Addr::from(0x0900_0000 + i)));
3271            }
3272            let ip = IpAddr::from([1, 1, 1, 1]);
3273            assert!(peers.on_incoming_pending_session(ip).is_ok());
3274            assert_eq!(peers.connection_info.num_pending_in, 1);
3275            assert_eq!(
3276                peers.incoming_ip_throttle.len(),
3277                usize::try_from(MAX_INCOMING_IP_THROTTLE_ENTRIES).unwrap()
3278            );
3279            peers.on_incoming_pending_session_gracefully_closed();
3280            assert_eq!(peers.connection_info.num_pending_in, 0);
3281            assert_eq!(
3282                peers.on_incoming_pending_session(ip),
3283                Err(InboundConnectionError::IpBanned)
3284            );
3285
3286            // A saturated throttle table must not weaken existing security bans.
3287            assert_eq!(
3288                peers.on_incoming_pending_session(IpAddr::from([8, 0, 0, 1])),
3289                Err(InboundConnectionError::IpBanned)
3290            );
3291        }
3292    }
3293
3294    #[tokio::test]
3295    async fn test_tick() {
3296        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2));
3297        let socket_addr = SocketAddr::new(ip, 8008);
3298        let config = PeersConfig::test();
3299        let mut peer_manager = PeersManager::new(config);
3300        let peer_id = PeerId::random();
3301        peer_manager.add_peer(peer_id, PeerAddr::from_tcp(socket_addr), None);
3302
3303        // Age the last tick directly so each reputation update sees a full elapsed second.
3304        peer_manager.last_tick -= Duration::from_secs(1);
3305        peer_manager.tick();
3306
3307        // still unconnected
3308        assert_eq!(peer_manager.peers.get_mut(&peer_id).unwrap().reputation, DEFAULT_REPUTATION);
3309
3310        // mark as connected
3311        peer_manager.peers.get_mut(&peer_id).unwrap().state = PeerConnectionState::Out;
3312
3313        peer_manager.last_tick -= Duration::from_secs(1);
3314        peer_manager.tick();
3315
3316        // still at default reputation
3317        assert_eq!(peer_manager.peers.get_mut(&peer_id).unwrap().reputation, DEFAULT_REPUTATION);
3318
3319        peer_manager.peers.get_mut(&peer_id).unwrap().reputation -= 1;
3320
3321        // The elapsed time exceeds the deficit, so recovery must stop at the default.
3322        peer_manager.last_tick -= Duration::from_secs(5);
3323        peer_manager.tick();
3324
3325        // tick applied
3326        assert_eq!(peer_manager.peers.get_mut(&peer_id).unwrap().reputation, DEFAULT_REPUTATION);
3327    }
3328
3329    #[tokio::test(start_paused = true)]
3330    async fn test_tick_keeps_time_below_a_second() {
3331        let mut peer_manager = PeersManager::new(PeersConfig::test());
3332        let peer_id = PeerId::random();
3333        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
3334        peer_manager.add_peer(peer_id, PeerAddr::from_tcp(addr), None);
3335        let peer = peer_manager.peers.get_mut(&peer_id).unwrap();
3336        peer.state = PeerConnectionState::Out;
3337        peer.reputation = DEFAULT_REPUTATION - 3;
3338
3339        tokio::time::advance(Duration::from_millis(600)).await;
3340        peer_manager.tick();
3341        assert_eq!(peer_manager.get_reputation(&peer_id), Some(DEFAULT_REPUTATION - 3));
3342
3343        // both ticks together cover one second, 200 ms are left
3344        tokio::time::advance(Duration::from_millis(600)).await;
3345        peer_manager.tick();
3346        assert_eq!(peer_manager.get_reputation(&peer_id), Some(DEFAULT_REPUTATION - 2));
3347
3348        // the 200 ms left complete the next second
3349        tokio::time::advance(Duration::from_millis(800)).await;
3350        peer_manager.tick();
3351        assert_eq!(peer_manager.get_reputation(&peer_id), Some(DEFAULT_REPUTATION - 1));
3352    }
3353
3354    #[tokio::test]
3355    async fn test_remove_incoming_after_disconnect() {
3356        let peer_id = PeerId::random();
3357        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3358        let mut peers = PeersManager::default();
3359
3360        peers.on_incoming_pending_session(addr.ip()).unwrap();
3361        peers.on_incoming_session_established(peer_id, addr);
3362        let peer = peers.peers.get(&peer_id).unwrap();
3363        assert_eq!(peer.state, PeerConnectionState::In);
3364        assert!(peer.remove_after_disconnect);
3365
3366        peers.on_active_session_gracefully_closed(peer_id);
3367        assert!(!peers.peers.contains_key(&peer_id))
3368    }
3369
3370    #[tokio::test]
3371    async fn test_repeated_remove_while_disconnecting_releases_slot() {
3372        let peer_id = PeerId::random();
3373        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3374        let mut peers = PeersManager::default();
3375
3376        peers.on_incoming_pending_session(addr.ip()).unwrap();
3377        peers.on_incoming_session_established(peer_id, addr);
3378        assert_eq!(peers.connection_info.num_inbound, 1);
3379
3380        peers.remove_peer(peer_id);
3381        peers.remove_peer(peer_id);
3382
3383        let peer = peers.peers.get(&peer_id).unwrap();
3384        assert_eq!(peer.state, PeerConnectionState::DisconnectingIn);
3385        assert!(peer.remove_after_disconnect);
3386        assert_eq!(peers.connection_info.num_inbound, 1);
3387
3388        peers.on_active_session_gracefully_closed(peer_id);
3389        assert_eq!(peers.connection_info.num_inbound, 0);
3390        assert!(!peers.peers.contains_key(&peer_id));
3391    }
3392
3393    #[tokio::test]
3394    async fn test_keep_incoming_after_disconnect_if_discovered() {
3395        let peer_id = PeerId::random();
3396        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3397        let mut peers = PeersManager::default();
3398
3399        peers.on_incoming_pending_session(addr.ip()).unwrap();
3400        peers.on_incoming_session_established(peer_id, addr);
3401        let peer = peers.peers.get(&peer_id).unwrap();
3402        assert_eq!(peer.state, PeerConnectionState::In);
3403        assert!(peer.remove_after_disconnect);
3404
3405        // trigger discovery manually while the peer is still connected
3406        peers.add_peer(peer_id, PeerAddr::from_tcp(addr), None);
3407
3408        peers.on_active_session_gracefully_closed(peer_id);
3409
3410        let peer = peers.peers.get(&peer_id).unwrap();
3411        assert_eq!(peer.state, PeerConnectionState::Idle);
3412        assert!(!peer.remove_after_disconnect);
3413    }
3414
3415    #[tokio::test]
3416    async fn test_peer_reconnect_after_graceful_close_respects_throttle() {
3417        let throttle_duration = Duration::from_millis(100);
3418        let config =
3419            PeersConfig { incoming_ip_throttle_duration: throttle_duration, ..PeersConfig::test() };
3420        let mut peers = PeersManager::new(config);
3421
3422        let peer_id = PeerId::random();
3423        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3424
3425        // Add as regular peer
3426        peers.add_peer(peer_id, PeerAddr::from_tcp(addr), None);
3427
3428        match event!(peers) {
3429            PeerAction::PeerAdded(id) => assert_eq!(id, peer_id),
3430            _ => unreachable!(),
3431        }
3432
3433        match event!(peers) {
3434            PeerAction::Connect { .. } => {}
3435            _ => unreachable!(),
3436        }
3437
3438        // Simulate outbound connection established
3439        peers.on_active_outgoing_established(peer_id);
3440        assert_eq!(peers.peers.get(&peer_id).unwrap().state, PeerConnectionState::Out);
3441
3442        // Gracefully close the session
3443        peers.on_active_session_gracefully_closed(peer_id);
3444
3445        let peer = peers.peers.get(&peer_id).unwrap();
3446        assert_eq!(peer.state, PeerConnectionState::Idle);
3447        assert!(peer.backed_off);
3448
3449        // Verify the peer is in the backed_off_peers set
3450        assert!(peers.backed_off_peers.contains_key(&peer_id));
3451
3452        // Immediately try to poll - should not trigger any actions yet
3453        poll_fn(|cx| {
3454            assert!(peers.poll(cx).is_pending());
3455            Poll::Ready(())
3456        })
3457        .await;
3458
3459        // Peer should still be backed off
3460        assert!(peers.backed_off_peers.contains_key(&peer_id));
3461        assert!(peers.peers.get(&peer_id).unwrap().backed_off);
3462
3463        // Sleep for the throttle duration
3464        tokio::time::sleep(throttle_duration).await;
3465
3466        // After throttle duration, event! will poll until we get a Connect action
3467        match event!(peers) {
3468            PeerAction::Connect { peer_id: id, .. } => assert_eq!(id, peer_id),
3469            _ => unreachable!(),
3470        }
3471
3472        // After connection is initiated, peer should no longer be backed off
3473        assert!(!peers.backed_off_peers.contains_key(&peer_id));
3474        assert!(!peers.peers.get(&peer_id).unwrap().backed_off);
3475    }
3476
3477    #[tokio::test]
3478    async fn test_backed_off_peer_can_accept_incoming_connection() {
3479        let throttle_duration = Duration::from_millis(100);
3480        let config =
3481            PeersConfig { incoming_ip_throttle_duration: throttle_duration, ..PeersConfig::test() };
3482        let mut peers = PeersManager::new(config);
3483
3484        let peer_id = PeerId::random();
3485        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3486
3487        // Add as regular peer
3488        peers.add_peer(peer_id, PeerAddr::from_tcp(addr), None);
3489
3490        match event!(peers) {
3491            PeerAction::PeerAdded(id) => assert_eq!(id, peer_id),
3492            _ => unreachable!(),
3493        }
3494
3495        match event!(peers) {
3496            PeerAction::Connect { .. } => {}
3497            _ => unreachable!(),
3498        }
3499
3500        // Simulate outbound connection established
3501        peers.on_active_outgoing_established(peer_id);
3502        assert_eq!(peers.peers.get(&peer_id).unwrap().state, PeerConnectionState::Out);
3503
3504        // Gracefully close the session - this will back off the peer
3505        peers.on_active_session_gracefully_closed(peer_id);
3506
3507        let peer = peers.peers.get(&peer_id).unwrap();
3508        assert_eq!(peer.state, PeerConnectionState::Idle);
3509        assert!(peer.backed_off);
3510        assert!(peers.backed_off_peers.contains_key(&peer_id));
3511
3512        // Now simulate an incoming connection from the backed-off peer
3513        // First, handle the incoming pending session
3514        assert!(peers.on_incoming_pending_session(addr.ip()).is_ok());
3515        assert_eq!(peers.connection_info.num_pending_in, 1);
3516
3517        // Establish the incoming session
3518        peers.on_incoming_session_established(peer_id, addr);
3519
3520        // Peer should have been added to incoming connections
3521        assert_eq!(peers.peers.get(&peer_id).unwrap().state, PeerConnectionState::In);
3522        assert_eq!(peers.connection_info.num_inbound, 1);
3523
3524        // Peer should still be backed off for outbound connections
3525        assert!(peers.backed_off_peers.contains_key(&peer_id));
3526        assert!(peers.peers.get(&peer_id).unwrap().backed_off);
3527
3528        // Verify we don't try to reconnect outbound while peer is backed off
3529        poll_fn(|cx| {
3530            assert!(peers.poll(cx).is_pending());
3531            Poll::Ready(())
3532        })
3533        .await;
3534
3535        // No outbound connection should be attempted while backed off
3536        assert_eq!(peers.peers.get(&peer_id).unwrap().state, PeerConnectionState::In);
3537
3538        // After throttle duration, the backoff should be cleared
3539        tokio::time::sleep(throttle_duration).await;
3540
3541        poll_fn(|cx| {
3542            let _ = peers.poll(cx);
3543            Poll::Ready(())
3544        })
3545        .await;
3546
3547        // Backoff should be cleared now
3548        assert!(!peers.backed_off_peers.contains_key(&peer_id));
3549        assert!(!peers.peers.get(&peer_id).unwrap().backed_off);
3550
3551        // Peer should still be in incoming state
3552        assert_eq!(peers.peers.get(&peer_id).unwrap().state, PeerConnectionState::In);
3553    }
3554
3555    #[tokio::test]
3556    async fn test_incoming_outgoing_already_connected() {
3557        let peer_id = PeerId::random();
3558        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3559        let mut peers = PeersManager::default();
3560
3561        peers.on_incoming_pending_session(addr.ip()).unwrap();
3562        peers.add_peer(peer_id, PeerAddr::from_tcp(addr), None);
3563
3564        match event!(peers) {
3565            PeerAction::PeerAdded(_) => {}
3566            _ => unreachable!(),
3567        }
3568
3569        match event!(peers) {
3570            PeerAction::Connect { .. } => {}
3571            _ => unreachable!(),
3572        }
3573
3574        peers.on_incoming_session_established(peer_id, addr);
3575        peers.on_already_connected(Direction::Outgoing(peer_id));
3576        assert_eq!(peers.peers.get(&peer_id).unwrap().state, PeerConnectionState::In);
3577        assert_eq!(peers.connection_info.num_inbound, 1);
3578        assert_eq!(peers.connection_info.num_pending_out, 0);
3579        assert_eq!(peers.connection_info.num_pending_in, 0);
3580        assert_eq!(peers.connection_info.num_outbound, 0);
3581    }
3582
3583    #[tokio::test]
3584    async fn test_already_connected_incoming_outgoing_connection_error() {
3585        let peer_id = PeerId::random();
3586        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8009);
3587        let mut peers = PeersManager::default();
3588
3589        peers.on_incoming_pending_session(addr.ip()).unwrap();
3590        peers.add_peer(peer_id, PeerAddr::from_tcp(addr), None);
3591
3592        match event!(peers) {
3593            PeerAction::PeerAdded(_) => {}
3594            _ => unreachable!(),
3595        }
3596
3597        match event!(peers) {
3598            PeerAction::Connect { .. } => {}
3599            _ => unreachable!(),
3600        }
3601
3602        peers.on_incoming_session_established(peer_id, addr);
3603
3604        peers.on_outgoing_connection_failure(
3605            &addr,
3606            &peer_id,
3607            &io::Error::new(io::ErrorKind::ConnectionRefused, ""),
3608        );
3609        assert_eq!(peers.peers.get(&peer_id).unwrap().state, PeerConnectionState::In);
3610        assert_eq!(peers.connection_info.num_inbound, 1);
3611        assert_eq!(peers.connection_info.num_pending_out, 0);
3612        assert_eq!(peers.connection_info.num_pending_in, 0);
3613        assert_eq!(peers.connection_info.num_outbound, 0);
3614    }
3615
3616    #[tokio::test]
3617    async fn test_max_concurrent_dials() {
3618        let config = PeersConfig::default();
3619        let mut peer_manager = PeersManager::new(config);
3620        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2));
3621        let peer_addr = PeerAddr::from_tcp(SocketAddr::new(ip, 8008));
3622        for _ in 0..peer_manager.connection_info.config.max_concurrent_outbound_dials * 2 {
3623            peer_manager.add_peer(PeerId::random(), peer_addr, None);
3624        }
3625
3626        peer_manager.fill_outbound_slots();
3627        let dials = peer_manager
3628            .queued_actions
3629            .iter()
3630            .filter(|ev| matches!(ev, PeerAction::Connect { .. }))
3631            .count();
3632        assert_eq!(dials, peer_manager.connection_info.config.max_concurrent_outbound_dials);
3633    }
3634
3635    #[tokio::test]
3636    async fn test_max_num_of_pending_dials() {
3637        let config = PeersConfig::default();
3638        let mut peer_manager = PeersManager::new(config);
3639        let ip = IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2));
3640        let peer_addr = PeerAddr::from_tcp(SocketAddr::new(ip, 8008));
3641
3642        // add more peers than allowed
3643        for _ in 0..peer_manager.connection_info.config.max_concurrent_outbound_dials * 2 {
3644            peer_manager.add_peer(PeerId::random(), peer_addr, None);
3645        }
3646
3647        for _ in 0..peer_manager.connection_info.config.max_concurrent_outbound_dials * 2 {
3648            match event!(peer_manager) {
3649                PeerAction::PeerAdded(_) => {}
3650                _ => unreachable!(),
3651            }
3652        }
3653
3654        for _ in 0..peer_manager.connection_info.config.max_concurrent_outbound_dials {
3655            match event!(peer_manager) {
3656                PeerAction::Connect { .. } => {}
3657                _ => unreachable!(),
3658            }
3659        }
3660
3661        // generate 'Connect' actions
3662        peer_manager.fill_outbound_slots();
3663
3664        // all dialed connections should be in 'PendingOut' state
3665        let dials = peer_manager.connection_info.num_pending_out;
3666        assert_eq!(dials, peer_manager.connection_info.config.max_concurrent_outbound_dials);
3667
3668        let num_pendingout_states = peer_manager
3669            .peers
3670            .iter()
3671            .filter(|(_, peer)| peer.state.is_pending_out())
3672            .map(|(peer_id, _)| *peer_id)
3673            .collect::<Vec<PeerId>>();
3674        assert_eq!(
3675            num_pendingout_states.len(),
3676            peer_manager.connection_info.config.max_concurrent_outbound_dials
3677        );
3678
3679        // establish dialed connections
3680        for peer_id in &num_pendingout_states {
3681            peer_manager.on_active_outgoing_established(*peer_id);
3682        }
3683
3684        // all dialed connections should now be in 'Out' state
3685        for peer_id in &num_pendingout_states {
3686            assert_eq!(peer_manager.peers.get(peer_id).unwrap().state, PeerConnectionState::Out);
3687        }
3688
3689        // no more pending outbound connections
3690        assert_eq!(peer_manager.connection_info.num_pending_out, 0);
3691    }
3692
3693    #[tokio::test]
3694    async fn test_connect() {
3695        let peer = PeerId::random();
3696        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
3697        let mut peers = PeersManager::default();
3698        peers.add_and_connect(peer, PeerAddr::from_tcp(socket_addr), None);
3699        assert_eq!(peers.peers.get(&peer).unwrap().state, PeerConnectionState::PendingOut);
3700
3701        match event!(peers) {
3702            PeerAction::Connect { peer_id, remote_addr } => {
3703                assert_eq!(peer_id, peer);
3704                assert_eq!(remote_addr, socket_addr);
3705            }
3706            _ => unreachable!(),
3707        }
3708
3709        let (record, _) = peers.peer_by_id(peer).unwrap();
3710        assert_eq!(record.tcp_addr(), socket_addr);
3711        assert_eq!(record.udp_addr(), socket_addr);
3712
3713        // connect again
3714        peers.add_and_connect(peer, PeerAddr::from_tcp(socket_addr), None);
3715
3716        let (record, _) = peers.peer_by_id(peer).unwrap();
3717        assert_eq!(record.tcp_addr(), socket_addr);
3718        assert_eq!(record.udp_addr(), socket_addr);
3719    }
3720
3721    #[tokio::test]
3722    async fn test_incoming_connection_from_banned() {
3723        let peer = PeerId::random();
3724        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
3725        let config = PeersConfig::test().with_max_inbound(3);
3726        let mut peers = PeersManager::new(config);
3727        peers.add_peer(peer, PeerAddr::from_tcp(socket_addr), None);
3728
3729        match event!(peers) {
3730            PeerAction::PeerAdded(peer_id) => {
3731                assert_eq!(peer_id, peer);
3732            }
3733            _ => unreachable!(),
3734        }
3735        match event!(peers) {
3736            PeerAction::Connect { peer_id, .. } => {
3737                assert_eq!(peer_id, peer);
3738            }
3739            _ => unreachable!(),
3740        }
3741
3742        poll_fn(|cx| {
3743            assert!(peers.poll(cx).is_pending());
3744            Poll::Ready(())
3745        })
3746        .await;
3747
3748        // simulate new connection drops with error
3749        loop {
3750            peers.on_active_session_dropped(
3751                &socket_addr,
3752                &peer,
3753                &EthStreamError::InvalidMessage(reth_eth_wire::message::MessageError::Invalid(
3754                    reth_eth_wire::EthVersion::Eth68,
3755                    reth_eth_wire::EthMessageID::Status,
3756                )),
3757            );
3758
3759            if peers.peers.get(&peer).unwrap().is_banned() {
3760                break;
3761            }
3762
3763            assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
3764            peers.on_incoming_session_established(peer, socket_addr);
3765
3766            match event!(peers) {
3767                PeerAction::Connect { peer_id, .. } => {
3768                    assert_eq!(peer_id, peer);
3769                }
3770                _ => unreachable!(),
3771            }
3772        }
3773
3774        assert!(peers.peers.get(&peer).unwrap().is_banned());
3775
3776        // fill all incoming slots
3777        for _ in 0..peers.connection_info.config.max_inbound {
3778            assert!(peers.on_incoming_pending_session(socket_addr.ip()).is_ok());
3779            peers.on_incoming_session_established(peer, socket_addr);
3780
3781            match event!(peers) {
3782                PeerAction::DisconnectBannedIncoming { peer_id } => {
3783                    assert_eq!(peer_id, peer);
3784                }
3785                _ => unreachable!(),
3786            }
3787        }
3788
3789        poll_fn(|cx| {
3790            assert!(peers.poll(cx).is_pending());
3791            Poll::Ready(())
3792        })
3793        .await;
3794
3795        assert_eq!(peers.connection_info.num_inbound, 0);
3796
3797        let new_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 3)), 8008);
3798
3799        // Assert we can still accept new connections
3800        assert!(peers.on_incoming_pending_session(new_addr.ip()).is_ok());
3801        assert_eq!(peers.connection_info.num_pending_in, 1);
3802
3803        // the triggered DisconnectBannedIncoming will result in dropped connections, assert that
3804        // connection info is updated via the peer's state which would be a noop here since the
3805        // banned peer's state is idle
3806        peers.on_active_session_gracefully_closed(peer);
3807        assert_eq!(peers.connection_info.num_inbound, 0);
3808    }
3809
3810    #[tokio::test]
3811    async fn test_add_pending_connect() {
3812        let peer = PeerId::random();
3813        let socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
3814        let mut peers = PeersManager::default();
3815        peers.add_and_connect(peer, PeerAddr::from_tcp(socket_addr), None);
3816        assert_eq!(peers.peers.get(&peer).unwrap().state, PeerConnectionState::PendingOut);
3817        assert_eq!(peers.connection_info.num_pending_out, 1);
3818    }
3819
3820    #[tokio::test]
3821    async fn test_dns_updates_peer_address() {
3822        let peer_id = PeerId::random();
3823        let initial_socket = SocketAddr::new("1.1.1.1".parse::<IpAddr>().unwrap(), 8008);
3824        let updated_ip = "2.2.2.2".parse::<IpAddr>().unwrap();
3825
3826        let trusted = TrustedPeer {
3827            host: url::Host::Ipv4("2.2.2.2".parse().unwrap()),
3828            tcp_port: 8008,
3829            udp_port: 8008,
3830            id: peer_id,
3831        };
3832
3833        let config = PeersConfig::test().with_trusted_nodes(vec![trusted.clone()]);
3834        let mut manager = PeersManager::new(config);
3835        manager
3836            .trusted_peers_resolver
3837            .set_interval(tokio::time::interval(Duration::from_millis(1)));
3838
3839        manager.peers.insert(
3840            peer_id,
3841            Peer::trusted(PeerAddr::new_with_ports(initial_socket.ip(), 8008, Some(8008))),
3842        );
3843
3844        for _ in 0..100 {
3845            let _ = event!(manager);
3846            if manager.peers.get(&peer_id).unwrap().addr.tcp().ip() == updated_ip {
3847                break;
3848            }
3849            tokio::time::sleep(Duration::from_millis(10)).await;
3850        }
3851
3852        let updated_peer = manager.peers.get(&peer_id).unwrap();
3853        assert_eq!(updated_peer.addr.tcp().ip(), updated_ip);
3854    }
3855
3856    #[tokio::test]
3857    async fn test_ip_filter_blocks_inbound_connection() {
3858        use std::net::IpAddr;
3859
3860        // Create a filter that only allows 192.168.0.0/16
3861        let ip_filter = IpFilter::from_cidr_string("192.168.0.0/16").unwrap();
3862        let config = PeersConfig::test().with_ip_filter(ip_filter);
3863        let mut peers = PeersManager::new(config);
3864
3865        // Try to connect from an allowed IP
3866        let allowed_ip: IpAddr = "192.168.1.100".parse().unwrap();
3867        assert!(peers.on_incoming_pending_session(allowed_ip).is_ok());
3868
3869        // Try to connect from a disallowed IP
3870        let disallowed_ip: IpAddr = "10.0.0.1".parse().unwrap();
3871        assert!(peers.on_incoming_pending_session(disallowed_ip).is_err());
3872    }
3873
3874    #[tokio::test]
3875    async fn test_ip_filter_blocks_outbound_connection() {
3876        use std::net::SocketAddr;
3877
3878        // Create a filter that only allows 192.168.0.0/16
3879        let ip_filter = IpFilter::from_cidr_string("192.168.0.0/16").unwrap();
3880        let config = PeersConfig::test().with_ip_filter(ip_filter);
3881        let mut peers = PeersManager::new(config);
3882
3883        let peer_id = PeerId::repeat_byte(1);
3884
3885        // Try to add a peer with an allowed IP
3886        let allowed_addr: SocketAddr = "192.168.1.100:30303".parse().unwrap();
3887        peers.add_peer(peer_id, PeerAddr::from_tcp(allowed_addr), None);
3888        assert!(peers.peers.contains_key(&peer_id));
3889
3890        // Try to add a peer with a disallowed IP
3891        let peer_id2 = PeerId::repeat_byte(2);
3892        let disallowed_addr: SocketAddr = "10.0.0.1:30303".parse().unwrap();
3893        peers.add_peer(peer_id2, PeerAddr::from_tcp(disallowed_addr), None);
3894        assert!(!peers.peers.contains_key(&peer_id2));
3895    }
3896
3897    #[tokio::test]
3898    async fn test_ip_filter_ipv6() {
3899        use std::net::IpAddr;
3900
3901        // Create a filter that only allows IPv6 range 2001:db8::/32
3902        let ip_filter = IpFilter::from_cidr_string("2001:db8::/32").unwrap();
3903        let config = PeersConfig::test().with_ip_filter(ip_filter);
3904        let mut peers = PeersManager::new(config);
3905
3906        // Try to connect from an allowed IPv6 address
3907        let allowed_ip: IpAddr = "2001:db8::1".parse().unwrap();
3908        assert!(peers.on_incoming_pending_session(allowed_ip).is_ok());
3909
3910        // Try to connect from a disallowed IPv6 address
3911        let disallowed_ip: IpAddr = "2001:db9::1".parse().unwrap();
3912        assert!(peers.on_incoming_pending_session(disallowed_ip).is_err());
3913    }
3914
3915    #[tokio::test]
3916    async fn test_ip_filter_multiple_ranges() {
3917        use std::net::IpAddr;
3918
3919        // Create a filter that allows multiple ranges
3920        let ip_filter = IpFilter::from_cidr_string("192.168.0.0/16,10.0.0.0/8").unwrap();
3921        let config = PeersConfig::test().with_ip_filter(ip_filter);
3922        let mut peers = PeersManager::new(config);
3923
3924        // Try IPs from both allowed ranges
3925        let ip1: IpAddr = "192.168.1.1".parse().unwrap();
3926        let ip2: IpAddr = "10.5.10.20".parse().unwrap();
3927        assert!(peers.on_incoming_pending_session(ip1).is_ok());
3928        assert!(peers.on_incoming_pending_session(ip2).is_ok());
3929
3930        // Try IP from disallowed range
3931        let disallowed_ip: IpAddr = "172.16.0.1".parse().unwrap();
3932        assert!(peers.on_incoming_pending_session(disallowed_ip).is_err());
3933    }
3934
3935    #[tokio::test]
3936    async fn test_ip_filter_no_restriction() {
3937        use std::net::IpAddr;
3938
3939        // Create a filter with no restrictions (allow all)
3940        let ip_filter = IpFilter::allow_all();
3941        let config = PeersConfig::test().with_ip_filter(ip_filter);
3942        let mut peers = PeersManager::new(config);
3943
3944        // All IPs should be allowed
3945        let ip1: IpAddr = "192.168.1.1".parse().unwrap();
3946        let ip2: IpAddr = "10.0.0.1".parse().unwrap();
3947        let ip3: IpAddr = "8.8.8.8".parse().unwrap();
3948        assert!(peers.on_incoming_pending_session(ip1).is_ok());
3949        assert!(peers.on_incoming_pending_session(ip2).is_ok());
3950        assert!(peers.on_incoming_pending_session(ip3).is_ok());
3951    }
3952
3953    #[tokio::test]
3954    async fn test_ip_filter_skips_configured_peers() {
3955        let allowed = NodeRecord::new("192.168.1.1:30303".parse().unwrap(), PeerId::random());
3956        let trusted = NodeRecord::new("10.0.0.1:30303".parse().unwrap(), PeerId::random());
3957        let persisted = NodeRecord::new("10.0.0.2:30303".parse().unwrap(), PeerId::random());
3958        let basic = NodeRecord::new("10.0.0.3:30303".parse().unwrap(), PeerId::random());
3959
3960        let mut config = PeersConfig::test()
3961            .with_ip_filter(IpFilter::from_cidr_string("192.168.0.0/16").unwrap())
3962            .with_trusted_nodes(vec![trusted.into()])
3963            .with_basic_nodes(std::iter::once(basic).collect());
3964        config.persisted_peers =
3965            [allowed, persisted].into_iter().map(PersistedPeerInfo::from_node_record).collect();
3966        let mut peers = PeersManager::new(config);
3967
3968        assert_eq!(peers.peers.keys().collect::<Vec<_>>(), [&allowed.id]);
3969        assert!(peers.trusted_peer_ids.contains(&trusted.id));
3970        assert_eq!(
3971            peers.persistable_peers().map(|peer| peer.record).collect::<Vec<_>>(),
3972            [allowed]
3973        );
3974        peers.fill_outbound_slots();
3975        assert!(
3976            matches!(peers.queued_actions.pop_front(), Some(PeerAction::Connect { peer_id, remote_addr })
3977            if peer_id == allowed.id && remote_addr == allowed.tcp_addr())
3978        );
3979        assert!(peers.queued_actions.is_empty());
3980
3981        peers.on_resolved_peer(trusted.id, trusted);
3982        assert!(!peers.peers.contains_key(&trusted.id));
3983        let resolved = NodeRecord::new("192.168.1.2:30303".parse().unwrap(), trusted.id);
3984        peers.on_resolved_peer(trusted.id, resolved);
3985        peers.on_resolved_peer(trusted.id, trusted);
3986        assert_eq!(peers.peers[&trusted.id].addr.tcp(), resolved.tcp_addr());
3987    }
3988
3989    #[tokio::test]
3990    async fn test_best_unconnected_prefers_fork_id_as_tiebreaker() {
3991        let mut peers = PeersManager::default();
3992        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8008);
3993
3994        let fork_id = ForkId { hash: ForkHash([0xaa, 0xbb, 0xcc, 0xdd]), next: 0 };
3995
3996        // add two peers with equal reputation, only one has a fork_id
3997        let no_fork = PeerId::random();
3998        peers.add_peer(no_fork, PeerAddr::from_tcp(addr), None);
3999
4000        let with_fork = PeerId::random();
4001        peers.add_peer(with_fork, PeerAddr::from_tcp(addr), None);
4002        peers.peers.get_mut(&with_fork).unwrap().fork_id = Some(Box::new(fork_id));
4003
4004        let (best_id, _) = peers.best_unconnected(false).unwrap();
4005        assert_eq!(best_id, with_fork, "fork_id should break tie when reputation is equal");
4006    }
4007
4008    #[tokio::test]
4009    async fn test_add_trusted_peer_node_resolves_absent_peer() {
4010        let peer_id = PeerId::random();
4011        let trusted = TrustedPeer {
4012            host: url::Host::Domain("example.invalid".to_string()),
4013            tcp_port: 30303,
4014            udp_port: 30303,
4015            id: peer_id,
4016        };
4017
4018        let mut manager = PeersManager::default();
4019        manager.add_trusted_peer_node(trusted);
4020
4021        assert!(manager.trusted_peer_ids.contains(&peer_id));
4022        assert_eq!(manager.trusted_peers_resolver.trusted_peers.len(), 1);
4023        assert!(!manager.peers.contains_key(&peer_id));
4024
4025        let resolved = NodeRecord {
4026            address: "10.0.0.1".parse::<IpAddr>().unwrap(),
4027            tcp_port: 30303,
4028            udp_port: 30303,
4029            id: peer_id,
4030        };
4031        manager.on_resolved_peer(peer_id, resolved);
4032
4033        let peer = manager.peers.get(&peer_id).expect("peer should be added after resolution");
4034        assert!(peer.kind.is_trusted());
4035        assert_eq!(peer.addr.tcp().ip(), "10.0.0.1".parse::<IpAddr>().unwrap());
4036    }
4037
4038    #[tokio::test]
4039    async fn test_configured_trusted_peer_resolves_after_startup_failure() {
4040        let peer_id = PeerId::random();
4041        let trusted = TrustedPeer::new(Host::Domain("example.invalid".into()), 30303, peer_id);
4042        let mut manager = PeersManager::new(PeersConfig::test().with_trusted_nodes(vec![trusted]));
4043        assert!(!manager.peers.contains_key(&peer_id));
4044
4045        let addr = "10.0.0.1:30303".parse::<SocketAddr>().unwrap();
4046        manager.on_resolved_peer(peer_id, NodeRecord::new(addr, peer_id));
4047        let peer = manager.peers.get(&peer_id).expect("peer should be added after resolution");
4048        assert!(peer.is_trusted());
4049        assert_eq!(peer.addr.tcp(), addr);
4050    }
4051
4052    #[tokio::test]
4053    async fn test_unresolved_trusted_peer_promotes_persisted_entry() {
4054        let peer_id = PeerId::random();
4055        let trusted = TrustedPeer::new(Host::Domain("example.invalid".into()), 30303, peer_id);
4056        let mut config = PeersConfig::test().with_trusted_nodes(vec![trusted]);
4057        config.persisted_peers.push(PersistedPeerInfo {
4058            record: NodeRecord::new("10.0.0.1:30303".parse().unwrap(), peer_id),
4059            kind: PeerKind::Basic,
4060            fork_id: None,
4061            reputation: 0,
4062        });
4063        let manager = PeersManager::new(config);
4064        assert!(manager.trusted_peer_ids.contains(&peer_id));
4065        assert!(manager.peers.get(&peer_id).unwrap().is_trusted());
4066    }
4067
4068    #[tokio::test]
4069    async fn test_unresolved_trusted_peer_inbound_then_resolved() {
4070        let peer_id = PeerId::random();
4071        let trusted = TrustedPeer::new(Host::Domain("example.invalid".into()), 30303, peer_id);
4072        let mut manager = PeersManager::new(
4073            PeersConfig::test().with_trusted_nodes(vec![trusted]).with_trusted_nodes_only(true),
4074        );
4075
4076        let inbound = "10.0.0.1:41234".parse::<SocketAddr>().unwrap();
4077        assert!(manager.on_incoming_pending_session(inbound.ip()).is_ok());
4078        manager.on_incoming_session_established(peer_id, inbound);
4079        assert!(manager.peers.get(&peer_id).unwrap().is_trusted());
4080
4081        let addr = "10.0.0.1:30303".parse::<SocketAddr>().unwrap();
4082        manager.on_resolved_peer(peer_id, NodeRecord::new(addr, peer_id));
4083        let peer = manager.peers.get(&peer_id).unwrap();
4084        assert!(peer.is_trusted());
4085        assert!(!peer.remove_after_disconnect);
4086        assert_eq!(peer.addr.tcp(), addr);
4087    }
4088
4089    #[tokio::test]
4090    async fn test_removed_trusted_peer_ignores_late_resolution() {
4091        let peer_id = PeerId::random();
4092        let trusted = TrustedPeer {
4093            host: url::Host::Domain("example.invalid".to_string()),
4094            tcp_port: 30303,
4095            udp_port: 30303,
4096            id: peer_id,
4097        };
4098
4099        let mut manager = PeersManager::default();
4100        manager.add_trusted_peer_node(trusted);
4101        manager.remove_peer_from_trusted_set(peer_id);
4102
4103        let resolved = NodeRecord {
4104            address: "10.0.0.1".parse::<IpAddr>().unwrap(),
4105            tcp_port: 30303,
4106            udp_port: 30303,
4107            id: peer_id,
4108        };
4109        manager.on_resolved_peer(peer_id, resolved);
4110
4111        assert!(!manager.peers.contains_key(&peer_id));
4112        assert!(!manager.trusted_peer_ids.contains(&peer_id));
4113    }
4114
4115    #[tokio::test]
4116    async fn test_resolution_promotes_basic_trusted_peer() {
4117        let peer_id = PeerId::random();
4118        let trusted = TrustedPeer {
4119            host: url::Host::Domain("example.invalid".to_string()),
4120            tcp_port: 30303,
4121            udp_port: 30303,
4122            id: peer_id,
4123        };
4124        let addr = "10.0.0.1:30303".parse::<SocketAddr>().unwrap();
4125
4126        let mut manager = PeersManager::default();
4127        manager.add_trusted_peer_node(trusted);
4128        manager.add_peer_kind(peer_id, Some(PeerKind::Basic), PeerAddr::from_tcp(addr), None);
4129        assert_eq!(manager.peers[&peer_id].kind, PeerKind::Basic);
4130        manager.on_resolved_peer(peer_id, NodeRecord::new(addr, peer_id));
4131        assert!(manager.peers[&peer_id].is_trusted());
4132    }
4133
4134    #[tokio::test]
4135    async fn test_rotation_disconnects_eligible_peer() {
4136        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
4137        let peer = PeerId::random();
4138        let mut peers = PeersManager::new(
4139            PeersConfig::test()
4140                .with_max_outbound(1)
4141                .with_peer_rotation_interval(Some(Duration::from_millis(50))),
4142        );
4143
4144        peers.add_peer(peer, PeerAddr::from_tcp(addr), None);
4145        match event!(peers) {
4146            PeerAction::PeerAdded(_) => {}
4147            _ => unreachable!(),
4148        }
4149        match event!(peers) {
4150            PeerAction::Connect { .. } => {}
4151            _ => unreachable!(),
4152        }
4153        peers.on_active_outgoing_established(peer);
4154
4155        set_connected_at(
4156            &mut peers,
4157            peer,
4158            std::time::Instant::now() - Duration::from_secs(11 * 60),
4159        );
4160
4161        tokio::time::sleep(Duration::from_millis(100)).await;
4162
4163        match event!(peers) {
4164            PeerAction::Disconnect { peer_id, reason } => {
4165                assert_eq!(peer_id, peer);
4166                assert_eq!(reason, Some(DisconnectReason::UselessPeer));
4167            }
4168            _ => unreachable!(),
4169        }
4170    }
4171
4172    #[tokio::test]
4173    async fn test_rotation_then_remove_uses_active_session_removal() {
4174        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 7)), 8008);
4175        let peer = PeerId::random();
4176        let mut peers = PeersManager::new(
4177            PeersConfig::test()
4178                .with_max_outbound(1)
4179                .with_peer_rotation_interval(Some(Duration::from_millis(50))),
4180        );
4181
4182        peers.add_peer(peer, PeerAddr::from_tcp(addr), None);
4183        match event!(peers) {
4184            PeerAction::PeerAdded(_) => {}
4185            _ => unreachable!(),
4186        }
4187        match event!(peers) {
4188            PeerAction::Connect { .. } => {}
4189            _ => unreachable!(),
4190        }
4191        peers.on_active_outgoing_established(peer);
4192        set_connected_at(
4193            &mut peers,
4194            peer,
4195            std::time::Instant::now() - Duration::from_secs(11 * 60),
4196        );
4197
4198        tokio::time::sleep(Duration::from_millis(100)).await;
4199
4200        match event!(peers) {
4201            PeerAction::Disconnect { peer_id, reason } => {
4202                assert_eq!(peer_id, peer);
4203                assert_eq!(reason, Some(DisconnectReason::UselessPeer));
4204            }
4205            _ => unreachable!(),
4206        }
4207        assert_eq!(peers.peers.get(&peer).unwrap().state, PeerConnectionState::Out);
4208        assert_eq!(peers.connection_info.num_outbound, 1);
4209
4210        peers.remove_peer(peer);
4211        match event!(peers) {
4212            PeerAction::PeerRemoved(peer_id) => assert_eq!(peer_id, peer),
4213            _ => unreachable!(),
4214        }
4215        match event!(peers) {
4216            PeerAction::Disconnect { peer_id, reason } => {
4217                assert_eq!(peer_id, peer);
4218                assert_eq!(reason, Some(DisconnectReason::DisconnectRequested));
4219            }
4220            _ => unreachable!(),
4221        }
4222
4223        let p = peers.peers.get(&peer).unwrap();
4224        assert_eq!(p.state, PeerConnectionState::DisconnectingOut);
4225        assert!(p.remove_after_disconnect);
4226        assert_eq!(peers.connection_info.num_outbound, 1);
4227
4228        peers.on_active_session_gracefully_closed(peer);
4229        assert_eq!(peers.connection_info.num_outbound, 0);
4230        assert!(!peers.peers.contains_key(&peer));
4231    }
4232
4233    #[tokio::test]
4234    async fn test_rotation_skips_trusted_peers() {
4235        let _addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 3)), 8008);
4236        let peer = PeerId::random();
4237        let trusted = TrustedPeer {
4238            host: Host::Ipv4(Ipv4Addr::new(127, 0, 1, 3)),
4239            tcp_port: 8008,
4240            udp_port: 8008,
4241            id: peer,
4242        };
4243        let mut peers = PeersManager::new(
4244            PeersConfig::test()
4245                .with_max_outbound(1)
4246                .with_trusted_nodes(vec![trusted])
4247                .with_peer_rotation_interval(Some(Duration::from_millis(50))),
4248        );
4249
4250        match event!(peers) {
4251            PeerAction::Connect { .. } => {}
4252            _ => unreachable!(),
4253        }
4254        peers.on_active_outgoing_established(peer);
4255        set_connected_at(
4256            &mut peers,
4257            peer,
4258            std::time::Instant::now() - Duration::from_secs(11 * 60),
4259        );
4260
4261        tokio::time::sleep(Duration::from_millis(100)).await;
4262
4263        poll_fn(|cx| {
4264            assert!(peers.poll(cx).is_pending(), "trusted peer must not be rotated");
4265            Poll::Ready(())
4266        })
4267        .await;
4268    }
4269
4270    #[tokio::test]
4271    async fn test_rotation_skips_recently_connected_peers() {
4272        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 4)), 8008);
4273        let peer = PeerId::random();
4274        let mut peers = PeersManager::new(
4275            PeersConfig::test()
4276                .with_max_outbound(1)
4277                .with_peer_rotation_interval(Some(Duration::from_millis(50))),
4278        );
4279
4280        peers.add_peer(peer, PeerAddr::from_tcp(addr), None);
4281        match event!(peers) {
4282            PeerAction::PeerAdded(_) => {}
4283            _ => unreachable!(),
4284        }
4285        match event!(peers) {
4286            PeerAction::Connect { .. } => {}
4287            _ => unreachable!(),
4288        }
4289        peers.on_active_outgoing_established(peer);
4290
4291        tokio::time::sleep(Duration::from_millis(100)).await;
4292
4293        poll_fn(|cx| {
4294            assert!(peers.poll(cx).is_pending(), "recently connected peer must not be rotated");
4295            Poll::Ready(())
4296        })
4297        .await;
4298    }
4299
4300    #[tokio::test]
4301    async fn test_rotation_skips_when_slots_available() {
4302        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 5)), 8008);
4303        let peer = PeerId::random();
4304        let mut peers = PeersManager::new(
4305            PeersConfig::test()
4306                .with_max_outbound(2)
4307                .with_peer_rotation_interval(Some(Duration::from_millis(50))),
4308        );
4309
4310        peers.add_peer(peer, PeerAddr::from_tcp(addr), None);
4311        match event!(peers) {
4312            PeerAction::PeerAdded(_) => {}
4313            _ => unreachable!(),
4314        }
4315        match event!(peers) {
4316            PeerAction::Connect { .. } => {}
4317            _ => unreachable!(),
4318        }
4319        peers.on_active_outgoing_established(peer);
4320        set_connected_at(
4321            &mut peers,
4322            peer,
4323            std::time::Instant::now() - Duration::from_secs(11 * 60),
4324        );
4325
4326        tokio::time::sleep(Duration::from_millis(100)).await;
4327
4328        poll_fn(|cx| {
4329            assert!(
4330                peers.poll(cx).is_pending(),
4331                "rotation must not fire when outbound slots are available"
4332            );
4333            Poll::Ready(())
4334        })
4335        .await;
4336    }
4337
4338    #[tokio::test]
4339    async fn test_rotation_disconnects_inbound_peer() {
4340        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 6)), 8008);
4341        let peer = PeerId::random();
4342        let mut peers = PeersManager::new(
4343            PeersConfig::test()
4344                .with_max_inbound(1)
4345                .with_peer_rotation_interval(Some(Duration::from_millis(50))),
4346        );
4347
4348        assert!(peers.on_incoming_pending_session(addr.ip()).is_ok());
4349        peers.on_incoming_session_established(peer, addr);
4350
4351        match event!(peers) {
4352            PeerAction::PeerAdded(_) => {}
4353            _ => unreachable!(),
4354        }
4355
4356        set_connected_at(
4357            &mut peers,
4358            peer,
4359            std::time::Instant::now() - Duration::from_secs(11 * 60),
4360        );
4361
4362        tokio::time::sleep(Duration::from_millis(100)).await;
4363
4364        match event!(peers) {
4365            PeerAction::Disconnect { peer_id, reason } => {
4366                assert_eq!(peer_id, peer);
4367                assert_eq!(reason, Some(DisconnectReason::UselessPeer));
4368            }
4369            _ => unreachable!(),
4370        }
4371    }
4372
4373    // Ensures explicitly added peers are dialed right away, while discovered peers wait for the
4374    // next refill tick.
4375    #[tokio::test]
4376    async fn test_requested_peer_is_dialed_before_refill_tick() {
4377        let mut peers = PeersManager::new(PeersConfig {
4378            refill_slots_interval: Duration::from_secs(60),
4379            ..PeersConfig::test()
4380        });
4381        // consume the initial refill tick
4382        assert!(poll_now(&mut peers).is_pending());
4383
4384        let discovered = PeerId::random();
4385        let discovered_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 1)), 8008);
4386        peers.add_peer(discovered, PeerAddr::from_tcp(discovered_addr), None);
4387        assert!(
4388            matches!(poll_now(&mut peers), Poll::Ready(PeerAction::PeerAdded(id)) if id == discovered)
4389        );
4390        assert!(poll_now(&mut peers).is_pending());
4391
4392        let requested = PeerId::random();
4393        let requested_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 1, 2)), 8008);
4394        peers.handle().add_peer(requested, requested_addr);
4395        assert!(
4396            matches!(poll_now(&mut peers), Poll::Ready(PeerAction::PeerAdded(id)) if id == requested)
4397        );
4398
4399        // the requested peer fills all free outbound slots, including one for the discovered peer
4400        let mut dialed = Vec::new();
4401        while let Poll::Ready(PeerAction::Connect { peer_id, .. }) = poll_now(&mut peers) {
4402            dialed.push(peer_id);
4403        }
4404        dialed.sort();
4405        let mut expected = vec![discovered, requested];
4406        expected.sort();
4407        assert_eq!(dialed, expected);
4408    }
4409
4410    #[tokio::test]
4411    async fn test_revoke_trust_independent_of_peer_kind() {
4412        for kind in [None, Some(PeerKind::Basic), Some(PeerKind::Static), Some(PeerKind::Trusted)] {
4413            let mut peers = PeersManager::new(PeersConfig::test());
4414            let peer_id = PeerId::random();
4415            peers.add_trusted_peer_id(peer_id);
4416            if let Some(kind) = kind {
4417                peers.add_peer_kind(
4418                    peer_id,
4419                    Some(kind),
4420                    PeerAddr::from_tcp("127.0.0.1:8008".parse().unwrap()),
4421                    None,
4422                );
4423            }
4424            peers.remove_peer_from_trusted_set(peer_id);
4425            assert!(!peers.trusted_peer_ids.contains(&peer_id));
4426            assert_eq!(
4427                peers.peers.get(&peer_id).map(|peer| peer.kind),
4428                kind.map(|kind| if kind == PeerKind::Trusted { PeerKind::Basic } else { kind })
4429            );
4430            // Revocation also removes the administrative ban exemption.
4431            peers.ban_peer_by_admin(peer_id);
4432            assert!(peers.ban_list.is_banned_peer(&peer_id));
4433        }
4434    }
4435
4436    #[tokio::test]
4437    async fn test_persisted_trust_controls_inbound_admission() {
4438        for kind in [PeerKind::Basic, PeerKind::Static, PeerKind::Trusted] {
4439            for trusted_only in [false, true] {
4440                let peer_id = PeerId::random();
4441                let addr = "127.0.0.1:8008".parse::<SocketAddr>().unwrap();
4442                let mut config = PeersConfig::test().with_trusted_nodes_only(trusted_only);
4443                config.connection_info.max_inbound = 0;
4444                config.persisted_peers.push(PersistedPeerInfo {
4445                    record: NodeRecord::new(addr, peer_id),
4446                    kind,
4447                    fork_id: None,
4448                    reputation: 0,
4449                });
4450                let mut peers = PeersManager::new(config);
4451                assert_eq!(peers.trusted_peer_ids.contains(&peer_id), kind.is_trusted());
4452                peers.connection_info.inc_pending_in();
4453                peers.on_incoming_session_established(peer_id, addr);
4454                if kind.is_trusted() {
4455                    assert!(peers.queued_actions.is_empty());
4456                    assert_eq!(peers.connection_info.num_inbound, 1);
4457                } else if trusted_only {
4458                    assert!(matches!(peers.queued_actions.pop_front(),
4459                        Some(PeerAction::DisconnectUntrustedIncoming { peer_id: id }) if id == peer_id));
4460                } else {
4461                    assert!(matches!(peers.queued_actions.pop_front(),
4462                        Some(PeerAction::Disconnect { peer_id: id, reason: Some(DisconnectReason::TooManyPeers) }) if id == peer_id));
4463                }
4464            }
4465        }
4466    }
4467
4468    #[tokio::test]
4469    async fn test_filtered_persisted_peer_does_not_restore_trust() {
4470        let peer_id = PeerId::random();
4471        let mut config = PeersConfig::test();
4472        config.enforce_enr_fork_id = true;
4473        config.persisted_peers.push(PersistedPeerInfo {
4474            record: NodeRecord::new("127.0.0.1:8008".parse().unwrap(), peer_id),
4475            kind: PeerKind::Trusted,
4476            fork_id: None,
4477            reputation: 0,
4478        });
4479        let peers = PeersManager::new(config);
4480        assert!(!peers.trusted_peer_ids.contains(&peer_id));
4481        assert!(!peers.peers.contains_key(&peer_id));
4482    }
4483    #[tokio::test]
4484    async fn test_pending_dials_reserve_outbound_capacity() {
4485        for max_outbound in [0, 1, 3] {
4486            let mut peers = PeersManager::new(PeersConfig::test().with_max_outbound(max_outbound));
4487            let addr = PeerAddr::from_tcp("127.0.0.1:8008".parse().unwrap());
4488            for _ in 0..30 {
4489                peers.add_peer(PeerId::random(), addr, None);
4490            }
4491            peers.fill_outbound_slots();
4492            let dialed = peers
4493                .queued_actions
4494                .iter()
4495                .filter_map(|action| match action {
4496                    PeerAction::Connect { peer_id, .. } => Some(*peer_id),
4497                    _ => None,
4498                })
4499                .collect::<Vec<_>>();
4500            assert_eq!(dialed.len(), max_outbound);
4501            peers.queued_actions.clear();
4502            for peer in dialed {
4503                peers.on_active_outgoing_established(peer);
4504                peers.fill_outbound_slots();
4505                assert!(peers.queued_actions.is_empty());
4506            }
4507            assert_eq!(peers.connection_info.num_outbound, max_outbound);
4508            assert_eq!(peers.connection_info.num_pending_out, 0);
4509        }
4510    }
4511
4512    #[tokio::test]
4513    async fn test_surplus_outbound_completion() {
4514        for kind in [PeerKind::Basic, PeerKind::Trusted, PeerKind::Static] {
4515            let mut peers = PeersManager::new(PeersConfig::test().with_max_outbound(0));
4516            let peer = PeerId::random();
4517            let addr = PeerAddr::from_tcp("127.0.0.1:8008".parse().unwrap());
4518            peers.add_and_connect_kind(peer, kind, addr, None);
4519            peers.queued_actions.clear();
4520            peers.on_active_outgoing_established(peer);
4521            if kind == PeerKind::Basic {
4522                assert!(matches!(
4523                    peers.queued_actions.pop_front(),
4524                    Some(PeerAction::Disconnect {
4525                        peer_id,
4526                        reason: Some(DisconnectReason::TooManyPeers),
4527                    }) if peer_id == peer
4528                ));
4529            } else {
4530                assert!(peers.queued_actions.is_empty());
4531            }
4532            // The closing session releases the accounting reserved at establishment.
4533            peers.on_active_session_gracefully_closed(peer);
4534            assert_eq!(peers.connection_info.num_outbound, 0);
4535            assert_eq!(peers.connection_info.num_pending_out, 0);
4536        }
4537    }
4538
4539    #[tokio::test]
4540    async fn test_surplus_outbound_preserves_id_trusted_peers() {
4541        for hostname in [false, true] {
4542            let mut peers = PeersManager::new(PeersConfig::test().with_max_outbound(0));
4543            let peer_id = PeerId::random();
4544            let addr = PeerAddr::from_tcp("127.0.0.1:8008".parse().unwrap());
4545            if hostname {
4546                peers.add_peer(peer_id, addr, None);
4547                peers.add_trusted_peer_node(TrustedPeer {
4548                    host: Host::Domain("example.invalid".to_string()),
4549                    tcp_port: 8008,
4550                    udp_port: 8008,
4551                    id: peer_id,
4552                });
4553            } else {
4554                peers.add_trusted_peer_id(peer_id);
4555            }
4556            peers.add_and_connect_kind(peer_id, PeerKind::Basic, addr, None);
4557            assert_eq!(peers.peers[&peer_id].kind, PeerKind::Basic);
4558            peers.queued_actions.clear();
4559
4560            peers.on_active_outgoing_established(peer_id);
4561
4562            assert!(peers.queued_actions.is_empty());
4563            assert_eq!(peers.num_outbound_connections(), 1);
4564            peers.on_active_session_gracefully_closed(peer_id);
4565            assert_eq!(peers.num_outbound_connections(), 0);
4566            assert_eq!(peers.num_pending_outbound_connections(), 0);
4567        }
4568    }
4569
4570    #[tokio::test]
4571    async fn test_pending_outbound_cleanup_preserves_incoming_session() {
4572        let mut peers = PeersManager::new(PeersConfig::test());
4573        let peer_id = PeerId::random();
4574        let addr = "127.0.0.1:8008".parse::<SocketAddr>().unwrap();
4575        peers.add_and_connect_kind(peer_id, PeerKind::Basic, PeerAddr::from_tcp(addr), None);
4576        peers.on_incoming_pending_session(addr.ip()).unwrap();
4577        peers.on_incoming_session_established(peer_id, addr);
4578        let connected_at = peers.peers[&peer_id].connected_at;
4579
4580        peers.on_outgoing_pending_session_gracefully_closed(&peer_id);
4581
4582        assert_eq!(peers.peers[&peer_id].state, PeerConnectionState::In);
4583        assert_eq!(peers.peers[&peer_id].connected_at, connected_at);
4584        assert_eq!(peers.connection_info.num_inbound, 1);
4585        assert_eq!(peers.num_pending_outbound_connections(), 0);
4586    }
4587
4588    #[tokio::test]
4589    async fn test_inbound_capacity_preserves_pending_outbound_and_trusted_exemption() {
4590        for trusted in [false, true] {
4591            let mut peers = PeersManager::new(PeersConfig::test().with_max_inbound(0));
4592            let peer_id = PeerId::random();
4593            let addr = "127.0.0.1:8008".parse().unwrap();
4594            peers.add_and_connect_kind(peer_id, PeerKind::Basic, PeerAddr::from_tcp(addr), None);
4595            if trusted {
4596                peers.add_trusted_peer_id(peer_id);
4597            }
4598            assert_eq!(peers.has_inbound_capacity(peer_id), trusted);
4599            assert_eq!(peers.peers[&peer_id].state, PeerConnectionState::PendingOut);
4600            assert_eq!(peers.connection_info.num_pending_out, 1);
4601        }
4602    }
4603
4604    #[tokio::test]
4605    async fn test_incoming_without_inbound_slots_admits_up_to_trusted_count() {
4606        let mut peers = PeersManager::new(PeersConfig::test().with_max_inbound(0));
4607        // The cap is `max(trusted_peer_ids.len(), max_inbound)` and also counts trusted ids
4608        // without a peer entry.
4609        peers.add_trusted_peer(
4610            PeerId::random(),
4611            PeerAddr::from_tcp("127.0.0.1:8008".parse().unwrap()),
4612        );
4613        peers.add_trusted_peer_id(PeerId::random());
4614
4615        for i in 1..=2 {
4616            assert!(peers.on_incoming_pending_session(Ipv4Addr::new(127, 0, 2, i).into()).is_ok());
4617        }
4618        assert_eq!(peers.connection_info.num_pending_in, 2);
4619        assert!(matches!(
4620            peers.on_incoming_pending_session(Ipv4Addr::new(127, 0, 2, 3).into()),
4621            Err(InboundConnectionError::ExceedsCapacity)
4622        ));
4623    }
4624
4625    #[tokio::test]
4626    async fn test_unauthenticated_outbound_errors_do_not_ban_identity() {
4627        for error in [
4628            PendingSessionHandshakeError::Timeout,
4629            PendingSessionHandshakeError::Eth(EthStreamError::P2PStreamError(
4630                P2PStreamError::HandshakeError(P2PHandshakeError::Timeout),
4631            )),
4632            PendingSessionHandshakeError::Eth(EthStreamError::P2PStreamError(
4633                P2PStreamError::HandshakeError(P2PHandshakeError::NoResponse),
4634            )),
4635            PendingSessionHandshakeError::Ecies(ECIESErrorImpl::InvalidAckData.into()),
4636            PendingSessionHandshakeError::Ecies(ECIESErrorImpl::TagCheckDecryptFailed.into()),
4637            PendingSessionHandshakeError::Eth(EthStreamError::P2PStreamError(P2PStreamError::Io(
4638                io::Error::other("invalid frame MAC"),
4639            ))),
4640        ] {
4641            let mut peers = PeersManager::new(PeersConfig::test());
4642            let peer_id = PeerId::random();
4643            let addr = "8.8.8.8:30303".parse::<SocketAddr>().unwrap();
4644            peers.add_and_connect_kind(peer_id, PeerKind::Basic, PeerAddr::from_tcp(addr), None);
4645            peers.queued_actions.clear();
4646            let reputation = peers.peers[&peer_id].reputation;
4647            for _ in 0..=peers.max_backoff_count + 1 {
4648                peers.add_and_connect_kind(
4649                    peer_id,
4650                    PeerKind::Basic,
4651                    PeerAddr::from_tcp(addr),
4652                    None,
4653                );
4654                peers.queued_actions.clear();
4655                peers.on_outgoing_pending_session_dropped(&addr, &peer_id, &error);
4656                assert_eq!(peers.peers[&peer_id].reputation, reputation);
4657            }
4658            let peer = &peers.peers[&peer_id];
4659            assert_eq!(peer.state, PeerConnectionState::Idle);
4660            assert_eq!(peer.reputation, reputation);
4661            assert_eq!(peer.severe_backoff_counter, 0);
4662            assert!(peer.backed_off);
4663            assert!(!peers.ban_list.is_banned_peer(&peer_id));
4664            assert!(peers.queued_actions.is_empty());
4665            assert_eq!(peers.connection_info.num_pending_out, 0);
4666
4667            // Inbound errors remain attributable to the actual remote IP.
4668            if matches!(&error, PendingSessionHandshakeError::Ecies(_)) {
4669                peers.connection_info.inc_pending_in();
4670                peers.on_incoming_pending_session_dropped(addr, &error);
4671                assert!(peers.ban_list.is_banned_ip(&addr.ip()));
4672            }
4673        }
4674    }
4675
4676    #[tokio::test]
4677    async fn test_unattributable_backoff_respects_maximum() {
4678        let mut config = PeersConfig::test();
4679        config.backoff_durations.low = Duration::from_secs(60);
4680        config.backoff_durations.max = Duration::from_secs(1);
4681        let mut peers = PeersManager::new(config);
4682        let peer_id = PeerId::random();
4683        let addr = "8.8.8.8:30303".parse::<SocketAddr>().unwrap();
4684        peers.add_and_connect_kind(peer_id, PeerKind::Basic, PeerAddr::from_tcp(addr), None);
4685        peers.peers.get_mut(&peer_id).unwrap().severe_backoff_counter = 3;
4686        let before = std::time::Instant::now();
4687        peers.on_outgoing_pending_session_dropped(
4688            &addr,
4689            &peer_id,
4690            &PendingSessionHandshakeError::Timeout,
4691        );
4692        let after = std::time::Instant::now();
4693        let until = peers.backed_off_peers[&peer_id];
4694        assert!(until >= before + Duration::from_secs(1));
4695        assert!(until <= after + Duration::from_secs(1));
4696        assert_eq!(peers.peers[&peer_id].severe_backoff_counter, 3);
4697    }
4698
4699    #[tokio::test]
4700    async fn test_unauthenticated_dial_failures_escalate_backoff() {
4701        let mut config = PeersConfig::test();
4702        config.backoff_durations.low = Duration::from_secs(10);
4703        config.backoff_durations.max = Duration::from_secs(60 * 60);
4704        let addr = "8.8.8.8:30303".parse::<SocketAddr>().unwrap();
4705        let assert_backoff_after_failure = |peers: &mut PeersManager, peer_id: PeerId, secs| {
4706            peers.peers.get_mut(&peer_id).unwrap().state = PeerConnectionState::PendingOut;
4707            peers.connection_info.inc_pending_out();
4708            let remote_addr = peers.peers[&peer_id].addr.tcp();
4709            let before = std::time::Instant::now();
4710            peers.on_outgoing_pending_session_dropped(
4711                &remote_addr,
4712                &peer_id,
4713                &PendingSessionHandshakeError::Timeout,
4714            );
4715            let after = std::time::Instant::now();
4716            let until = peers.backed_off_peers[&peer_id];
4717            let backoff = Duration::from_secs(secs);
4718            assert!(until >= before + backoff && until <= after + backoff);
4719        };
4720
4721        let mut peers = PeersManager::new(config.clone());
4722        let peer_id = PeerId::random();
4723        peers.add_peer_kind(peer_id, Some(PeerKind::Basic), PeerAddr::from_tcp(addr), None);
4724        assert_backoff_after_failure(&mut peers, peer_id, 10);
4725        assert_backoff_after_failure(&mut peers, peer_id, 20);
4726        assert_backoff_after_failure(&mut peers, peer_id, 30);
4727        let peer = &peers.peers[&peer_id];
4728        assert_eq!(peer.reputation, DEFAULT_REPUTATION);
4729        assert_eq!(peer.severe_backoff_counter, 0);
4730
4731        // An established session resets the escalation.
4732        peers.peers.get_mut(&peer_id).unwrap().state = PeerConnectionState::PendingOut;
4733        peers.connection_info.inc_pending_out();
4734        peers.on_active_outgoing_established(peer_id);
4735        peers.on_active_session_gracefully_closed(peer_id);
4736        assert_backoff_after_failure(&mut peers, peer_id, 10);
4737
4738        // A severe failure replaces the escalated backoff and clears the counter, so a later reset
4739        // can't shorten it.
4740        peers.peers.get_mut(&peer_id).unwrap().state = PeerConnectionState::PendingOut;
4741        peers.connection_info.inc_pending_out();
4742        peers.on_outgoing_connection_failure(
4743            &addr,
4744            &peer_id,
4745            &io::Error::new(io::ErrorKind::ConnectionRefused, ""),
4746        );
4747        assert_eq!(peers.peers[&peer_id].unauthenticated_dial_failures, 0);
4748        let until = peers.backed_off_peers[&peer_id];
4749        let other_addr = PeerAddr::from_tcp("1.1.1.1:30303".parse().unwrap());
4750        peers.add_peer_kind(peer_id, None, other_addr, None);
4751        assert_eq!(peers.backed_off_peers[&peer_id], until);
4752        peers.add_peer_kind(peer_id, None, PeerAddr::from_tcp(addr), None);
4753        assert_backoff_after_failure(&mut peers, peer_id, 10);
4754
4755        // A new address resets the escalation and shortens the pending backoff.
4756        assert_backoff_after_failure(&mut peers, peer_id, 20);
4757        let new_addr = PeerAddr::from_tcp("8.8.4.4:30303".parse().unwrap());
4758        peers.add_peer_kind(peer_id, None, new_addr, None);
4759        assert!(
4760            peers.backed_off_peers[&peer_id] <= std::time::Instant::now() + Duration::from_secs(10)
4761        );
4762        assert_eq!(peers.peers[&peer_id].unauthenticated_dial_failures, 0);
4763
4764        // A late failure from the previous address isn't counted for the new one.
4765        peers.peers.get_mut(&peer_id).unwrap().state = PeerConnectionState::PendingOut;
4766        peers.connection_info.inc_pending_out();
4767        peers.on_outgoing_pending_session_dropped(
4768            &addr,
4769            &peer_id,
4770            &PendingSessionHandshakeError::Timeout,
4771        );
4772        assert_eq!(peers.peers[&peer_id].unauthenticated_dial_failures, 0);
4773
4774        // So does becoming trusted.
4775        assert_backoff_after_failure(&mut peers, peer_id, 10);
4776        assert_backoff_after_failure(&mut peers, peer_id, 20);
4777        peers.add_trusted_peer_id(peer_id);
4778        assert!(
4779            peers.backed_off_peers[&peer_id] <= std::time::Instant::now() + Duration::from_secs(10)
4780        );
4781
4782        for (kind, trusted_id) in
4783            [(PeerKind::Static, false), (PeerKind::Trusted, false), (PeerKind::Basic, true)]
4784        {
4785            let mut peers = PeersManager::new(config.clone());
4786            let peer_id = PeerId::random();
4787            peers.add_peer_kind(peer_id, Some(kind), PeerAddr::from_tcp(addr), None);
4788            if trusted_id {
4789                // DNS-resolved trusted IDs keep their discovered kind.
4790                peers.trusted_peer_ids.insert(peer_id);
4791            }
4792            assert_backoff_after_failure(&mut peers, peer_id, 10);
4793            assert_backoff_after_failure(&mut peers, peer_id, 10);
4794        }
4795    }
4796
4797    #[tokio::test]
4798    async fn test_dns_trusted_ids_bypass_outbound_capacity() {
4799        for register_first in [false, true] {
4800            let mut peers = PeersManager::new(PeersConfig::test().with_max_outbound(0));
4801            let peer_id = PeerId::random();
4802            let addr = "127.0.0.1:30303".parse::<SocketAddr>().unwrap();
4803            let trusted =
4804                TrustedPeer::new(Host::Domain("trusted.invalid".into()), addr.port(), peer_id);
4805            if register_first {
4806                peers.add_trusted_peer_node(trusted.clone());
4807            }
4808            peers.add_peer(peer_id, PeerAddr::from_tcp(addr), None);
4809            if !register_first {
4810                peers.add_trusted_peer_node(trusted);
4811            }
4812            assert_eq!(peers.peers[&peer_id].kind, PeerKind::Trusted);
4813            peers.queued_actions.clear();
4814            peers.fill_outbound_slots();
4815            assert!(
4816                matches!(peers.queued_actions.pop_front(), Some(PeerAction::Connect { peer_id: id, remote_addr }) if id == peer_id && remote_addr == addr)
4817            );
4818            assert!(peers.queued_actions.is_empty());
4819        }
4820    }
4821
4822    #[tokio::test]
4823    async fn test_trusted_bypass_respects_shared_dial_limit() {
4824        let mut peers = PeersManager::new(
4825            PeersConfig::test().with_max_outbound(1).with_max_concurrent_dials(1),
4826        );
4827        let addr = "127.0.0.1:30303".parse().unwrap();
4828        let basic = PeerId::random();
4829        peers.add_peer(basic, PeerAddr::from_tcp(addr), None);
4830        peers.fill_outbound_slots();
4831        assert_eq!(peers.connection_info.num_pending_out, 1);
4832        for _ in 0..2 {
4833            peers.add_trusted_peer(PeerId::random(), PeerAddr::from_tcp(addr));
4834        }
4835        peers.queued_actions.clear();
4836        peers.fill_outbound_slots();
4837        assert!(peers.queued_actions.is_empty());
4838        peers.on_active_outgoing_established(basic);
4839        peers.fill_outbound_slots();
4840        assert!(
4841            matches!(peers.queued_actions.pop_front(), Some(PeerAction::Connect { peer_id, .. }) if peers.peers[&peer_id].is_trusted())
4842        );
4843        assert!(peers.queued_actions.is_empty());
4844        assert_eq!(peers.connection_info.num_pending_out, 1);
4845        assert_eq!(peers.connection_info.num_outbound, 1);
4846    }
4847
4848    #[tokio::test]
4849    async fn test_ip_filter_preserves_trust_on_rediscovery() {
4850        for persisted in [false, true] {
4851            let blocked = NodeRecord::new("10.0.0.1:30303".parse().unwrap(), PeerId::random());
4852            let allowed = NodeRecord::new("192.168.1.1:30303".parse().unwrap(), blocked.id);
4853            let mut config = PeersConfig::test()
4854                .with_ip_filter(IpFilter::from_cidr_string("192.168.0.0/16").unwrap());
4855            if persisted {
4856                config.persisted_peers.push(PersistedPeerInfo {
4857                    kind: PeerKind::Trusted,
4858                    ..PersistedPeerInfo::from_node_record(blocked)
4859                });
4860            } else {
4861                config.trusted_nodes.push(blocked.into());
4862            }
4863            let mut peers = PeersManager::new(config);
4864            assert!(peers.peers.is_empty());
4865            assert!(peers.trusted_peer_ids.contains(&blocked.id));
4866            peers.add_peer(blocked.id, PeerAddr::from_tcp(blocked.tcp_addr()), None);
4867            assert!(peers.peers.is_empty());
4868
4869            peers.add_peer(allowed.id, PeerAddr::from_tcp(allowed.tcp_addr()), None);
4870            assert_eq!(peers.peers[&allowed.id].kind, PeerKind::Trusted);
4871            peers.apply_reputation_change(&allowed.id, ReputationChangeKind::Timeout);
4872            assert_eq!(peers.peers[&allowed.id].reputation, DEFAULT_REPUTATION);
4873            peers.remove_peer(allowed.id);
4874            assert!(peers.peers.contains_key(&allowed.id));
4875            assert_eq!(peers.persistable_peers().next().unwrap().kind, PeerKind::Trusted);
4876
4877            peers.remove_peer_from_trusted_set(allowed.id);
4878            peers.remove_peer(allowed.id);
4879            peers.add_peer(allowed.id, PeerAddr::from_tcp(allowed.tcp_addr()), None);
4880            assert_eq!(peers.peers[&allowed.id].kind, PeerKind::Basic);
4881        }
4882    }
4883
4884    #[tokio::test]
4885    async fn test_ip_filter_preserves_trust_with_startup_fallback() {
4886        for persisted_trust in [false, true] {
4887            for persisted_fallback in [false, true] {
4888                let blocked = NodeRecord::new("10.0.0.1:30303".parse().unwrap(), PeerId::random());
4889                let allowed = NodeRecord::new("192.168.1.1:30303".parse().unwrap(), blocked.id);
4890                let mut config = PeersConfig::test()
4891                    .with_ip_filter(IpFilter::from_cidr_string("192.168.0.0/16").unwrap());
4892                if persisted_trust {
4893                    config.persisted_peers.push(PersistedPeerInfo {
4894                        kind: PeerKind::Trusted,
4895                        ..PersistedPeerInfo::from_node_record(blocked)
4896                    });
4897                } else {
4898                    config.trusted_nodes.push(blocked.into());
4899                }
4900                if persisted_fallback {
4901                    config.persisted_peers.push(PersistedPeerInfo::from_node_record(allowed));
4902                } else {
4903                    config.basic_nodes.insert(allowed);
4904                }
4905                let peers = PeersManager::new(config);
4906                assert_eq!(peers.peers.len(), 1);
4907                assert!(peers.trusted_peer_ids.contains(&allowed.id));
4908                assert_eq!(peers.peers[&allowed.id].kind, PeerKind::Trusted);
4909                assert_eq!(peers.peers[&allowed.id].addr.tcp(), allowed.tcp_addr());
4910            }
4911        }
4912    }
4913
4914    #[tokio::test]
4915    async fn test_ip_filter_startup_ipv6_and_allowed_metadata() {
4916        for kind in [PeerKind::Basic, PeerKind::Static, PeerKind::Trusted] {
4917            let allowed = NodeRecord::new("[2001:db8::1]:30303".parse().unwrap(), PeerId::random());
4918            let blocked = NodeRecord::new("[2001:db9::1]:30303".parse().unwrap(), PeerId::random());
4919            let fork_id = ForkId { hash: ForkHash([1, 2, 3, 4]), next: 0 };
4920            let mut config = PeersConfig::test()
4921                .with_ip_filter(IpFilter::from_cidr_string("2001:db8::/32").unwrap());
4922            config.persisted_peers = [allowed, blocked]
4923                .into_iter()
4924                .map(|record| PersistedPeerInfo {
4925                    record,
4926                    kind,
4927                    fork_id: Some(fork_id),
4928                    reputation: 10,
4929                })
4930                .collect();
4931            let mut peers = PeersManager::new(config);
4932            assert_eq!(peers.peers.len(), 1);
4933            assert_eq!(peers.trusted_peer_ids.contains(&blocked.id), kind.is_trusted());
4934            assert_eq!(
4935                peers.persistable_peers().collect::<Vec<_>>(),
4936                [PersistedPeerInfo {
4937                    record: allowed,
4938                    kind,
4939                    fork_id: Some(fork_id),
4940                    reputation: 10,
4941                }]
4942            );
4943            peers.fill_outbound_slots();
4944            assert!(
4945                matches!(peers.queued_actions.pop_front(), Some(PeerAction::Connect { peer_id, remote_addr })
4946                if peer_id == allowed.id && remote_addr == allowed.tcp_addr())
4947            );
4948            assert!(peers.queued_actions.is_empty());
4949        }
4950    }
4951
4952    #[tokio::test]
4953    async fn test_temporary_peer_removed_after_dropped_session() {
4954        let mut peers = PeersManager::new(PeersConfig::test());
4955        let inbound = PeerId::random();
4956        let socket_addr = "5.6.7.8:40404".parse().unwrap();
4957        assert!(peers.on_incoming_pending_session(IpAddr::V4(Ipv4Addr::new(5, 6, 7, 8))).is_ok());
4958        peers.on_incoming_session_established(inbound, socket_addr);
4959        assert!(peers.peers[&inbound].remove_after_disconnect);
4960        // its source port is not a listening endpoint, so it is not saved
4961        let persisted =
4962            |peers: &PeersManager, id| peers.persistable_peers().any(|peer| peer.record.id == id);
4963        assert!(!persisted(&peers, inbound));
4964
4965        peers.on_active_session_dropped(
4966            &socket_addr,
4967            &inbound,
4968            &EthStreamError::P2PStreamError(P2PStreamError::Disconnected(
4969                DisconnectReason::TooManyPeers,
4970            )),
4971        );
4972        assert!(!peers.peers.contains_key(&inbound));
4973
4974        // unless it is trusted by id, so the trust survives a restart
4975        let trusted = PeerId::random();
4976        assert!(peers.on_incoming_pending_session(IpAddr::V4(Ipv4Addr::new(5, 6, 7, 9))).is_ok());
4977        peers.on_incoming_session_established(trusted, "5.6.7.9:40404".parse().unwrap());
4978        peers.add_trusted_peer_id(trusted);
4979        assert!(persisted(&peers, trusted));
4980    }
4981
4982    #[tokio::test]
4983    async fn test_peer_added_as_static_is_kept() {
4984        let mut peers = PeersManager::new(PeersConfig::test());
4985        let addr = PeerAddr::from_tcp("5.6.7.8:30303".parse().unwrap());
4986
4987        // an inbound peer, once the operator supplies its listening endpoint
4988        let inbound = PeerId::random();
4989        assert!(peers.on_incoming_pending_session(IpAddr::V4(Ipv4Addr::new(5, 6, 7, 8))).is_ok());
4990        peers.on_incoming_session_established(inbound, "5.6.7.8:40404".parse().unwrap());
4991        peers.add_and_connect_kind(inbound, PeerKind::Static, addr, None);
4992        assert!(peers.persistable_peers().any(|peer| peer.record.id == inbound));
4993
4994        // a peer removed while it was dialed, then added again before the dial fails
4995        let dialed = PeerId::random();
4996        peers.add_and_connect_kind(dialed, PeerKind::Basic, addr, None);
4997        peers.remove_peer(dialed);
4998        peers.add_and_connect_kind(dialed, PeerKind::Static, addr, None);
4999        peers.on_outgoing_connection_failure(
5000            &addr.tcp(),
5001            &dialed,
5002            &io::Error::new(io::ErrorKind::ConnectionRefused, ""),
5003        );
5004        assert!(peers.peers[&dialed].is_static());
5005
5006        // but not one already being disconnected, whose removal was reported
5007        peers.remove_peer(inbound);
5008        peers.add_and_connect_kind(inbound, PeerKind::Static, addr, None);
5009        peers.on_active_session_gracefully_closed(inbound);
5010        assert!(!peers.peers.contains_key(&inbound));
5011    }
5012
5013    #[tokio::test]
5014    async fn test_skipped_persisted_peers_reserve_no_capacity() {
5015        let rows = 10_000;
5016        let mut config = PeersConfig::test();
5017        config.enforce_enr_fork_id = true;
5018        // records without a fork id are skipped when the fork id is enforced
5019        config.persisted_peers = (0..rows)
5020            .map(|_| {
5021                PersistedPeerInfo::from_node_record(NodeRecord::new(
5022                    "1.2.3.4:30303".parse().unwrap(),
5023                    PeerId::random(),
5024                ))
5025            })
5026            .collect();
5027
5028        let peers = PeersManager::new(config);
5029        assert!(peers.peers.is_empty());
5030        assert!(peers.peers.capacity() < rows);
5031    }
5032
5033    #[tokio::test]
5034    async fn test_peer_removed_while_dialed() {
5035        let mut peers = PeersManager::new(PeersConfig::test());
5036        let addr = "5.6.7.8:30303".parse::<SocketAddr>().unwrap();
5037
5038        let closed = PeerId::random();
5039        peers.add_and_connect_kind(closed, PeerKind::Basic, PeerAddr::from_tcp(addr), None);
5040        peers.remove_peer(closed);
5041        peers.queued_actions.clear();
5042        peers.on_outgoing_pending_session_gracefully_closed(&closed);
5043        assert!(matches!(
5044            peers.queued_actions.pop_front(),
5045            Some(PeerAction::PeerRemoved(peer_id)) if peer_id == closed
5046        ));
5047
5048        let timed_out = PeerId::random();
5049        peers.add_and_connect_kind(timed_out, PeerKind::Basic, PeerAddr::from_tcp(addr), None);
5050        peers.remove_peer(timed_out);
5051        peers.on_outgoing_pending_session_dropped(
5052            &addr,
5053            &timed_out,
5054            &PendingSessionHandshakeError::Timeout,
5055        );
5056
5057        let established = PeerId::random();
5058        peers.add_and_connect_kind(established, PeerKind::Basic, PeerAddr::from_tcp(addr), None);
5059        peers.remove_peer(established);
5060        peers.queued_actions.clear();
5061        peers.on_active_outgoing_established(established);
5062        assert_eq!(peers.peers[&established].state, PeerConnectionState::DisconnectingOut);
5063        assert!(matches!(
5064            peers.queued_actions.pop_front(),
5065            Some(PeerAction::Disconnect {
5066                peer_id,
5067                reason: Some(DisconnectReason::DisconnectRequested),
5068            }) if peer_id == established
5069        ));
5070        peers.on_active_session_gracefully_closed(established);
5071
5072        assert!(peers.peers.is_empty());
5073        assert_eq!(peers.num_pending_outbound_connections(), 0);
5074        assert_eq!(peers.num_outbound_connections(), 0);
5075    }
5076}