Skip to main content

reth_network_types/peers/
mod.rs

1pub mod addr;
2pub mod config;
3pub mod kind;
4pub mod reputation;
5pub mod state;
6
7pub use config::{ConnectionsConfig, PeersConfig};
8pub use reputation::{Reputation, ReputationChange, ReputationChangeKind, ReputationChangeWeights};
9
10use alloy_eip2124::ForkId;
11use reth_network_peers::{NodeRecord, PeerId};
12use std::time::{Duration, Instant};
13use tracing::trace;
14
15use crate::{
16    is_banned_reputation, PeerAddr, PeerConnectionState, PeerKind, ReputationChangeOutcome,
17    DEFAULT_REPUTATION,
18};
19
20/// Tracks info about a single peer.
21#[derive(Debug, Clone)]
22pub struct Peer {
23    /// Where to reach the peer.
24    pub addr: PeerAddr,
25    /// Reputation of the peer.
26    pub reputation: i32,
27    /// The state of the connection, if any.
28    pub state: PeerConnectionState,
29    /// When the current session was established.
30    pub connected_at: Option<Instant>,
31    /// The [`ForkId`] that the peer announced via discovery.
32    pub fork_id: Option<Box<ForkId>>,
33    /// Whether the entry should be removed after an existing session was terminated.
34    pub remove_after_disconnect: bool,
35    /// The kind of peer
36    pub kind: PeerKind,
37    /// Whether the peer is currently backed off.
38    pub backed_off: bool,
39    /// Counts number of times the peer was backed off due to a severe
40    /// [`BackoffKind`](crate::BackoffKind).
41    pub severe_backoff_counter: u8,
42    /// Counts outbound dial failures before authentication since the last established session.
43    ///
44    /// Only used to space out retries; it never affects reputation or bans. Reset once a session
45    /// is established in either direction.
46    pub unauthenticated_dial_failures: u8,
47}
48
49// === impl Peer ===
50
51impl Peer {
52    /// Returns a new peer for given [`PeerAddr`].
53    pub fn new(addr: PeerAddr) -> Self {
54        Self::with_state(addr, Default::default())
55    }
56
57    /// Returns a new trusted peer for given [`PeerAddr`].
58    pub fn trusted(addr: PeerAddr) -> Self {
59        Self { kind: PeerKind::Trusted, ..Self::new(addr) }
60    }
61
62    /// Returns the reputation of the peer
63    pub const fn reputation(&self) -> i32 {
64        self.reputation
65    }
66
67    /// Marks this peer as connected.
68    pub fn mark_connected(&mut self) {
69        self.connected_at = Some(Instant::now());
70        self.unauthenticated_dial_failures = 0;
71    }
72
73    /// Clears the current connection timestamp.
74    pub const fn mark_disconnected(&mut self) {
75        self.connected_at = None;
76    }
77
78    /// Returns `true` if the current connection has been active for at least `min_uptime`.
79    pub fn connected_for_at_least(&self, now: Instant, min_uptime: Duration) -> bool {
80        self.connected_at
81            .is_some_and(|connected_at| now.saturating_duration_since(connected_at) >= min_uptime)
82    }
83
84    /// Returns a new peer for given [`PeerAddr`] and [`PeerConnectionState`].
85    pub fn with_state(addr: PeerAddr, state: PeerConnectionState) -> Self {
86        Self {
87            addr,
88            state,
89            connected_at: None,
90            reputation: DEFAULT_REPUTATION,
91            fork_id: None,
92            remove_after_disconnect: false,
93            kind: Default::default(),
94            backed_off: false,
95            severe_backoff_counter: 0,
96            unauthenticated_dial_failures: 0,
97        }
98    }
99
100    /// Returns a new peer for given [`PeerAddr`] and [`PeerKind`].
101    pub fn with_kind(addr: PeerAddr, kind: PeerKind) -> Self {
102        Self { kind, ..Self::new(addr) }
103    }
104
105    /// Resets the reputation of the peer to the default value. This always returns
106    /// [`ReputationChangeOutcome::None`].
107    pub const fn reset_reputation(&mut self) -> ReputationChangeOutcome {
108        self.reputation = DEFAULT_REPUTATION;
109
110        ReputationChangeOutcome::None
111    }
112
113    /// Applies a reputation change to the peer and returns what action should be taken.
114    pub fn apply_reputation(
115        &mut self,
116        reputation: i32,
117        kind: ReputationChangeKind,
118    ) -> ReputationChangeOutcome {
119        let previous = self.reputation;
120        // we add reputation since negative reputation change decrease total reputation
121        self.reputation = previous.saturating_add(reputation);
122
123        trace!(target: "net::peers", reputation=%self.reputation, banned=%self.is_banned(), ?kind, "applied reputation change");
124
125        if self.state.is_connected() && self.is_banned() {
126            self.state.disconnect();
127            return ReputationChangeOutcome::DisconnectAndBan
128        }
129
130        if self.is_banned() && !is_banned_reputation(previous) {
131            return ReputationChangeOutcome::Ban
132        }
133
134        if !self.is_banned() && is_banned_reputation(previous) {
135            return ReputationChangeOutcome::Unban
136        }
137
138        ReputationChangeOutcome::None
139    }
140
141    /// Returns true if the peer's reputation is below the banned threshold.
142    #[inline]
143    pub const fn is_banned(&self) -> bool {
144        is_banned_reputation(self.reputation)
145    }
146
147    /// Returns `true` if peer is banned.
148    #[inline]
149    pub const fn is_backed_off(&self) -> bool {
150        self.backed_off
151    }
152
153    /// Unbans the peer by resetting its reputation
154    #[inline]
155    pub const fn unban(&mut self) {
156        self.reputation = DEFAULT_REPUTATION
157    }
158
159    /// Returns whether this peer is trusted
160    #[inline]
161    pub const fn is_trusted(&self) -> bool {
162        self.kind.is_trusted()
163    }
164
165    /// Returns whether this peer is static
166    #[inline]
167    pub const fn is_static(&self) -> bool {
168        self.kind.is_static()
169    }
170
171    /// Returns whether this peer is only tracked until its current session ends.
172    ///
173    /// Trusted peers are never temporary, even when marked for removal after disconnecting.
174    #[inline]
175    pub const fn is_temporary(&self) -> bool {
176        self.remove_after_disconnect && !self.is_trusted()
177    }
178}
179
180/// Peer info persisted to disk.
181///
182/// Contains richer metadata than a plain [`NodeRecord`], preserving the peer's kind, fork ID,
183/// and reputation across restarts.
184#[derive(Debug, Clone, PartialEq, Eq)]
185#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
186pub struct PersistedPeerInfo {
187    /// The node record (id, address, ports).
188    pub record: NodeRecord,
189    /// The kind of peer.
190    pub kind: PeerKind,
191    /// The [`ForkId`] that the peer announced via discovery.
192    #[cfg_attr(feature = "serde", serde(default, skip_serializing_if = "Option::is_none"))]
193    pub fork_id: Option<ForkId>,
194    /// The peer's reputation at the time of persisting.
195    pub reputation: i32,
196}
197
198impl PersistedPeerInfo {
199    /// Returns the peer id.
200    pub const fn peer_id(&self) -> PeerId {
201        self.record.id
202    }
203
204    /// Converts a legacy [`NodeRecord`] into a [`PersistedPeerInfo`] with default metadata.
205    pub const fn from_node_record(record: NodeRecord) -> Self {
206        Self { record, kind: PeerKind::Basic, fork_id: None, reputation: DEFAULT_REPUTATION }
207    }
208}