Skip to main content

reth_network_types/peers/
config.rs

1//! Configuration for peering.
2
3use std::{collections::HashSet, time::Duration};
4
5use reth_net_banlist::{BanList, IpFilter};
6use reth_network_peers::{NodeRecord, TrustedPeer};
7
8use crate::{peers::PersistedPeerInfo, BackoffKind, ReputationChangeWeights};
9
10#[cfg(feature = "serde")]
11use jiff::fmt::serde::unsigned_duration::friendly::compact;
12
13/// Maximum number of available slots for outbound sessions.
14pub const DEFAULT_MAX_COUNT_PEERS_OUTBOUND: u32 = 100;
15
16/// Maximum number of available slots for inbound sessions.
17pub const DEFAULT_MAX_COUNT_PEERS_INBOUND: u32 = 30;
18
19/// Maximum number of available slots for concurrent outgoing dials.
20///
21/// This restricts how many outbound dials can be performed concurrently.
22pub const DEFAULT_MAX_COUNT_CONCURRENT_OUTBOUND_DIALS: usize = 30;
23
24/// A temporary timeout for ips on incoming connection attempts.
25pub const INBOUND_IP_THROTTLE_DURATION: Duration = Duration::from_secs(30);
26
27/// The durations to use when a backoff should be applied to a peer.
28///
29/// See also [`BackoffKind`].
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
32pub struct PeerBackoffDurations {
33    /// Applies to connection problems where there is a chance that they will be resolved after the
34    /// short duration.
35    #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
36    pub low: Duration,
37    /// Applies to more severe connection problems where there is a lower chance that they will be
38    /// resolved.
39    #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
40    pub medium: Duration,
41    /// Intended for spammers, or bad peers in general.
42    #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
43    pub high: Duration,
44    /// Maximum total backoff duration.
45    #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
46    pub max: Duration,
47}
48
49impl PeerBackoffDurations {
50    /// Returns the corresponding [`Duration`]
51    pub const fn backoff(&self, kind: BackoffKind) -> Duration {
52        match kind {
53            BackoffKind::Low => self.low,
54            BackoffKind::Medium => self.medium,
55            BackoffKind::High => self.high,
56        }
57    }
58
59    /// Returns the timestamp until which we should backoff.
60    ///
61    /// The Backoff duration is capped by the configured maximum backoff duration.
62    pub fn backoff_until(&self, kind: BackoffKind, backoff_counter: u8) -> std::time::Instant {
63        let backoff_time = self.backoff(kind);
64        let backoff_time = backoff_time + backoff_time * backoff_counter as u32;
65        let now = std::time::Instant::now();
66        now + backoff_time.min(self.max)
67    }
68
69    /// Returns durations for testing.
70    #[cfg(any(test, feature = "test-utils"))]
71    pub const fn test() -> Self {
72        Self {
73            low: Duration::from_millis(200),
74            medium: Duration::from_millis(200),
75            high: Duration::from_millis(200),
76            max: Duration::from_millis(200),
77        }
78    }
79}
80
81impl Default for PeerBackoffDurations {
82    fn default() -> Self {
83        Self {
84            low: Duration::from_secs(30),
85            // 3min
86            medium: Duration::from_secs(60 * 3),
87            // 15min
88            high: Duration::from_secs(60 * 15),
89            // 1h
90            max: Duration::from_secs(60 * 60),
91        }
92    }
93}
94
95/// Tracks stats about connected nodes
96#[derive(Debug, Clone, PartialEq, Eq)]
97#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(default))]
98pub struct ConnectionsConfig {
99    /// Maximum allowed outbound connections. Trusted peers are dialed regardless.
100    pub max_outbound: usize,
101    /// Maximum allowed inbound connections.
102    pub max_inbound: usize,
103    /// Maximum allowed concurrent outbound dials.
104    #[cfg_attr(feature = "serde", serde(default))]
105    pub max_concurrent_outbound_dials: usize,
106}
107
108impl Default for ConnectionsConfig {
109    fn default() -> Self {
110        Self {
111            max_outbound: DEFAULT_MAX_COUNT_PEERS_OUTBOUND as usize,
112            max_inbound: DEFAULT_MAX_COUNT_PEERS_INBOUND as usize,
113            max_concurrent_outbound_dials: DEFAULT_MAX_COUNT_CONCURRENT_OUTBOUND_DIALS,
114        }
115    }
116}
117
118/// Default mean interval for the jittered peer rotation timer.
119///
120/// The actual fire interval is uniformly random in `[mean * 3/5, mean * 7/5]`. With the default
121/// of 5 minutes that gives a `[3 min, 7 min]` range, matching geth's peer dropper.
122pub const DEFAULT_PEER_ROTATION_INTERVAL: Duration = Duration::from_mins(5);
123
124/// Minimum connection uptime before a peer is eligible for rotation eviction.
125pub const PEER_ROTATION_MIN_UPTIME: Duration = Duration::from_mins(10);
126
127/// Config type for initiating a `PeersManager` instance.
128#[derive(Debug, Clone, PartialEq, Eq)]
129#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
130#[cfg_attr(feature = "serde", serde(default))]
131pub struct PeersConfig {
132    /// How often to recheck free slots for outbound connections.
133    #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
134    pub refill_slots_interval: Duration,
135    /// Trusted nodes to connect to or accept from
136    pub trusted_nodes: Vec<TrustedPeer>,
137    /// Connect to or accept from trusted nodes only?
138    #[cfg_attr(feature = "serde", serde(alias = "connect_trusted_nodes_only"))]
139    pub trusted_nodes_only: bool,
140    /// Interval to update trusted nodes DNS resolution
141    #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
142    pub trusted_nodes_resolution_interval: Duration,
143    /// Maximum number of backoff attempts before we give up on a peer and dropping.
144    ///
145    /// The max time spent of a peer before it's removed from the set is determined by the
146    /// configured backoff duration and the max backoff count.
147    ///
148    /// With a backoff counter of 5 and a backoff duration of 1h, the minimum time spent of the
149    /// peer in the table is the sum of all backoffs (1h + 2h + 3h + 4h + 5h = 15h).
150    ///
151    /// Note: this does not apply to trusted peers.
152    pub max_backoff_count: u8,
153    /// Basic nodes to connect to.
154    #[cfg_attr(feature = "serde", serde(skip))]
155    pub basic_nodes: HashSet<NodeRecord>,
156    /// Peers restored from a previous run, containing richer metadata than basic nodes.
157    #[cfg_attr(feature = "serde", serde(skip))]
158    pub persisted_peers: Vec<PersistedPeerInfo>,
159    /// How long to ban bad peers.
160    #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
161    pub ban_duration: Duration,
162    /// Restrictions on `PeerIds` and Ips.
163    #[cfg_attr(feature = "serde", serde(skip))]
164    pub ban_list: BanList,
165    /// Restrictions on connections.
166    pub connection_info: ConnectionsConfig,
167    /// How to weigh reputation changes.
168    pub reputation_weights: ReputationChangeWeights,
169    /// How long to backoff peers that we are failed to connect to for non-fatal reasons.
170    ///
171    /// The backoff duration increases with number of backoff attempts.
172    pub backoff_durations: PeerBackoffDurations,
173    /// How long to temporarily ban ips on incoming connection attempts.
174    ///
175    /// This acts as an IP based rate limit.
176    #[cfg_attr(feature = "serde", serde(default, with = "compact::required"))]
177    pub incoming_ip_throttle_duration: Duration,
178    /// IP address filter for restricting network connections to specific IP ranges.
179    ///
180    /// Similar to geth's --netrestrict flag. If configured, only connections to/from
181    /// IPs within the specified CIDR ranges will be allowed.
182    #[cfg_attr(feature = "serde", serde(skip))]
183    pub ip_filter: IpFilter,
184    /// If true, discovered peers without a confirmed ENR [`ForkId`](alloy_eip2124::ForkId)
185    /// (EIP-868) will not be added to the peer set until their fork ID is verified.
186    ///
187    /// This filters out peers from other networks that pollute the discovery table.
188    pub enforce_enr_fork_id: bool,
189    /// How often to rotate a random non-protected peer (inbound or outbound) to open a slot for
190    /// new nodes. Set to `None` to disable rotation.
191    #[cfg_attr(feature = "serde", serde(default, with = "compact::optional"))]
192    pub peer_rotation_interval: Option<Duration>,
193}
194
195impl Default for PeersConfig {
196    fn default() -> Self {
197        Self {
198            refill_slots_interval: Duration::from_millis(5_000),
199            connection_info: Default::default(),
200            reputation_weights: Default::default(),
201            ban_list: Default::default(),
202            // Ban peers for 12h
203            ban_duration: Duration::from_secs(60 * 60 * 12),
204            backoff_durations: Default::default(),
205            trusted_nodes: Default::default(),
206            trusted_nodes_only: false,
207            trusted_nodes_resolution_interval: Duration::from_secs(60 * 60),
208            basic_nodes: Default::default(),
209            persisted_peers: Default::default(),
210            max_backoff_count: 5,
211            incoming_ip_throttle_duration: INBOUND_IP_THROTTLE_DURATION,
212            ip_filter: IpFilter::default(),
213            enforce_enr_fork_id: false,
214            peer_rotation_interval: Some(DEFAULT_PEER_ROTATION_INTERVAL),
215        }
216    }
217}
218
219impl PeersConfig {
220    /// A set of `peer_ids` and ip addr that we want to never connect to
221    pub fn with_ban_list(mut self, ban_list: BanList) -> Self {
222        self.ban_list = ban_list;
223        self
224    }
225
226    /// Configure how long to ban bad peers
227    pub const fn with_ban_duration(mut self, ban_duration: Duration) -> Self {
228        self.ban_duration = ban_duration;
229        self
230    }
231
232    /// Configure how long to refill outbound slots
233    pub const fn with_refill_slots_interval(mut self, interval: Duration) -> Self {
234        self.refill_slots_interval = interval;
235        self
236    }
237
238    /// Maximum allowed outbound connections.
239    pub const fn with_max_outbound(mut self, max_outbound: usize) -> Self {
240        self.connection_info.max_outbound = max_outbound;
241        self
242    }
243
244    /// Maximum allowed inbound connections with optional update.
245    pub const fn with_max_inbound_opt(mut self, max_inbound: Option<usize>) -> Self {
246        if let Some(max_inbound) = max_inbound {
247            self.connection_info.max_inbound = max_inbound;
248        }
249        self
250    }
251
252    /// Maximum allowed outbound connections with optional update.
253    pub const fn with_max_outbound_opt(mut self, max_outbound: Option<usize>) -> Self {
254        if let Some(max_outbound) = max_outbound {
255            self.connection_info.max_outbound = max_outbound;
256        }
257        self
258    }
259
260    /// Maximum allowed inbound connections.
261    pub const fn with_max_inbound(mut self, max_inbound: usize) -> Self {
262        self.connection_info.max_inbound = max_inbound;
263        self
264    }
265
266    /// Maximum allowed concurrent outbound dials.
267    pub const fn with_max_concurrent_dials(mut self, max_concurrent_outbound_dials: usize) -> Self {
268        self.connection_info.max_concurrent_outbound_dials = max_concurrent_outbound_dials;
269        self
270    }
271
272    /// Nodes to always connect to.
273    pub fn with_trusted_nodes(mut self, nodes: Vec<TrustedPeer>) -> Self {
274        self.trusted_nodes = nodes;
275        self
276    }
277
278    /// Connect only to trusted nodes.
279    pub const fn with_trusted_nodes_only(mut self, trusted_only: bool) -> Self {
280        self.trusted_nodes_only = trusted_only;
281        self
282    }
283
284    /// Nodes available at launch.
285    pub fn with_basic_nodes(mut self, nodes: HashSet<NodeRecord>) -> Self {
286        self.basic_nodes = nodes;
287        self
288    }
289
290    /// Configures the max allowed backoff count.
291    pub const fn with_max_backoff_count(mut self, max_backoff_count: u8) -> Self {
292        self.max_backoff_count = max_backoff_count;
293        self
294    }
295
296    /// Configures how to weigh reputation changes.
297    pub const fn with_reputation_weights(
298        mut self,
299        reputation_weights: ReputationChangeWeights,
300    ) -> Self {
301        self.reputation_weights = reputation_weights;
302        self
303    }
304
305    /// Configures how long to backoff peers that are we failed to connect to for non-fatal reasons
306    pub const fn with_backoff_durations(mut self, backoff_durations: PeerBackoffDurations) -> Self {
307        self.backoff_durations = backoff_durations;
308        self
309    }
310
311    /// Returns the maximum number of peers, inbound and outbound.
312    pub const fn max_peers(&self) -> usize {
313        self.connection_info.max_outbound + self.connection_info.max_inbound
314    }
315
316    /// Read persisted peers from file at launch.
317    ///
318    /// Supports both the current [`PersistedPeerInfo`] format and the legacy `Vec<NodeRecord>`
319    /// format. Legacy entries are converted to [`PersistedPeerInfo`] with default metadata.
320    ///
321    /// Ignored if `optional_file` is `None` or the file does not exist.
322    #[cfg(feature = "serde")]
323    pub fn with_basic_nodes_from_file(
324        mut self,
325        optional_file: Option<impl AsRef<std::path::Path>>,
326    ) -> Result<Self, std::io::Error> {
327        let Some(file_path) = optional_file else { return Ok(self) };
328        let raw = match std::fs::read_to_string(file_path.as_ref()) {
329            Ok(contents) => contents,
330            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(self),
331            Err(e) => return Err(e),
332        };
333
334        tracing::info!(target: "net::peers", file = %file_path.as_ref().display(), "Loading saved peers");
335
336        // Try the new format first, fall back to legacy Vec<NodeRecord>
337        let peers: Vec<PersistedPeerInfo> = serde_json::from_str(&raw)
338            .or_else(|_| {
339                let nodes: HashSet<NodeRecord> = serde_json::from_str(&raw)?;
340                Ok::<_, serde_json::Error>(
341                    nodes.into_iter().map(PersistedPeerInfo::from_node_record).collect(),
342                )
343            })
344            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
345
346        tracing::info!(target: "net::peers", count = peers.len(), "Loaded persisted peers");
347        self.persisted_peers = peers;
348        Ok(self)
349    }
350
351    /// Configure the IP filter for restricting network connections to specific IP ranges.
352    pub fn with_ip_filter(mut self, ip_filter: IpFilter) -> Self {
353        self.ip_filter = ip_filter;
354        self
355    }
356
357    /// If set, discovered peers without a confirmed ENR [`ForkId`](alloy_eip2124::ForkId) will not
358    /// be added to the peer set until their fork ID is verified via EIP-868.
359    pub const fn with_enforce_enr_fork_id(mut self, enforce: bool) -> Self {
360        self.enforce_enr_fork_id = enforce;
361        self
362    }
363
364    /// Configures the interval at which a random outbound peer is rotated.
365    /// Pass `None` to disable rotation.
366    pub const fn with_peer_rotation_interval(mut self, interval: Option<Duration>) -> Self {
367        self.peer_rotation_interval = interval;
368        self
369    }
370
371    /// Returns settings for testing
372    #[cfg(any(test, feature = "test-utils"))]
373    pub fn test() -> Self {
374        Self {
375            refill_slots_interval: Duration::from_millis(100),
376            backoff_durations: PeerBackoffDurations::test(),
377            ban_duration: Duration::from_millis(200),
378            peer_rotation_interval: None,
379            ..Default::default()
380        }
381    }
382}