reth_network_types/peers/
config.rs1use 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
13pub const DEFAULT_MAX_COUNT_PEERS_OUTBOUND: u32 = 100;
15
16pub const DEFAULT_MAX_COUNT_PEERS_INBOUND: u32 = 30;
18
19pub const DEFAULT_MAX_COUNT_CONCURRENT_OUTBOUND_DIALS: usize = 30;
23
24pub const INBOUND_IP_THROTTLE_DURATION: Duration = Duration::from_secs(30);
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
32pub struct PeerBackoffDurations {
33 #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
36 pub low: Duration,
37 #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
40 pub medium: Duration,
41 #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
43 pub high: Duration,
44 #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
46 pub max: Duration,
47}
48
49impl PeerBackoffDurations {
50 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 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 #[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 medium: Duration::from_secs(60 * 3),
87 high: Duration::from_secs(60 * 15),
89 max: Duration::from_secs(60 * 60),
91 }
92 }
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
97#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(default))]
98pub struct ConnectionsConfig {
99 pub max_outbound: usize,
101 pub max_inbound: usize,
103 #[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
118pub const DEFAULT_PEER_ROTATION_INTERVAL: Duration = Duration::from_mins(5);
123
124pub const PEER_ROTATION_MIN_UPTIME: Duration = Duration::from_mins(10);
126
127#[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 #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
134 pub refill_slots_interval: Duration,
135 pub trusted_nodes: Vec<TrustedPeer>,
137 #[cfg_attr(feature = "serde", serde(alias = "connect_trusted_nodes_only"))]
139 pub trusted_nodes_only: bool,
140 #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
142 pub trusted_nodes_resolution_interval: Duration,
143 pub max_backoff_count: u8,
153 #[cfg_attr(feature = "serde", serde(skip))]
155 pub basic_nodes: HashSet<NodeRecord>,
156 #[cfg_attr(feature = "serde", serde(skip))]
158 pub persisted_peers: Vec<PersistedPeerInfo>,
159 #[cfg_attr(feature = "serde", serde(with = "compact::required"))]
161 pub ban_duration: Duration,
162 #[cfg_attr(feature = "serde", serde(skip))]
164 pub ban_list: BanList,
165 pub connection_info: ConnectionsConfig,
167 pub reputation_weights: ReputationChangeWeights,
169 pub backoff_durations: PeerBackoffDurations,
173 #[cfg_attr(feature = "serde", serde(default, with = "compact::required"))]
177 pub incoming_ip_throttle_duration: Duration,
178 #[cfg_attr(feature = "serde", serde(skip))]
183 pub ip_filter: IpFilter,
184 pub enforce_enr_fork_id: bool,
189 #[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_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 pub fn with_ban_list(mut self, ban_list: BanList) -> Self {
222 self.ban_list = ban_list;
223 self
224 }
225
226 pub const fn with_ban_duration(mut self, ban_duration: Duration) -> Self {
228 self.ban_duration = ban_duration;
229 self
230 }
231
232 pub const fn with_refill_slots_interval(mut self, interval: Duration) -> Self {
234 self.refill_slots_interval = interval;
235 self
236 }
237
238 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 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 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 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 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 pub fn with_trusted_nodes(mut self, nodes: Vec<TrustedPeer>) -> Self {
274 self.trusted_nodes = nodes;
275 self
276 }
277
278 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 pub fn with_basic_nodes(mut self, nodes: HashSet<NodeRecord>) -> Self {
286 self.basic_nodes = nodes;
287 self
288 }
289
290 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 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 pub const fn with_backoff_durations(mut self, backoff_durations: PeerBackoffDurations) -> Self {
307 self.backoff_durations = backoff_durations;
308 self
309 }
310
311 pub const fn max_peers(&self) -> usize {
313 self.connection_info.max_outbound + self.connection_info.max_inbound
314 }
315
316 #[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 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 pub fn with_ip_filter(mut self, ip_filter: IpFilter) -> Self {
353 self.ip_filter = ip_filter;
354 self
355 }
356
357 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 pub const fn with_peer_rotation_interval(mut self, interval: Option<Duration>) -> Self {
367 self.peer_rotation_interval = interval;
368 self
369 }
370
371 #[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}